diff --git a/seaweed-block/README.md b/seaweed-block/README.md index b9cc163ea1..0346daff2d 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -131,6 +131,7 @@ sw-block ops chunk fork --chunk-filer --source v1 --snapshot s1 --t sw-block ops chunk detach --volume v1 --status-addr # final cut and release; resume elsewhere sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 sw-block ops chunk gc --chunk-filer --master # preview; --apply to reclaim +sw-block ops chunk verify --volume v1 --chunk-filer # read-only check of the remote image ``` `volume-delete` is refused while the volume is attached or has snapshots. diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 7942b7a517..bc15628796 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -28,7 +28,9 @@ import ( ) const ( - chunkExitFailed = 1 + chunkExitFailed = 1 + // chunkExitFindings: the command completed and found problems (verify). + chunkExitFindings = 3 defaultChunkPathCLI = "/swblock/chunks" chunkResponseLimit = 64 << 20 ) @@ -71,7 +73,7 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|verify|volume-delete|restore", false) } switch args[0] { case "gc": @@ -94,8 +96,12 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkUsage(args[1:], stdout, stderr) case "retain": return chunkRetain(args[1:], stdout, stderr) + case "verify": + return chunkVerify(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go index e9e52d078c..99dd726bf2 100644 --- a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -33,7 +33,7 @@ func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) defer f.mu.Unlock() b, ok := f.blobs[id] if !ok { - return nil, chunkstore.ErrNotFound + return nil, fmt.Errorf("%w: %w", chunkstore.ErrBlobNotFound, chunkstore.ErrNotFound) } return append([]byte(nil), b...), nil } diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go new file mode 100644 index 0000000000..4a94e2f456 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkRestore starts (or joins) the independent-restore driver of a volume +// restored from a snapshot and prints its status; with --status it only +// prints the status. The driver runs in blockvolume and outlives this call. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("restore", stderr) + var ( + volumeID, statusAddr string + statusOnly bool + ) + fs.StringVar(&volumeID, "volume", "", "restored volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go new file mode 100644 index 0000000000..2c9c32f1c2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { + var got []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { + http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) + })) + defer srv.Close() + for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { + var out, errb bytes.Buffer + if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { + t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) + } + } + if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { + t.Fatalf("requests %v: want a start, then a status-only call", got) + } + var out, errb bytes.Buffer + if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { + t.Fatal("restore without --volume must be refused") + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go new file mode 100644 index 0000000000..1d70e92f0d --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -0,0 +1,158 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkVerify: sw-block ops chunk verify --volume v --chunk-filer host:port +// checks the volume's remote image against its HEAD (and, on request, its +// snapshots), read-only (chunkstore.Catalog.Verify). Exit 0: clean; 3: the +// pass completed with findings; 1: it could not complete (the partial result +// is printed with the error); 2: usage. +func chunkVerify(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("verify", stderr) + var ( + volumeID, filer, base, snapshot, depth string + allSnapshots bool + concurrency int + bytesPerSec int64 + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + 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", "", "also check this snapshot") + fs.BoolVar(&allSnapshots, "all-snapshots", false, "also check every snapshot") + fs.StringVar(&depth, "depth", string(chunkstore.VerifyBindings), "meta, bindings or data (data reads every chunk once)") + fs.IntVar(&concurrency, "concurrency", chunkstore.DefaultVerifyConcurrency, "chunk reads in flight (depth data)") + fs.Int64Var(&bytesPerSec, "bytes-per-sec", chunkstore.DefaultVerifyBytesPerSecond, "pace chunk reads (depth data); 0 leaves them unpaced") + 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 + fs.Visit(func(f *flag.Flag) { + if f.Name == "timeout" { + timeoutSet = true + } + }) + usage := func(msg string) int { + return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + d := chunkstore.VerifyDepth(depth) + switch { + case fs.NArg() != 0: + return usage("unexpected arguments") + case volumeID == "": + return usage("--volume is required") + case d != chunkstore.VerifyMeta && d != chunkstore.VerifyBindings && d != chunkstore.VerifyData: + 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 == chunkstore.VerifyData && !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") + } + // One bound for the whole pass, the single-filer start check included: + // the deadline starts before the check. Verify writes nothing, but it + // runs the check (writes=true): against a split filer view it would + // report false findings. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog("verify", filer, base, true, timeout, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + if bytesPerSec == 0 { + bytesPerSec = -1 // the library's "unpaced" + } + res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots, + Concurrency: concurrency, BytesPerSecond: bytesPerSec}) + if err != nil { + return verifyIncomplete(res, err, stdout, stderr) + } + out, err := verifyJSON(res) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %v\n", err) + return chunkExitFailed + } + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err) + return chunkExitFailed + } + if len(res.Findings) != 0 { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings %v\n", volumeID, len(res.Findings), res.FindingsByClass) + if res.ChunksNotRead != 0 { + // READ_ERROR is not damage: those objects were not verified. + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d could not be read and were not verified; re-run\n", volumeID, res.ChunksNotRead) + } + return chunkExitFindings + } + return ops.VolumeStatusExitOK +} + +// verifyJSON is the result as one JSON object whose findings array holds +// one finding per line. +func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) { + findings := res.Findings + res.Findings = nil + head, err := json.Marshal(res) + if err != nil { + return nil, err + } + const tail = `"findings":null}` + if !bytes.HasSuffix(head, []byte(tail)) { + return nil, errors.New("verify result: unexpected field order") + } + var buf bytes.Buffer + buf.Write(head[:len(head)-len(tail)]) + buf.WriteString(`"findings":[`) + for i, f := range findings { + line, err := json.Marshal(f) + if err != nil { + return nil, err + } + if i > 0 { + buf.WriteByte(',') + } + buf.WriteByte('\n') + buf.Write(line) + } + if len(findings) > 0 { + buf.WriteByte('\n') + } + buf.WriteString("]}\n") + return buf.Bytes(), nil +} + +// verifyIncomplete prints the error body with the partial result under +// "verify", and fails. +func verifyIncomplete(res chunkstore.VerifyResult, err error, stdout, stderr io.Writer) int { + body := struct { + chunkErrBody + Verify chunkstore.VerifyResult `json:"verify"` + }{Verify: res} + body.Code, body.Message = codeInternalCLI, err.Error() + var ce *chunkstore.CatalogError + switch { + case errors.As(err, &ce): + body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable + case errors.Is(err, context.DeadlineExceeded): + body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true + } + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) + chunkResult("verify", body, nil, stdout, stderr) + return chunkExitFailed +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go new file mode 100644 index 0000000000..bdf82a3447 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -0,0 +1,229 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/url" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// verifyCLIFixture is volume v1 with two published chunks on an in-memory +// filer and blob store; it returns the store and the HEAD. +func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { + t.Helper() + ctx := context.Background() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewChunkRemote(mem, mem, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := uint64(0); idx < 2; idx++ { + data := bytes.Repeat([]byte{byte(0x30 + idx)}, 8*4096) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return mem, h +} + +func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult { + t.Helper() + var res chunkstore.VerifyResult + if err := json.Unmarshal([]byte(out), &res); err != nil || res.VolumeID == "" { + t.Fatalf("stdout is not a verify result: %q (%v)", out, err) + } + return res +} + +// verify's exit codes: 0 clean, 3 completed with findings, 1 could not +// complete, 2 usage; the result is one JSON object with one finding per line. +func TestOpsChunk_VerifyExitCodes(t *testing.T) { + mem, h := verifyCLIFixture(t) + filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} + + code, out, errs := runChunk(append([]string{"verify"}, filer...)...) + res := decodeVerify(t, out) + if code != 0 || !res.Complete || res.Depth != chunkstore.VerifyBindings || len(res.Findings) != 0 || res.ChunksChecked != 2 || + !strings.Contains(out, `"findings":[]`) || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("clean verify: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--bytes-per-sec", "0"}, filer...)...) + if res = decodeVerify(t, out); code != 0 || res.DistinctChunksRead != 2 || res.BytesRead != 2*8*4096 { + t.Fatalf("clean data verify: %d %q %q", code, out, errs) + } + + // A binding gone: completed with a finding. + own := strings.TrimPrefix(h.Chunks[1].Key, "@v1/") + if err := mem.DeleteEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own), nil); err != nil { + t.Fatal(err) + } + code, out, errs = runChunk(append([]string{"verify"}, filer...)...) + res = decodeVerify(t, out) + if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingBindingMissing || + res.FindingsByClass[chunkstore.FindingBindingMissing] != 1 || !strings.Contains(errs, "1 findings") { + t.Fatalf("verify with a missing binding: %d %q %q", code, out, errs) + } + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 3 || !strings.HasPrefix(lines[1], `{"volume":"v1"`) || !strings.Contains(lines[1], `"class":"BINDING_MISSING"`) || lines[2] != "]}" { + t.Fatalf("findings are not one per line:\n%s", out) + } + + // Could not complete: the error body, with what was covered. + code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) || + !strings.Contains(out, `"incomplete":"error"`) { + t.Fatalf("verify of a missing volume: %d %q", code, out) + } + + for _, args := range [][]string{ + {"verify", "--chunk-filer", "f:1"}, // no volume + {"verify", "--volume", "v1"}, // no filer + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "all"}, // bad depth + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"}, // data without --timeout + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--snapshot", "s1", "--all-snapshots"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--concurrency", "0"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bytes-per-sec", "-1"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "extra"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bogus"}, + } { + code, out, _ := runChunk(args...) + if code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI { + t.Fatalf("%v: exit %d %q; want 2 and bad_request", args, code, out) + } + } + if code, out, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"); !strings.Contains(out, "--timeout") { + t.Fatalf("data without --timeout: %d %q; want the reason", code, out) + } +} + +// unreadableStore fails every read of one needle with an error that is not +// "not found" (a volume server answering 503). +type unreadableStore struct { + *manifestFixtureFiler + fid string +} + +func (s unreadableStore) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == s.fid { + return nil, fmt.Errorf("chunkstore: read %s: http 503 from volume:8080", fid) + } + return s.manifestFixtureFiler.Get(ctx, fid) +} + +// A chunk that cannot be read is READ_ERROR (not verified), and the pass +// exits 3: it did not verify everything. +func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) { + mem, h := verifyCLIFixture(t) + own := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + e, err := mem.LookupEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own)) + if err != nil { + t.Fatal(err) + } + store := unreadableStore{mem, string(e.Extended["swb.fid"])} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") + res := decodeVerify(t, out) + if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError || + res.ChunksNotRead != 1 || res.ReadRetries != 2 || !strings.Contains(errs, "not verified") { + t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs) + } +} + +// verify writes nothing, yet it is in the set that runs the single-filer +// start check (a split filer view would give false findings), and it refuses +// the way the writing commands do (TestOpsChunk_WritingCommandsRunTheSingleFilerCheck). +func TestOpsChunk_VerifyRunsTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + for name, args := range map[string][]string{ + "verify": append([]string{"ops", "chunk", "verify", "--volume", "v1"}, filer...), + "verify --depth data": append([]string{"ops", "chunk", "verify", "--volume", "v1", "--depth", "data", "--timeout", "10s"}, filer...), + } { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } +} + +// The start check runs within verify's --timeout, as for the writing +// commands (TestOpsChunk_StartCheckIsBoundedByTheTimeout): a check stalled on +// its filer or master ends verify at the timeout, as a retryable refusal. +func TestOpsChunk_VerifyStartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + args := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--timeout", "200ms"} + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("a stalled start check held verify past its 200ms --timeout") + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("verify: exit %d, out %q; want a retryable remote_unavailable refusal", code, out.String()) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 06f94c6ee8..f1f9d8dc0c 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -2297,6 +2297,8 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--snapshot |--all-snapshots] [--depth meta|bindings|data]") + fmt.Fprintln(w, " [--concurrency 2] [--bytes-per-sec 33554432] [--timeout ] (read-only; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") fmt.Fprintln(w, " sw-block ops workspace force-move --master --volume --target-host --target-data --target-ctrl --request-id --confirm-forced @ [--dry-run]") fmt.Fprintln(w, " sw-block ops workspace lost-range --master --volume [--request-id ] (authority only; no bypass: see `sw-block ops workspace help`)") diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 7d35415762..ce19c81325 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "runtime" "strings" "sync" "sync/atomic" @@ -911,7 +912,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { case werr = <-writersDone: writersDone <- werr // keep it for the cleanup join case <-time.After(20 * time.Second): - t.Fatal("deadlock: writers did not finish after the release") + t.Fatal("deadlock: writers did not finish after the release", allGoroutineStacks()) } if werr != nil { t.Fatal("writer:", werr) @@ -919,7 +920,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-closed: case <-time.After(20 * time.Second): - t.Fatal("deadlock: Close did not finish after the release") + t.Fatal("deadlock: Close did not finish after the release", allGoroutineStacks()) } time.Sleep(50 * time.Millisecond) // renewals continue after Close stopRenewers() @@ -928,7 +929,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-settled: case <-time.After(20 * time.Second): - t.Fatal("deadlock: renewers did not finish") + t.Fatal("deadlock: renewers did not finish", allGoroutineStacks()) } if s := time.Duration(slowest.Load()); s >= 2*time.Second { @@ -1218,3 +1219,16 @@ func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { t.Fatal(e) } } + +// allGoroutineStacks returns the stack of every goroutine on a new line, so +// that a stall reported by a test shows where each party is blocked. +func allGoroutineStacks() string { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + return string('\n') + string(buf[:n]) + } + buf = make([]byte, 2*len(buf)) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 8a3ad3bb9f..c3b5a5c883 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -103,3 +103,161 @@ This test requires the binary and fails rather than skips when it is absent. It 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). diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index dcd18a41c2..ade786fa78 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -252,6 +252,11 @@ type SnapshotRequest struct { // SourceReadAt is when the caller obtained the HEAD it snapshots (the // cut's return); OpDeadline counts from it. Zero means now. SourceReadAt time.Time + // ShareToken is the ShareGuard token of a caller that began the share + // before it obtained the HEAD (the owner's seal: Begin, then the cut). + // Empty: CreateSnapshot begins the share itself and refuses a HEAD that + // is no longer current. Unused without a guard; never stored. + ShareToken string } // ListOptions pages a snapshot listing. @@ -297,6 +302,8 @@ type Catalog struct { // retainHook, when set, runs at the named stages of a Retain pass (a // test seam for interleavings; see hookPlanned). retainHook func(stage, name string) + // guard, when set, is told about every share of a volume's chunks. + guard ShareGuard } // NewCatalog returns the catalog for the chunk base directory base (the @@ -887,6 +894,12 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) } } + shareToken := req.ShareToken + if shareToken == "" { + if shareToken, err = c.beginShare(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } + } // Take the name: this request's record, or an earlier attempt's of it. attempt, err := c.claimName(ctx, vol, root, req, head.Gen) @@ -947,6 +960,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline()) } dir := path.Join(root, snapsDir, req.Name) + if err := c.finishShare(ctx, vol, shareToken, head); err != nil { + // Clean abort: the snapshot entry was never sent. + c.dropIntent(ctx, root, id) + return SnapshotInfo{}, err + } pctx, cancel := c.publishCtx(ctx, deadline) outcome, got, cerr := c.createResolved(ctx, pctx, dir, e, attempt) cancel() @@ -1267,6 +1285,12 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For // readAt + deadline, the last moment this fork can publish // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() + var shareToken string + if c.guard != nil { // the shared HEAD is the snapshot's, read below + if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil { + return ForkResult{}, remoteErr(err, "share guard for %s", req.Source) + } + } snap, err := c.readForkParent(ctx, req) if err != nil { return ForkResult{}, err @@ -1352,6 +1376,11 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For c.dropIntent(ctx, dstRoot, id) return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline()) } + if err := c.finishShare(ctx, req.Source, shareToken, src); err != nil { + // Clean abort: HEAD was never sent. + c.dropIntent(ctx, dstRoot, id) + return ForkResult{}, err + } // Under this request's VOLUME only this request's attempts write HEAD // (attach refuses a fork without HEAD), so a HEAD found there completes // the fork; if it is another attempt's and this create is unsettled, diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index a127f5a2d7..8462cfad23 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -236,6 +236,32 @@ func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { return r.b.Get(ctx, fid) } +// ReclaimKey deletes the needle bound to one of this volume's own keys +// with GC's step (reclaimBinding): the binding is tombstoned, the exact fid +// deleted, the binding kept for ever and marked done. It decides nothing: +// the caller must know that no HEAD, snapshot, fork or intent references +// key. An owner-qualified key is refused. +func (r *ChunkRemote) ReclaimKey(ctx context.Context, key string, blobs BlobDeleter) error { + if err := storage.ValidChunkKey(key); err != nil { + return fmt.Errorf("%w: %v", ErrInvalidKey, err) + } + if strings.HasPrefix(key, "@") { + return fmt.Errorf("%w: %q is owner-qualified; a volume reclaims only its own keys", ErrInvalidKey, key) + } + name, err := keyName(key) + if err != nil { + return err + } + e, err := r.f.LookupEntry(ctx, r.keyDir(), name) + if err != nil { + return fmt.Errorf("chunkstore: chunk key %q: %w", key, err) + } + if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { + return fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) + } + return reclaimBinding(ctx, r.f, blobs, r.keyDir(), e) +} + // Delete is not supported; see ErrDeleteUnsupported. func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 9f3ddcfb15..adfcc42ed1 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -256,7 +256,7 @@ func (b *fakeBlobs) Get(_ context.Context, fid string) ([]byte, error) { b.gets++ d, ok := b.data[fid] if !ok { - return nil, errors.New("fake: no such fid " + fid) + return nil, fmt.Errorf("fake: no such fid %s: %w", fid, ErrBlobNotFound) } return append([]byte(nil), d...), nil } diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index d46175a8cf..2416e85f58 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -392,24 +392,11 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e if err = ctx.Err(); err != nil { return result, err } - // Preserve the immutable binding forever: removing it would allow Put - // to rebind a key that once existed. The tombstone also permits retry - // after a failed physical delete without losing the fid. - if string(b.entry.Extended[extGCDeleted]) != "1" { - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("1") - expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: b.entry.Extended[extFid], extGCDeleted: nil} - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, expected); err != nil { - return result, err - } + err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry) + if err != nil && ctx.Err() != nil { + err = ctx.Err() } - if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { - if ctx.Err() != nil { - return result, ctx.Err() - } - if !errors.Is(err, ErrBlobDeleteRejected) { - return result, err - } + if errors.Is(err, ErrBlobDeleteRejected) { // INV-GC-DELETE-PROGRESS-001: a confirmed object rejection // must not starve later candidates or invalidate a complete mark. // Keep the fid/tombstone and retry; never record this object done. @@ -419,9 +406,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e nextCandidates[p] = candidate continue } - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("done") - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, map[string][]byte{extFid: b.entry.Extended[extFid], extGCDeleted: []byte("1")}); err != nil { + if err != nil { return result, err } result.Reclaimed++ @@ -463,6 +448,34 @@ func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { return reader.Get(ctx, fid) } +// reclaimBinding deletes the needle a key binding names, keeping the binding +// for ever: removing it would allow Put to rebind a key that once existed. +// The binding first gets a conditional swb.gc.deleted=1 tombstone (which +// also lets a failed physical delete be retried without losing the fid), +// then the exact fid is deleted, then the tombstone becomes done. A binding +// already done is left as it is. The caller decides that nothing references +// the key. +func reclaimBinding(ctx context.Context, f Filer, blobs BlobDeleter, dir string, entry *filerpb.Entry) error { + switch string(entry.Extended[extGCDeleted]) { + case "done": + return nil + case "1": + default: + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("1") + expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: entry.Extended[extFid], extGCDeleted: nil} + if err := f.UpdateEntry(ctx, dir, e, expected); err != nil { + return err + } + } + if err := blobs.DeleteBlob(ctx, string(entry.Extended[extFid])); err != nil { + return err + } + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("done") + return f.UpdateEntry(ctx, dir, e, map[string][]byte{extFid: entry.Extended[extFid], extGCDeleted: []byte("1")}) +} + // INV-GC-CLOCK-SKEW-001: expiry uses a lower bound on elapsed time, // never the raw difference of timestamps from different hosts. Subtracting // separately avoids overflowing grace + skew for large configured durations. diff --git a/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go new file mode 100644 index 0000000000..25acbb33d0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go @@ -0,0 +1,47 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ReclaimKey is GC's step for one own key: the binding is tombstoned and +// kept, the needle deleted; repeating it is a no-op; a qualified key is +// refused. +func TestChunkRemote_ReclaimKey(t *testing.T) { + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, catBase+"/v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := r.Put(ctx, "k1", []byte("payload")); err != nil { + t.Fatal(err) + } + fid := r.fids["k1"] + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, r.keyDir(), "k1") + if err != nil { + t.Fatalf("binding removed: %v", err) + } + if string(e.Extended[extGCDeleted]) != "done" || string(e.Extended[extFid]) != fid { + t.Fatalf("binding after reclaim: %q fid %q; want done, same fid", e.Extended[extGCDeleted], e.Extended[extFid]) + } + if _, err := b.Get(ctx, fid); err == nil { + t.Fatal("needle still readable after reclaim") + } + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatalf("repeated reclaim: %v", err) + } + if err := r.Put(ctx, "k1", []byte("again")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a reclaimed key: %v", err) + } + if err := r.ReclaimKey(ctx, "@v0/k1", gcBlobs{b}); err == nil { + t.Fatal("reclaim of an owner-qualified key accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/remote.go b/seaweed-block/core/frontend/chunkstore/remote.go index 78dd8dd4b9..cd8e87f18a 100644 --- a/seaweed-block/core/frontend/chunkstore/remote.go +++ b/seaweed-block/core/frontend/chunkstore/remote.go @@ -40,7 +40,9 @@ type Blobs interface { // Put stores data as a new needle and returns its fid. A fid is never // reused, so a Put can never overwrite data another manifest references. Put(ctx context.Context, data []byte) (fid string, err error) - // Get returns the whole needle payload. + // Get returns the whole needle payload. When the store reports the + // needle absent (not merely unreachable), the error wraps + // ErrBlobNotFound. Get(ctx context.Context, fid string) ([]byte, error) } @@ -54,4 +56,8 @@ var ( // ErrInvalidKey: a chunk key is malformed, or names an owner that is // not a plain volume id, or is qualified where only own keys are allowed. ErrInvalidKey = errors.New("chunkstore: invalid chunk key") + // ErrBlobNotFound: the blob store answered that the needle does not + // exist (SWFS: HTTP 404 from every location). A timeout, a refused + // connection or any other status is not this error. + ErrBlobNotFound = errors.New("chunkstore: needle not found") ) diff --git a/seaweed-block/core/frontend/chunkstore/share_guard.go b/seaweed-block/core/frontend/chunkstore/share_guard.go new file mode 100644 index 0000000000..1f4ba19c7c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard.go @@ -0,0 +1,61 @@ +package chunkstore + +import ( + "context" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ShareGuard is told about every sharer of a volume's chunks. A snapshot or +// fork calls Begin before it obtains the HEAD it will reference, and Finish, +// with that HEAD, right before it activates its result; an error from either +// aborts the share before anything is activated. A token Begin returned and +// nobody finished is the guard's to expire. +// +// No guard (the default) changes nothing: no call is made and no check is +// added. +type ShareGuard interface { + Begin(ctx context.Context, vol string) (token string, err error) + Finish(ctx context.Context, vol, token string, head storage.ChunkHead) error +} + +// SetShareGuard installs g (nil removes it). Set it before the catalog is +// used. +func (c *Catalog) SetShareGuard(g ShareGuard) { c.guard = g } + +// ShareGuard returns the installed guard, or nil. +func (c *Catalog) ShareGuard() ShareGuard { return c.guard } + +// beginShare starts a share of vol's chunks for a caller that passes the +// HEAD in: with a guard, it begins the share, then refuses unless head is +// still vol's current HEAD (a share that obtained an older HEAD could +// reference chunks superseded meanwhile). token is "" without a guard. +func (c *Catalog) beginShare(ctx context.Context, vol string, head storage.ChunkHead) (token string, err error) { + if c.guard == nil { + return "", nil + } + token, err = c.guard.Begin(ctx, vol) + if err != nil { + return "", remoteErr(err, "share guard for %s", vol) + } + cur, ok, err := c.ReadHead(ctx, vol) + if err != nil { + return "", err + } + if !ok || cur.Gen != head.Gen || cur.Epoch != head.Epoch { + return "", catErr(CodeOutcomeUnknown, true, nil, "volume %s: the HEAD to share (gen %d) is no longer current (gen %d); retry", vol, head.Gen, cur.Gen) + } + return token, nil +} + +// finishShare finishes a share before its result is activated; no-op +// without a guard. +func (c *Catalog) finishShare(ctx context.Context, vol, token string, head storage.ChunkHead) error { + if c.guard == nil { + return nil + } + if err := c.guard.Finish(ctx, vol, token, head); err != nil { + return remoteErr(err, "share guard for %s refused the share", vol) + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/share_guard_test.go b/seaweed-block/core/frontend/chunkstore/share_guard_test.go new file mode 100644 index 0000000000..a0f7661520 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard_test.go @@ -0,0 +1,204 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// recGuard records Begin and Finish; onFinish runs inside Finish. +type recGuard struct { + mu sync.Mutex + events []string + n int + finishErr error + beginErr error + onFinish func() +} + +func (g *recGuard) Begin(_ context.Context, vol string) (string, error) { + g.mu.Lock() + defer g.mu.Unlock() + g.n++ + g.events = append(g.events, "begin:"+vol) + if g.beginErr != nil { + return "", g.beginErr + } + return fmt.Sprintf("tok-%d", g.n), nil +} + +func (g *recGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + if g.onFinish != nil { + g.onFinish() + } + g.mu.Lock() + defer g.mu.Unlock() + g.events = append(g.events, fmt.Sprintf("finish:%s:%s:%d", vol, token, head.Gen)) + return g.finishErr +} + +func (g *recGuard) list() []string { + g.mu.Lock() + defer g.mu.Unlock() + return append([]string(nil), g.events...) +} + +func countUnder(f *fakeFiler, prefix string) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for k := range f.entries { + if strings.HasPrefix(k, prefix) { + n++ + } + } + return n +} + +// A snapshot of a passed-in HEAD begins the share, checks the HEAD is still +// current, and finishes it before the snapshot entry is written. +func TestShareGuard_SnapshotFinishesBeforeActivation(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + g := &recGuard{} + g.onFinish = func() { + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Errorf("snapshot entry written before Finish (%d entries)", n) + } + } + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + if countUnder(f, catBase+"/v1/snaps/s1/") == 0 { + t.Fatal("snapshot not written after a successful Finish") + } +} + +// A refused Finish aborts the snapshot: nothing activated, its intent dropped. +func TestShareGuard_RefusedFinishAbortsTheSnapshot(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + intents := countUnder(f, catBase+"/v1/intents/") + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot activated after a refused Finish") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Finish", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d; want the snapshot's intent dropped", intents, n) + } +} + +// A passed-in HEAD that is no longer current is refused before Finish. +func TestShareGuard_StaleHeadIsRefused(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + publishSource(t, f, b, "v1", map[uint64][]byte{5: chunkBytes(0x20)}) // HEAD moves on + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot of a superseded HEAD accepted with a guard") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish called for a refused share: %v", g.list()) + } + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries for a refused share", n) + } +} + +// A caller that began the share itself passes its token: no second Begin. +func TestShareGuard_CallerToken(t *testing.T) { + _, _, c, h := catalogFixture(t) + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r", ShareToken: "owner-tok"}, h); err != nil { + t.Fatal(err) + } + if got := g.list(); len(got) != 1 || got[0] != fmt.Sprintf("finish:v1:owner-tok:%d", h.Gen) { + t.Fatalf("guard events %v; want only Finish with the caller's token", got) + } +} + +// A fork begins the share before reading the snapshot and finishes it with +// the snapshot's HEAD before writing the child's HEAD; a refused Finish +// writes no child HEAD. +func TestShareGuard_Fork(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + g := &recGuard{} + g.onFinish = func() { + if countUnder(f, catBase+"/v2/HEAD") != 0 { + t.Error("child HEAD written before Finish") + } + } + c.SetShareGuard(g) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "fork-2"}); err == nil { + t.Fatal("fork activated after a refused Finish") + } + if countUnder(f, catBase+"/v3/HEAD") != 0 { + t.Fatal("child HEAD written after a refused Finish") + } + if n := countUnder(f, catBase+"/v3/intents/"); n != 0 { + t.Fatalf("%d intents left for the refused fork; want its new intent dropped", n) + } +} + +// A refused Begin stops the snapshot and the fork before anything is +// written: no Finish, no snapshot entry, no child HEAD, no intent left. +func TestShareGuard_BeginRefused(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil { + t.Fatal(err) + } + intents := countUnder(f, catBase+"/v1/intents/") + g := &recGuard{beginErr: errors.New("share refused")} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Begin", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d after a refused Begin", intents, n) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v4", RequestID: "fork-b"}); err == nil { + t.Fatal("fork after a refused Begin") + } + if countUnder(f, catBase+"/v4/HEAD") != 0 || countUnder(f, catBase+"/v4/intents/") != 0 { + t.Fatal("a fork refused at Begin wrote a child HEAD or an intent") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish after a refused Begin: %v", g.list()) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index a126d1a998..067c9e9850 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -224,30 +224,77 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) { } // Get implements Blobs: resolve the fid's volume through the filer, then GET -// the needle from each location until one answers. +// the needle from each location until one answers. The needle is reported +// absent (ErrBlobNotFound) only when every location of a fresh lookup +// answers 404: cached locations can be stale after a volume moves, so their +// 404s are followed by one fresh lookup. func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { vid, _, ok := strings.Cut(fid, ",") if !ok { return nil, fmt.Errorf("chunkstore: bad fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, cached, err := c.lookupVolume(ctx, vid) if err != nil { return nil, err } - var lastErr error - for _, host := range urls { - b, err := c.getFrom(ctx, host, fid) - if err == nil { - return b, nil - } - lastErr = err + b, allNotFound, lastErr := c.getFromAll(ctx, urls, fid) + if lastErr == nil { + return b, nil } c.mu.Lock() delete(c.vidCache, vid) c.mu.Unlock() + if allNotFound && cached { + if urls, _, err = c.lookupVolume(ctx, vid); err != nil { + return nil, err + } + if b, allNotFound, lastErr = c.getFromAll(ctx, urls, fid); lastErr == nil { + return b, nil + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + } + if allNotFound { + lastErr = &blobNotFoundError{lastErr} + } return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) } +// getFromAll tries each location in turn. On failure lastErr is the last +// location's error and allNotFound whether every location answered 404. +func (c *SWFS) getFromAll(ctx context.Context, urls []string, fid string) (b []byte, allNotFound bool, lastErr error) { + allNotFound = true + for _, host := range urls { + b, err := c.getFrom(ctx, host, fid) + if err == nil { + return b, false, nil + } + lastErr = err + var se *blobStatusError + if !errors.As(err, &se) || se.code != http.StatusNotFound { + allNotFound = false + } + } + return nil, allNotFound && lastErr != nil, lastErr +} + +// blobStatusError is a volume server's non-200 answer to a needle GET. +type blobStatusError struct { + code int + host string +} + +func (e *blobStatusError) Error() string { return fmt.Sprintf("http %d from %s", e.code, e.host) } + +// blobNotFoundError marks a read every location answered 404: it reads as +// the last location's error and matches ErrBlobNotFound. +type blobNotFoundError struct{ err error } + +func (e *blobNotFoundError) Error() string { return e.err.Error() } +func (e *blobNotFoundError) Unwrap() error { return e.err } +func (e *blobNotFoundError) Is(target error) bool { return target == ErrBlobNotFound } + func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+host+"/"+fid, nil) if err != nil { @@ -259,21 +306,23 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d from %s", resp.StatusCode, host) + return nil, &blobStatusError{code: resp.StatusCode, host: host} } return io.ReadAll(resp.Body) } -func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { +// lookupVolume returns vid's locations; cached reports that they came from +// the cache rather than a lookup made now. +func (c *SWFS) lookupVolume(ctx context.Context, vid string) (urls []string, cached bool, err error) { c.mu.Lock() urls, ok := c.vidCache[vid] c.mu.Unlock() if ok && len(urls) > 0 { - return urls, nil + return urls, true, nil } resp, err := c.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}}) if err != nil { - return nil, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) + return nil, false, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) } for _, l := range resp.GetLocationsMap()[vid].GetLocations() { if l.GetUrl() != "" { @@ -281,12 +330,12 @@ func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { } } if len(urls) == 0 { - return nil, fmt.Errorf("chunkstore: volume %s has no locations", vid) + return nil, false, fmt.Errorf("chunkstore: volume %s has no locations", vid) } c.mu.Lock() c.vidCache[vid] = urls c.mu.Unlock() - return urls, nil + return urls, false, nil } var ( @@ -303,7 +352,7 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") { return fmt.Errorf("chunkstore: bad deletion fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, _, err := c.lookupVolume(ctx, vid) if err != nil { return err } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_test.go b/seaweed-block/core/frontend/chunkstore/swfs_test.go index 748681e3a8..b26eedeafa 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_test.go @@ -32,6 +32,7 @@ type fakeFilerGRPC struct { lookupErr error assignResp *filerpb.AssignVolumeResponse lookupVol *filerpb.LookupVolumeResponse + volLookups int // LookupVolume calls lastCreate *filerpb.CreateEntryRequest lastUpdate *filerpb.UpdateEntryRequest @@ -80,6 +81,7 @@ func (f *fakeFilerGRPC) AssignVolume(_ context.Context, r *filerpb.AssignVolumeR func (f *fakeFilerGRPC) LookupVolume(_ context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) { f.mu.Lock() defer f.mu.Unlock() + f.volLookups++ return f.lookupVol, nil } diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go new file mode 100644 index 0000000000..0c11116d75 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -0,0 +1,1633 @@ +package chunkstore + +// Verify: a read-only check of one volume's remote image against what its +// HEAD (and, on request, its snapshots) say. It writes nothing to the filer +// or the blob store: no intent, no mark, no tombstone, no binding. +// +// Depths, each including the one before: +// +// - meta: the HEAD root decodes and is self-consistent; its geometry +// matches VOLUME; a snapshot's document names the volume and the +// snapshot it was found under; every segment a selected root names is +// readable and passes its SHA-256 and strict decode; a fork's record +// matches the parent snapshot it was made from. References to one +// chunk with different SHA-256s disagree (CONTENT_MISMATCH). +// - bindings (the default): every chunk key a selected root references +// has a sound binding in its owner's keys/ (one listing per owner), +// not tombstoned by GC. +// - data: every distinct chunk (owner + key, across all selected roots) +// is fetched once; its length must be the chunk size and its SHA-256 +// each reference's (the rule the chunk layer applies on a read miss). +// +// The pass runs beside a live owner and beside GC, so what it reports about +// chunks comes from a small automaton (the V.* names on the functions): +// +// - V.Discover: an object (a chunk or a segment, by owner and key) a root +// view names that the pass has not seen is queued for one check; every +// reference met is recorded as seen, with nothing judged about it. +// - V.Settle: the check records the object's one outcome (its content, or +// binding missing or tombstoned, needle missing, read error) and reports +// nothing; a settled object is never checked again. +// - V.Refresh: HEAD is read again at least every RefreshInterval; a newer +// generation replaces the HEAD view (an older one is ignored), the keys +// the old view named and the new one does not are marked dropped, and +// its new keys are discovered. +// - V.Round: once every queued chunk is settled, one closing read of HEAD +// and of each selected snapshot's state; if it names a chunk not seen, +// the pass checks it and reads again, at most ClosingRounds times +// (V.GiveUp: then the pass is incomplete). +// - V.Close: a closing read that names no chunk not seen is the final view. +// Only a decodable HEAD, not older than the view, can close a pass as +// complete: a closing read that finds no HEAD, or one that does not +// decode (ROOT_INVALID), leaves no HEAD root and the pass incomplete. +// - V.Reconcile: the findings and counters are computed from the outcomes, +// the references seen and the final view alone, nowhere else. Judge, a +// pure function of an object's outcome and one reference, gives the +// outcome when it is bad, else CONTENT_MISMATCH (another hash), +// SIZE_MISMATCH (a chunk not a chunk long) or SEGMENT_UNREADABLE (a +// segment that does not decode under that reference's fields), else +// sound. Per object and class Judge gives a final reference: one finding, +// under the first final root having one (HEAD, then the snapshots not +// gone, in order) at its first such index. An object with a problem +// under any reference seen, and no finding, is counted once. A key HEAD +// dropped and names again is ROOT_INVALID, whatever its outcome. +// +// The pass therefore reports the state of each named chunk at its check, +// for the roots at the final read; a chunk damaged after its check is the +// next pass's finding. A chunk that left HEAD can be collected after GC's +// grace, and a deleted snapshot's chunks are kept only for the grace, so an +// object that no root names at the final read is not a finding. +// +// A needle is NEEDLE_MISSING only when the store reports it absent +// (ErrBlobNotFound). Any other read failure is retried; if it persists it is +// READ_ERROR, which means "not verified", not "damaged". +// +// A finding never stops the pass. Only an inability to continue does (the +// context ended, the filer failed) or a HEAD that keeps naming new chunks: +// Verify then returns the result with Complete false and the reason in +// Incomplete, the findings computed from what was checked, and the error. + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// VerifyDepth selects how far Verify checks. +type VerifyDepth string + +const ( + VerifyMeta VerifyDepth = "meta" + VerifyBindings VerifyDepth = "bindings" + VerifyData VerifyDepth = "data" +) + +const ( + // DefaultVerifyConcurrency bounds the chunk reads in flight. + DefaultVerifyConcurrency = 2 + // DefaultVerifyBytesPerSecond paces chunk reads. + DefaultVerifyBytesPerSecond int64 = 32 << 20 + // DefaultVerifyRefresh is the longest a pass works from one HEAD view; + // it stays below the operation deadline, the shortest time a chunk + // that just left HEAD is still guaranteed to be kept by GC. + DefaultVerifyRefresh = 2 * time.Minute + // DefaultVerifyIntentStaleAge is the age past which a capture intent + // below HEAD's epoch is reported as stale (the gc --intent-ttl default). + DefaultVerifyIntentStaleAge = time.Hour + // DefaultVerifyClosingRounds is the default ClosingRounds. + DefaultVerifyClosingRounds = 3 +) + +// Finding classes. +const ( + FindingRootInvalid = "ROOT_INVALID" + FindingGeometry = "GEOMETRY" + FindingSegmentUnreadable = "SEGMENT_UNREADABLE" + FindingBindingMissing = "BINDING_MISSING" + FindingBindingTombstoned = "BINDING_TOMBSTONED" + FindingNeedleMissing = "NEEDLE_MISSING" + FindingContentMismatch = "CONTENT_MISMATCH" + FindingSizeMismatch = "SIZE_MISMATCH" + FindingForkRecordMismatch = "FORK_RECORD_MISMATCH" + FindingIntentStale = "INTENT_STALE" + // FindingReadError is not proof of damage: a needle (chunk or segment) + // could not be read for a reason other than the store reporting it + // absent, after retries. That object was not verified; re-run. + FindingReadError = "READ_ERROR" +) + +// A read the store does not answer with "not found" is tried this many +// times in all, the retries spaced by verifyRetryBackoff times the attempt. +const verifyReadAttempts = 3 + +var verifyRetryBackoff = 50 * time.Millisecond + +// VerifyOptions configures a Verify pass. Zero values take the defaults. +type VerifyOptions struct { + // Depth is meta, bindings (default) or data. + Depth VerifyDepth + // Snapshot adds the named snapshot to the roots checked; AllSnapshots + // adds every published snapshot not marked deleting. HEAD is always + // checked. At most one of the two may be set. + Snapshot string + AllSnapshots bool + // Concurrency bounds the chunk reads in flight (depth data). + Concurrency int + // BytesPerSecond paces chunk reads: 0 is the default, a negative value + // leaves them unpaced. + BytesPerSecond int64 + // RefreshInterval is the longest the pass works from one HEAD view. + RefreshInterval time.Duration + // IntentStaleAge is the age past which a capture intent below HEAD's + // epoch that names no key HEAD references is reported (a hint only). + IntentStaleAge time.Duration + // ClosingRounds bounds the closing reads that may name chunks not seen + // before; past it the pass is incomplete. + ClosingRounds int + + // hook, when set, runs at the named stages of a pass (a test seam). + hook func(stage string) +} + +// Verify stages passed to the hook. +const ( + verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked + verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too + verifyHookBatchChecked = "batch-checked" // a batch of checks has settled + verifyHookClosingRead = "closing-read" // a closing read is about to be made + verifyHookClosed = "closed" // the quiet closing read was made: the final view is fixed +) + +// VerifyIncomplete is why a pass did not complete. +type VerifyIncomplete string + +const ( + VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed + VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled + VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks + VerifyIncompleteHeadAbsent VerifyIncomplete = "head_absent" // the closing read found no HEAD + VerifyIncompleteHeadInvalid VerifyIncomplete = "head_invalid" // the closing read's HEAD does not decode + VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request +) + +// CodeVerifyIncomplete: the closing reads could not close the pass (each +// named chunks not seen before, or the last found no usable HEAD). +const CodeVerifyIncomplete = "verify_incomplete" + +// VerifyFinding is one problem found. Segment is set for a segment's own +// problem, Index for a chunk's. +type VerifyFinding struct { + Volume string `json:"volume"` + Root string `json:"root"` + Segment *uint64 `json:"segment,omitempty"` + Index *uint64 `json:"index,omitempty"` + Owner string `json:"owner,omitempty"` + Key string `json:"key,omitempty"` + FID string `json:"fid,omitempty"` + Class string `json:"class"` + Detail string `json:"detail"` +} + +// VerifyResult is a pass's summary and findings. Complete is false when the +// pass could not finish (Incomplete says why); the counters and findings +// then cover what it checked. +type VerifyResult struct { + VolumeID string `json:"volumeID"` + Depth VerifyDepth `json:"depth"` + Complete bool `json:"complete"` + // Incomplete is why the pass did not complete ("" when it did). + Incomplete VerifyIncomplete `json:"incomplete,omitempty"` + // HeadGens are the HEAD generations the pass read, in order; the last + // is the final view's. + HeadGens []uint64 `json:"headGens"` + // Snapshots are the snapshots checked, as name/attempt. + Snapshots []string `json:"snapshots"` + // SegmentsChecked counts segment references checked (per root walked); + // SegmentReads the segment objects actually read. + SegmentsChecked int `json:"segmentsChecked"` + SegmentReads int `json:"segmentReads"` + // ChunksChecked counts the chunk references (root, index) of the final + // view; DistinctChunks the distinct chunks (owner, key) the pass saw. + ChunksChecked int `json:"chunksChecked"` + DistinctChunks int `json:"distinctChunks"` + // DistinctChunksRead and BytesRead count the chunk data read. + DistinctChunksRead int `json:"distinctChunksRead"` + BytesRead int64 `json:"bytesRead"` + // SupersededDuringVerify counts the chunks and segments that had a bad + // outcome or a problem under a reference seen during the pass, yet yield + // no finding (no final reference has a problem), once each; + // RootDeletedDuringVerify counts instead those whose problem reference + // was carried by a selected snapshot deleted during the pass. + SupersededDuringVerify int `json:"supersededDuringVerify"` + RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` + // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked + // snapshots gone at the final read: they are not fully covered. + SnapshotsDeletedDuringVerify []string `json:"snapshotsDeletedDuringVerify"` + // ForkSourceGone: this volume is a fork whose source volume no longer + // exists, so its fork record could not be compared with the parent + // snapshot. Not a finding. + ForkSourceGone bool `json:"forkSourceGone,omitempty"` + // ChunksNotRead counts the READ_ERROR findings: chunks or segments that + // could not be read, so were not verified. ReadRetries counts the + // retried reads. + ChunksNotRead int `json:"chunksNotRead"` + ReadRetries int `json:"readRetries"` + FindingsByClass map[string]int `json:"findingsByClass"` + Findings []VerifyFinding `json:"findings"` +} + +// Verify checks vol's remote image at opts.Depth; see the top of this file. +func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (VerifyResult, error) { + res := VerifyResult{VolumeID: vol, HeadGens: []uint64{}, Snapshots: []string{}, SnapshotsDeletedDuringVerify: []string{}, + FindingsByClass: map[string]int{}, Findings: []VerifyFinding{}} + refuse := func(err error) (VerifyResult, error) { + res.Incomplete = VerifyIncompleteError + return res, err + } + if opts.Depth == "" { + opts.Depth = VerifyBindings + } + res.Depth = opts.Depth + if opts.Depth != VerifyMeta && opts.Depth != VerifyBindings && opts.Depth != VerifyData { + return refuse(catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth)) + } + if opts.Snapshot != "" && opts.AllSnapshots { + return refuse(catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine")) + } + if opts.Snapshot != "" { + if err := CheckSnapshotName(opts.Snapshot); err != nil { + return refuse(err) + } + } + if opts.Concurrency <= 0 { + opts.Concurrency = DefaultVerifyConcurrency + } + if opts.BytesPerSecond == 0 { + opts.BytesPerSecond = DefaultVerifyBytesPerSecond + } + if opts.RefreshInterval <= 0 { + opts.RefreshInterval = DefaultVerifyRefresh + } + if opts.IntentStaleAge <= 0 { + opts.IntentStaleAge = DefaultVerifyIntentStaleAge + } + if opts.ClosingRounds <= 0 { + opts.ClosingRounds = DefaultVerifyClosingRounds + } + root, err := c.volRoot(vol) + if err != nil { + return refuse(err) + } + v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, + segs: map[string]*verifySegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, + seenChunks: map[string]map[seenChunk]bool{}, seenSegs: map[string]map[seenSeg]bool{}, + pacer: &verifyPacer{rate: opts.BytesPerSecond}} + err = v.run(ctx) + v.reconcile() + sort.SliceStable(res.Findings, func(i, j int) bool { return findingLess(res.Findings[i], res.Findings[j]) }) + for _, f := range res.Findings { + res.FindingsByClass[f.Class]++ + } + res.DistinctChunks = len(v.chunks) + if err != nil { + switch { + case errors.Is(err, errVerifyHeadAbsent): + res.Incomplete = VerifyIncompleteHeadAbsent + case errors.Is(err, errVerifyHeadInvalid): + res.Incomplete = VerifyIncompleteHeadInvalid + case CodeOf(err) == CodeVerifyIncomplete: + res.Incomplete = VerifyIncompleteRounds + case errors.Is(err, context.DeadlineExceeded): + res.Incomplete = VerifyIncompleteDeadline + case errors.Is(err, context.Canceled): + res.Incomplete = VerifyIncompleteCancelled + default: + res.Incomplete = VerifyIncompleteError + } + return res, err + } + res.Complete = true + return res, nil +} + +// Why a closing read leaves no HEAD root (wrapped in CodeVerifyIncomplete). +var ( + errVerifyHeadAbsent = errors.New("chunkstore: verify: the closing read found no HEAD") + errVerifyHeadInvalid = errors.New("chunkstore: verify: the closing read's HEAD does not decode") +) + +// verifySegment is one segment object (owner, key): read once, like a chunk +// (keys are never rebound). Its one outcome is a bad one (class and detail: +// binding missing, needle missing, read error) or its content (sum, body: +// a segment keeps its bytes). A reference to it is judged at need +// (judgeSegment); nothing about a reference is kept but the decode memo. +type verifySegment struct { + owner, key string + fid string + tombstoned bool + class, detail string + sum [32]byte + body []byte + memo map[segRef]segJudged // decodes by the full reference (every input of the decode) +} + +// segRef is one root's reference to a segment, with every root field its +// decode depends on. +type segRef struct { + group, chunkBytes, remoteLSN uint64 + ref storage.ChunkSegment +} + +// segJudged is Judge's answer for a segment reference: a class (and detail) +// when it is not sound, else this root's chunk references. +type segJudged struct { + class, detail string + chunks map[uint64]storage.ChunkRef +} + +// segID is a segment's identity: its owner and key. +func segID(vol string, ref storage.ChunkSegment) string { return chunkIdentity(vol, ref.Key) } + +// Seen references, per object: the root (HEAD, or a snapshot's label), the +// index (a chunk's) or the reference with its root fields (a segment's). +type seenChunk struct { + root string + idx uint64 + sha [32]byte +} + +type seenSeg struct { + root string + ref segRef +} + +const headRoot = "HEAD" // the root of every HEAD generation's references + +// verifyChunk is one distinct chunk (owner volume + the owner's own key): +// unseen while absent from the verifier's map, then queued, then settled. +type verifyChunk struct { + id string + owner, key string + fid string + bound bool // a sound, untombstoned binding was found + + // The outcome, under the verifier's lock until the checks are joined: + // class and detail of a bad outcome (binding missing or tombstoned, + // needle missing, read error), or the content read (read: its SHA-256 + // and length). + settled bool + class, detail string + read bool + digest [32]byte + length int +} + +// verifyView is one root as last read: its references by index, and its +// root document (for the segments it names). +type verifyView struct { + label string + h storage.ChunkHead + chunks map[uint64]storage.ChunkRef + // snapshots only: the identity they were found under, and whether the + // final round read them gone. + name, attempt string + gone bool +} + +type verifier struct { + c *Catalog + vol string + root string + opts VerifyOptions + blobs Blobs + pacer *verifyPacer + + geo Geometry + chunkBytes uint64 + nChunks uint64 + + mu sync.Mutex + res *VerifyResult + segs map[string]*verifySegment // the segments read, by identity + chunks map[string]*verifyChunk // the chunks seen, by identity + pending []*verifyChunk // queued, not yet checked + listed bool // the owners' keys/ were listed once + + head *verifyView // the HEAD view; nil without a usable HEAD + dropped map[string]bool // keys a HEAD view named and a later one did not + snaps []*verifyView // the selected snapshots, in order + lastRefresh time.Time + + seenChunks map[string]map[seenChunk]bool // the references seen, per chunk + seenSegs map[string]map[seenSeg]bool // the references seen, per segment +} + +func (v *verifier) hook(stage string) { + if v.opts.hook != nil { + v.opts.hook(stage) + } +} + +func (v *verifier) finding(f VerifyFinding) { + f.Volume = v.vol + v.mu.Lock() + v.res.Findings = append(v.res.Findings, f) + if f.Class == FindingReadError { + v.res.ChunksNotRead++ + } + v.mu.Unlock() +} + +func isContextErr(ctx context.Context, err error) bool { + return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + +// fetch reads one needle. A needle the store reports absent (ErrBlobNotFound) +// and a context error are returned at once; any other failure is retried, +// up to verifyReadAttempts reads in all, before it is returned. +func (v *verifier) fetch(ctx context.Context, fid string) ([]byte, error) { + for attempt := 1; ; attempt++ { + data, err := v.blobs.Get(ctx, fid) + if err == nil || errors.Is(err, ErrBlobNotFound) || isContextErr(ctx, err) || attempt == verifyReadAttempts { + return data, err + } + v.mu.Lock() + v.res.ReadRetries++ + v.mu.Unlock() + t := time.NewTimer(verifyRetryBackoff * time.Duration(attempt)) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return nil, ctx.Err() + } + } +} + +// readErrorDetail describes a read that failed for a reason other than "not found". +func readErrorDetail(err error) string { + return fmt.Sprintf("not verified: could not read the needle in %d attempts (re-run): %v", verifyReadAttempts, err) +} + +// verifyPrefetched serves one needle already read, so the shared segment +// decoder verifies exactly the bytes fetch returned. +type verifyPrefetched struct { + fid string + body []byte +} + +func (p verifyPrefetched) Put(context.Context, []byte) (string, error) { + return "", errors.New("chunkstore: verify is read-only") +} + +func (p verifyPrefetched) Get(_ context.Context, fid string) ([]byte, error) { + if fid != p.fid { + return nil, fmt.Errorf("chunkstore: verify: unexpected needle %s", fid) + } + return p.body, nil +} + +// abortErr turns a failure that stops the pass into its error: a context +// error stays one (the CLI reports deadline_exceeded), anything else from +// the filer is remote_unavailable. +func abortErr(ctx context.Context, err error, format string, a ...any) error { + if ctx.Err() != nil { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), ctx.Err()) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), err) + } + if CodeOf(err) != "" { + return err + } + return remoteErr(err, format, a...) +} + +func headLabel(gen uint64) string { return fmt.Sprintf("HEAD gen %d", gen) } + +func (v *verifier) run(ctx context.Context) error { + vi, ok, err := v.c.ReadVolume(ctx, v.vol) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read VOLUME of %s", v.vol) + } + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok { + return catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", v.vol) + } + v.geo = vi.Geometry + v.chunkBytes = uint64(v.geo.ChunkBlocks) * uint64(v.geo.BlockSize) + if v.geo.ChunkBlocks > 0 { + v.nChunks = (v.geo.NumBlocks + uint64(v.geo.ChunkBlocks) - 1) / uint64(v.geo.ChunkBlocks) + } + if v.chunkBytes == 0 { + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingGeometry, Detail: fmt.Sprintf("VOLUME geometry %+v has no chunk size", v.geo)}) + } + if err := v.forkRecord(ctx, vi); err != nil { + return err + } + + // HEAD: the root once, then the segments it names. + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + switch { + case errors.Is(err, ErrNotFound): + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "the volume has a VOLUME entry but no HEAD"}) + case err != nil: + return abortErr(ctx, err, "read HEAD of %s", v.vol) + default: + h, derr := decodeHead(path.Join(v.root, headName), e) + if derr != nil { + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) + break + } + v.lastRefresh = v.c.now() + if _, err := v.refresh(ctx, h); err != nil { + return err + } + if err := v.intents(ctx, h, v.head.chunks); err != nil { + return err + } + } + v.hook(verifyHookHeadWalked) + + if err := v.snapshots(ctx); err != nil { + return err + } + v.hook(verifyHookRootsWalked) + for rounds := 0; ; { + if err := v.drain(ctx); err != nil { + return err + } + named, err := v.round(ctx) + if err != nil { + return err + } + if !named { + v.hook(verifyHookClosed) + return nil // V.Close: this read is the final view + } + if rounds++; rounds == v.opts.ClosingRounds { + return catErr(CodeVerifyIncomplete, true, nil, // V.GiveUp + "verify of %s: each of %d closing reads of HEAD named chunks not seen before; the pass is incomplete (re-run when the volume is quieter)", + v.vol, rounds) + } + } +} + +// drain checks every queued chunk, batch by batch, refreshing HEAD between +// batches (a refresh can queue more). +func (v *verifier) drain(ctx context.Context) error { + for len(v.pending) > 0 { + batch := v.pending + v.pending = nil + if err := v.checkBindings(ctx, batch, !v.listed); err != nil { + return err + } + v.listed = true + if v.opts.Depth == VerifyData { + if err := v.checkData(ctx, batch); err != nil { + return err + } + } + v.hook(verifyHookBatchChecked) + if err := v.maybeRefresh(ctx); err != nil { + return err + } + } + return nil +} + +// V.Round: once every queued chunk is settled, read HEAD and each selected snapshot's state once; report whether HEAD named a chunk not seen. +func (v *verifier) round(ctx context.Context) (bool, error) { + v.hook(verifyHookClosingRead) + named := false + if v.head != nil { + var err error + if named, err = v.readHead(ctx, true); err != nil { + return false, err + } + } + for _, s := range v.snaps { + active, err := v.snapshotActive(ctx, s) + if err != nil { + return false, err + } + s.gone = !active + } + return named, nil +} + +// ---- roots and segments ---- + +// V.Discover and V.Settle (segments): the segment ref names, read once per (owner, key) by this pass, its outcome kept. An error stops the pass. +func (v *verifier) segment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { + id := segID(v.vol, ref) + if s := v.segs[id]; s != nil { + return s, nil + } + s, err := v.readSegment(ctx, ref) + if err != nil { + return nil, err + } + v.segs[id] = s + return s, nil +} + +func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { + if v.blobs == nil { + return nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") + } + r, err := NewChunkRemote(v.c.f, v.blobs, v.root) + if err != nil { + return nil, err + } + s := &verifySegment{owner: ref.Owner, key: ref.Key, memo: map[segRef]segJudged{}} + dir, name, err := r.keyLocation(ref.Key) + if err != nil { + s.class, s.detail = FindingBindingMissing, "segment binding: "+err.Error() + return s, nil + } + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + s.class, s.detail = FindingBindingMissing, "segment binding not found" + return s, nil + } + if err != nil { + return nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) + } + s.fid = string(e.Extended[extFid]) + if bad := bindingProblem(e); bad != "" { + s.class, s.detail = FindingBindingMissing, "invalid segment binding: "+bad + return s, nil + } + s.tombstoned = len(e.Extended[extGCDeleted]) != 0 + v.mu.Lock() + v.res.SegmentReads++ + v.mu.Unlock() + body, err := v.fetch(ctx, s.fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return nil, abortErr(ctx, err, "read segment %s", ref.Key) + case errors.Is(err, ErrBlobNotFound): + s.class, s.detail = FindingNeedleMissing, "segment needle not found: "+err.Error() + return s, nil + default: + s.class, s.detail = FindingReadError, readErrorDetail(err) + return s, nil + } + s.sum, s.body = sha256.Sum256(body), body + return s, nil +} + +// V.Reconcile's Judge for a segment reference (also used to walk a root): the segment's bad outcome; a hash mismatch; bytes that do not decode under this reference's own fields (SEGMENT_UNREADABLE); else this root's chunk references. +func (v *verifier) judgeSegment(ctx context.Context, s *verifySegment, k segRef) segJudged { + switch { + case s.class != "": + return segJudged{class: s.class, detail: s.detail} + case k.ref.SHA256 != s.sum: + return segJudged{class: FindingContentMismatch, detail: fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} + } + // A memo of the decode, keyed by the full reference: the decode is a + // function of the bytes and of k alone, so the memo cannot change an + // answer; it only saves decoding a segment again at each walk. + if j, ok := s.memo[k]; ok { + return j + } + j := segJudged{} + r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) + if err == nil { + r.mu.Lock() + r.fids[k.ref.Key] = s.fid + r.mu.Unlock() + one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{k.group: k.ref}, ChunkBytes: k.chunkBytes, + ManifestChunkCount: k.ref.Count, RemoteLSN: k.remoteLSN, State: storage.ChunkHeadActive} + var resolved storage.ChunkHead + if resolved, err = r.resolveManifest(ctx, one); err == nil { + j.chunks = resolved.Chunks + } + } + if err != nil { + j = segJudged{class: FindingSegmentUnreadable, detail: err.Error()} + } + s.memo[k] = j + return j +} + +// bindingProblem is what makes e unusable as a chunk key binding, or "". +func bindingProblem(e *filerpb.Entry) string { + switch { + case e.GetIsDirectory(): + return "is a directory" + case len(e.GetChunks()) != 0: + return fmt.Sprintf("carries %d filer chunks", len(e.GetChunks())) + case string(e.Extended[extKind]) != kindChunkKey: + return fmt.Sprintf("kind %q, want %q", e.Extended[extKind], kindChunkKey) + case len(e.Extended[extFid]) == 0: + return "no fid" + } + return "" +} + +// walk reads the segments root h (of root, HEAD or a snapshot's label) names +// and returns its chunk references by index, and the segment groups whose +// reference Judge does not find sound (their chunks are unknown). Every +// reference met is recorded as seen. +func (v *verifier) walk(ctx context.Context, root string, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { + out := map[uint64]storage.ChunkRef{} + unusable := map[uint64]bool{} + if h.Segments == nil { + for idx, ref := range h.Chunks { + out[idx] = ref + } + } + for _, g := range sortedGroups(h.Segments) { + v.mu.Lock() + v.res.SegmentsChecked++ + v.mu.Unlock() + s, err := v.segment(ctx, h.Segments[g]) + if err != nil { + return out, unusable, err + } + k := segRef{group: g, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[g]} + see(v.seenSegs, segID(v.vol, k.ref), seenSeg{root, k}) + j := v.judgeSegment(ctx, s, k) + if j.class != "" { + unusable[g] = true + continue + } + for idx, cr := range j.chunks { + out[idx] = cr + } + } + for idx, ref := range out { + see(v.seenChunks, chunkIdentity(v.vol, ref.Key), seenChunk{root, idx, ref.SHA256}) + } + return out, unusable, nil +} + +// see records a reference to object id as seen. +func see[R comparable](seen map[string]map[R]bool, id string, r R) { + if seen[id] == nil { + seen[id] = map[R]bool{} + } + seen[id][r] = true +} + +// geometry reports a root's chunk size and chunk indices against VOLUME. +func (v *verifier) geometry(label string, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) { + if h.Segments != nil && h.ChunkBytes != v.chunkBytes { + v.finding(VerifyFinding{Root: label, Class: FindingGeometry, + Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) + } + for _, idx := range sortedIndexes(chunks) { + if idx >= v.nChunks { + i := idx + owner, key := splitIdentity(chunkIdentity(v.vol, chunks[idx].Key)) + v.finding(VerifyFinding{Root: label, Index: &i, Owner: owner, Key: key, Class: FindingGeometry, + Detail: fmt.Sprintf("chunk index %d outside the volume (%d chunks)", idx, v.nChunks)}) + } + } +} + +// V.Discover: queue one check of each chunk the references name that this pass has not seen; report whether there was one. +func (v *verifier) discover(chunks map[uint64]storage.ChunkRef) bool { + found := false + for _, idx := range sortedIndexes(chunks) { + id := chunkIdentity(v.vol, chunks[idx].Key) + if v.chunks[id] != nil { + continue + } + owner, key := splitIdentity(id) + w := &verifyChunk{id: id, owner: owner, key: key} + v.chunks[id] = w + found = true + if v.opts.Depth == VerifyMeta { + w.settled = true // nothing to check at this depth + continue + } + v.pending = append(v.pending, w) + } + return found +} + +// V.Settle: record w's outcome (a bad outcome's class and detail, or none); report nothing. +func (v *verifier) settle(w *verifyChunk, class, detail string) { + v.mu.Lock() + w.settled, w.class, w.detail = true, class, detail + v.mu.Unlock() +} + +// snapshotActive reads snapshot s's state again (part of V.Round): its name +// record must still name s's attempt, and the attempt entry must still +// exist, neither aborted nor marked deleting (the attempt path is never +// reused, so a snapshot read gone stays gone). +func (v *verifier) snapshotActive(ctx context.Context, s *verifyView) (bool, error) { + ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), s.name) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, s.name) + } + if rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, s.name), ne); err == nil && rec.Attempt != s.attempt { + return false, nil + } + e, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapsDir, s.name), s.attempt) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, s.name, s.attempt) + } + st := string(e.Extended[extSnapState]) + return st != SnapAborted && st != SnapDeleting && len(e.Extended[extSnapDeletedNs]) == 0, nil +} + +func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { + out := make([]uint64, 0, len(m)) + for idx := range m { + out = append(out, idx) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// splitIdentity splits a chunkIdentity into the owner volume and its key. +func splitIdentity(id string) (owner, key string) { + owner, key, _ = strings.Cut(id, "\x00") + return owner, key +} + +// ---- snapshots and fork record ---- + +func (v *verifier) snapshots(ctx context.Context) error { + if v.opts.Snapshot != "" { + ref, ok, err := v.c.resolveSnap(ctx, v.vol, v.opts.Snapshot) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, v.opts.Snapshot) + } + v.finding(VerifyFinding{Root: "snapshot " + v.opts.Snapshot, Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", v.vol, v.opts.Snapshot) + } + if ref.info.State == SnapDeleting { + return catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted; GC may already reclaim its chunks", v.vol, v.opts.Snapshot) + } + return v.snapshot(ctx, v.opts.Snapshot, ref) + } + if !v.opts.AllSnapshots { + return nil + } + dir := path.Join(v.root, snapNamesDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list snapshots of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing snapshot listing of %s", v.vol) + } + after = e.GetName() + ref, ok, err := v.c.resolveSnap(ctx, v.vol, e.GetName()) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, e.GetName()) + } + v.finding(VerifyFinding{Root: "snapshot " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted || ref.info.State == SnapDeleting { + continue + } + if err := v.snapshot(ctx, e.GetName(), ref); err != nil { + return err + } + } + if len(page) < listPage { + return nil + } + } +} + +// snapshot selects the snapshot found under name, at the attempt its name +// record names: that path is its identity (label, state reads), and a +// document naming another volume or snapshot is ROOT_INVALID. Its +// references are fixed; its chunks are discovered (V.Discover). +func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error { + s := &verifyView{label: "snapshot " + name + "/" + ref.rec.Attempt, h: ref.info.Head(), name: name, attempt: ref.rec.Attempt} + v.res.Snapshots = append(v.res.Snapshots, name+"/"+s.attempt) + v.snaps = append(v.snaps, s) + if ref.info.VolumeID != v.vol || ref.info.Name != name { + v.finding(VerifyFinding{Root: s.label, Class: FindingRootInvalid, + Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", ref.info.VolumeID, ref.info.Name, v.vol, name)}) + } + if ref.info.geo != (Geometry{}) && ref.info.geo != v.geo { + v.finding(VerifyFinding{Root: s.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", ref.info.geo, v.geo)}) + } + chunks, _, err := v.walk(ctx, s.label, s.h) + if err != nil { + return err + } + s.chunks = chunks + v.geometry(s.label, s.h, chunks) + v.discover(chunks) + return nil +} + +// forkRecord checks a fork's record against the parent snapshot it names: +// some attempt of that snapshot, at the recorded source generation, must +// have exactly the recorded HEAD digest (attempt entries are never +// removed, so a parent snapshot deleted or renamed since still answers). +func (v *verifier) forkRecord(ctx context.Context, vi VolumeInfo) error { + fr := vi.Fork + if vi.Origin != OriginFork || fr == nil { + return nil + } + const label = "VOLUME fork record" + mismatch := func(format string, a ...any) error { + v.finding(VerifyFinding{Root: label, Owner: fr.Source, Class: FindingForkRecordMismatch, Detail: fmt.Sprintf(format, a...)}) + return nil + } + if CheckVolumeID(fr.Source) != nil || CheckSnapshotName(fr.Snapshot) != nil { + return mismatch("fork record names source %q snapshot %q", fr.Source, fr.Snapshot) + } + dir := path.Join(v.c.base, fr.Source, snapsDir, fr.Snapshot) + after := "" + sawGen := false + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list attempts of %s/%s", fr.Source, fr.Snapshot) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing attempt listing of %s/%s", fr.Source, fr.Snapshot) + } + after = e.GetName() + info, _, err := decodeSnap(path.Join(dir, e.GetName()), e) + if err != nil || info.State == SnapAborted || info.HeadGen != fr.SourceGen { + continue + } + sawGen = true + if info.digest == fr.HeadSHA256 { + return nil + } + } + if len(page) < listPage { + break + } + } + if sawGen { + return mismatch("no attempt of snapshot %s/%s at gen %d has HEAD digest %s", fr.Source, fr.Snapshot, fr.SourceGen, fr.HeadSHA256) + } + // The source volume itself may have been deleted since the fork: its + // snapshot records went with it and there is nothing to compare with. + // That is not damage to this volume, whose chunks are checked through + // its own roots. + if _, ok, err := v.c.ReadVolume(ctx, fr.Source); err != nil { + return abortErr(ctx, err, "read fork source %s", fr.Source) + } else if !ok { + v.res.ForkSourceGone = true + return nil + } + return mismatch("no attempt of snapshot %s/%s at gen %d found", fr.Source, fr.Snapshot, fr.SourceGen) +} + +// ---- intents ---- + +// intents reports capture intents that look stale: below HEAD's epoch, +// older than IntentStaleAge, and naming no key HEAD references. It is a +// hint; whether GC may expire one is GC's decision, with blockmaster +// authority. An intent that does not decode is an invalid GC root. +func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) error { + named := map[string]bool{} + for _, ref := range chunks { + named[chunkIdentity(v.vol, ref.Key)] = true + } + for _, ref := range h.Segments { + named[chunkIdentity(v.vol, ref.Key)] = true + } + now := v.c.now() + dir := path.Join(v.root, intentsDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list intents of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing intent listing of %s", v.vol) + } + after = e.GetName() + in, err := decodeIntent(path.Join(dir, e.GetName()), e) + if err != nil { + v.finding(VerifyFinding{Root: "intent " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { + continue // copy intents never expire by epoch + } + age := now.Sub(time.Unix(0, in.CreatedNs)) + if in.Epoch >= h.Epoch || age <= v.opts.IntentStaleAge { + continue + } + bound := false + for _, k := range in.Keys { + if named[chunkIdentity(v.vol, k)] { + bound = true + break + } + } + if bound { + continue + } + v.finding(VerifyFinding{Root: "intent " + in.ID, Class: FindingIntentStale, + Detail: fmt.Sprintf("capture intent of %q at epoch %d below HEAD epoch %d, %s old, naming %d keys HEAD does not reference", + in.Holder, in.Epoch, h.Epoch, age.Round(time.Second), len(in.Keys))}) + } + if len(page) < listPage { + return nil + } + } +} + +// ---- refresh ---- + +// maybeRefresh reads HEAD again (V.Refresh) once RefreshInterval has passed since the last read. +func (v *verifier) maybeRefresh(ctx context.Context) error { + if v.head == nil || v.c.now().Sub(v.lastRefresh) < v.opts.RefreshInterval { + return nil + } + _, err := v.readHead(ctx, false) + return err +} + +// readHead reads HEAD and applies it (V.Refresh); it reports whether HEAD +// named a chunk not seen. A periodic read that finds no HEAD, one that does +// not decode, or an older generation changes nothing: the closing read +// decides. At the closing read (closing set) every answer decides the final +// view: no HEAD leaves no HEAD root and the pass incomplete (HEAD absent); +// an undecodable one is ROOT_INVALID, no HEAD root, incomplete (HEAD +// invalid); an older generation than the view cannot be the final view and +// cannot keep the earlier one, so the pass is incomplete (an error). +func (v *verifier) readHead(ctx context.Context, closing bool) (bool, error) { + v.lastRefresh = v.c.now() + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + if errors.Is(err, ErrNotFound) { + if !closing { + return false, nil + } + v.head = nil + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadAbsent, "verify of %s: the closing read found no HEAD; the pass has no HEAD to report against", v.vol) + } + if err != nil { + return false, abortErr(ctx, err, "refresh HEAD of %s", v.vol) + } + h, err := decodeHead(path.Join(v.root, headName), e) + if err != nil { + if !closing { + return false, nil + } + v.head = nil + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "HEAD at the closing read: " + err.Error()}) + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadInvalid, "verify of %s: the HEAD of the closing read does not decode", v.vol) + } + if closing && v.head != nil && h.Gen < v.head.h.Gen { + return false, remoteErr(nil, "verify of %s: the closing read returned HEAD gen %d, older than gen %d already read", v.vol, h.Gen, v.head.h.Gen) + } + return v.refresh(ctx, h) +} + +// V.Refresh: replace the HEAD view with h unless h is older (or the same); mark the keys it drops; discover its new keys. +func (v *verifier) refresh(ctx context.Context, h storage.ChunkHead) (bool, error) { + if v.head != nil && (h.Gen < v.head.h.Gen || h.Gen == v.head.h.Gen && h.Epoch == v.head.h.Epoch) { + return false, nil + } + chunks, unusable, err := v.walk(ctx, headRoot, h) + if err != nil { + return false, err + } + if v.head != nil { + // A key the old view named that h does not is dropped, unless its + // old index lies in a segment of h that could not be read. + perSeg := uint64(0) + if h.ChunkBytes > 0 { + perSeg = manifestSegmentBytes / h.ChunkBytes + } + now := map[string]bool{} + for _, ref := range chunks { + now[chunkIdentity(v.vol, ref.Key)] = true + } + for idx, ref := range v.head.chunks { + if id := chunkIdentity(v.vol, ref.Key); !now[id] && (perSeg == 0 || !unusable[idx/perSeg]) { + v.dropped[id] = true + } + } + } + v.head = &verifyView{label: headLabel(h.Gen), h: h, chunks: chunks} + v.res.HeadGens = append(v.res.HeadGens, h.Gen) + return v.discover(chunks), nil +} + +// ---- bindings ---- + +// checkBindings checks the binding of every chunk in batch. The first batch +// lists each owner's keys/ once; chunks not found in a listing (bound after +// it, or queued by a refresh) are looked up one by one. +func (v *verifier) checkBindings(ctx context.Context, batch []*verifyChunk, list bool) error { + found := map[*verifyChunk]*filerpb.Entry{} + if list { + byOwner := map[string]map[string]*verifyChunk{} + var owners []string + for _, w := range batch { + name, err := keyName(w.key) + if err != nil { + continue + } + if byOwner[w.owner] == nil { + byOwner[w.owner] = map[string]*verifyChunk{} + owners = append(owners, w.owner) + } + byOwner[w.owner][name] = w + } + sort.Strings(owners) + for _, owner := range owners { + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if CheckVolumeID(owner) != nil { + continue + } + want := byOwner[owner] + dir := path.Join(v.c.base, owner, keysDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list the chunk keys of %s", owner) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing chunk key listing of %s", owner) + } + after = e.GetName() + if w := want[e.GetName()]; w != nil { + found[w] = e + } + } + if len(page) < listPage { + break + } + } + } + } + for _, w := range batch { + e := found[w] + if e == nil { + var err error + if e, err = v.lookupBinding(ctx, w); err != nil { + return err + } + } + v.evaluateBinding(w, e) + } + return nil +} + +// lookupBinding reads w's binding directly; nil when it does not exist. +func (v *verifier) lookupBinding(ctx context.Context, w *verifyChunk) (*filerpb.Entry, error) { + if CheckVolumeID(w.owner) != nil { + return nil, nil + } + name, err := keyName(w.key) + if err != nil { + return nil, nil + } + dir := path.Join(v.c.base, w.owner, keysDir) + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return nil, nil + } + if err != nil { + return nil, abortErr(ctx, err, "read chunk key binding %s/%s", dir, name) + } + return e, nil +} + +// V.Settle (bindings): a missing, invalid or tombstoned binding is w's outcome; a sound one settles it at depth bindings. +func (v *verifier) evaluateBinding(w *verifyChunk, e *filerpb.Entry) { + if e == nil { + v.settle(w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) + return + } + w.fid = string(e.Extended[extFid]) + switch bad := bindingProblem(e); { + case bad != "": + v.settle(w, FindingBindingMissing, "invalid binding: "+bad) + case len(e.Extended[extGCDeleted]) != 0: + v.settle(w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, e.Extended[extGCDeleted])) + default: + w.bound = true + if v.opts.Depth != VerifyData { + v.settle(w, "", "") + } + } +} + +// ---- data ---- + +// checkData fetches every bound chunk of batch once, at bounded concurrency +// and paced. +func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { + if v.blobs == nil { + return errors.New("chunkstore: verify needs a blob reader for depth data") + } + jobs := make(chan *verifyChunk) + var ( + wg sync.WaitGroup + errMu sync.Mutex + firstEr error + ) + setErr := func(err error) { + errMu.Lock() + if firstEr == nil { + firstEr = err + } + errMu.Unlock() + } + getErr := func() error { + errMu.Lock() + defer errMu.Unlock() + return firstEr + } + wctx, cancel := context.WithCancel(ctx) + defer cancel() + for i := 0; i < v.opts.Concurrency; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for w := range jobs { + if err := v.readChunk(wctx, w); err != nil { + setErr(err) + cancel() + } + } + }() + } + dispatch := func() error { + for _, w := range batch { + if !w.bound { + continue + } + if err := getErr(); err != nil { + return err + } + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if err := v.pacer.wait(wctx, int64(v.chunkBytes)); err != nil { + if werr := getErr(); werr != nil { + return werr + } + return abortErr(ctx, err, "pace chunk reads") + } + select { + case jobs <- w: + case <-wctx.Done(): + if err := getErr(); err != nil { + return err + } + return abortErr(ctx, wctx.Err(), "read chunks of %s", v.vol) + } + } + return nil + } + if err := dispatch(); err != nil { + // Stop the reads in flight before waiting for them, so a known + // failure is not held up by a read that would end only with the + // caller's deadline. The failure that stopped the pass is the one + // returned, not the cancellation it caused in the readers. + setErr(err) + cancel() + } + close(jobs) + wg.Wait() + return getErr() +} + +// V.Settle (data): read w's needle once and record the outcome (missing, read error, wrong size, or the content's SHA-256). +func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { + data, err := v.fetch(ctx, w.fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return abortErr(ctx, err, "read chunk %s", w.fid) + case errors.Is(err, ErrBlobNotFound): + v.settle(w, FindingNeedleMissing, err.Error()) + return nil + default: + v.settle(w, FindingReadError, readErrorDetail(err)) + return nil + } + sum := sha256.Sum256(data) + v.mu.Lock() + defer v.mu.Unlock() + v.res.DistinctChunksRead++ + v.res.BytesRead += int64(len(data)) + w.settled, w.read, w.digest, w.length = true, true, sum, len(data) + return nil +} + +// ---- reconcile ---- + +// V.Reconcile's Judge for a chunk reference: the chunk's bad outcome; a hash mismatch; a wrong length; else sound (""). +func (v *verifier) judgeChunk(w *verifyChunk, sha [32]byte) (string, string) { + switch { + case w.class != "": + return w.class, w.detail + case !w.read: // checked to its binding (depth bindings), or not checked (depth meta) + return "", "" + case sha != w.digest: + return FindingContentMismatch, fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(sha[:])) + case uint64(w.length) != v.chunkBytes: + return FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", w.length, v.chunkBytes) + } + return "", "" +} + +// judged is Judge's answer for one final reference: its root (position +// among the final roots), its index (a chunk's) or group (a segment's), the +// SHA-256 it expects, and its class ("" when sound) and detail. +type judged struct { + root int + at uint64 + sha [32]byte + class, detail string +} + +// V.Reconcile: every finding and counter, from the settled outcomes, the references seen and the final view alone (an incomplete pass: its last view); root deleted takes precedence over superseded. +func (v *verifier) reconcile() { + // The final roots: the HEAD view, then each selected snapshot not gone, + // in order. Per object and class Judge gives a final reference: one + // finding (byClass). An object with a bad outcome or a problem under any + // reference seen, and no finding, is counted once (count). Objects never + // settled (an incomplete pass) are not judged. + var roots []*verifyView + gone := map[string]bool{} + if v.head != nil { + roots = append(roots, v.head) + v.geometry(v.head.label, v.head.h, v.head.chunks) + } + for _, s := range v.snaps { + if s.gone { + gone[s.label] = true + v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) + } else { + roots = append(roots, s) + } + } + finalChunks := map[string][]judged{} + for ri, r := range roots { + for _, idx := range sortedIndexes(r.chunks) { + ref := r.chunks[idx] + id := chunkIdentity(v.vol, ref.Key) + finalChunks[id] = append(finalChunks[id], judged{root: ri, at: idx, sha: ref.SHA256}) + v.res.ChunksChecked++ + } + } + for _, id := range sortedKeys(v.chunks) { + w := v.chunks[id] + if !w.settled { + continue + } + refs := finalChunks[id] + for i := range refs { + refs[i].class, refs[i].detail = v.judgeChunk(w, refs[i].sha) + } + mk := func(j judged) VerifyFinding { + idx := j.at + return VerifyFinding{Root: roots[j.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) + if v.opts.Depth != VerifyData { + // Below depth data no content was read: final references to one + // chunk with different SHA-256s disagree with each other. + for _, r := range refs[min(1, len(refs)):] { + if r.sha != refs[0].sha { + v.finding(mk(judged{root: r.root, at: r.at, class: FindingContentMismatch, detail: fmt.Sprintf( + "references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", + hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].at)})) + reported = true + break + } + } + } + if !reported { + var problem []string + for r := range v.seenChunks[id] { + if c, _ := v.judgeChunk(w, r.sha); c != "" { + problem = append(problem, r.root) + } + } + v.count(problem, w.class != "", gone) + } + } + if v.head != nil { + reported := map[string]bool{} + for _, idx := range sortedIndexes(v.head.chunks) { + id := chunkIdentity(v.vol, v.head.chunks[idx].Key) + if v.dropped[id] && !reported[id] { + reported[id] = true + i := idx + owner, key := splitIdentity(id) + fid := "" + if w := v.chunks[id]; w != nil { + fid = w.fid + } + v.finding(VerifyFinding{Root: v.head.label, Index: &i, Owner: owner, Key: key, FID: fid, Class: FindingRootInvalid, + Detail: "HEAD names a key it had dropped earlier in this pass; a key that left every root must not be named again"}) + } + } + } + for _, id := range sortedKeys(v.segs) { + s := v.segs[id] + var refs []judged + for ri, r := range roots { + for _, g := range sortedGroups(r.h.Segments) { + if ref := r.h.Segments[g]; segID(v.vol, ref) == id { + j := v.judgeSegment(context.Background(), s, segRef{group: g, chunkBytes: r.h.ChunkBytes, remoteLSN: r.h.RemoteLSN, ref: ref}) + refs = append(refs, judged{root: ri, at: g, class: j.class, detail: j.detail}) + } + } + } + mk := func(j judged) VerifyFinding { + g := j.at + return VerifyFinding{Root: roots[j.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: s.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) + // A tombstoned segment binding is reported beside the segment's + // outcome, at depths that check bindings. + tomb := s.tombstoned && v.opts.Depth != VerifyMeta + if tomb && len(refs) > 0 { + v.finding(mk(judged{root: refs[0].root, at: refs[0].at, class: FindingBindingTombstoned, detail: "segment binding tombstoned by GC"})) + reported = true + } + if !reported { + var problem []string + for r := range v.seenSegs[id] { + if tomb || v.judgeSegment(context.Background(), s, r.ref).class != "" { + problem = append(problem, r.root) + } + } + v.count(problem, s.class != "" || tomb, gone) + } + } +} + +// byClass reports one finding per class among refs (in final-root order): +// under the first reference of that class, its detail counting the others +// of that class and naming the next root carrying one. It reports whether it +// made one. +func (v *verifier) byClass(roots []*verifyView, refs []judged, mk func(judged) VerifyFinding) bool { + var order []string + first, more, next := map[string]int{}, map[string]int{}, map[string]string{} + for i, j := range refs { + if j.class == "" { + continue + } + f, ok := first[j.class] + if !ok { + first[j.class] = i + order = append(order, j.class) + continue + } + more[j.class]++ + if next[j.class] == "" && j.root != refs[f].root { + next[j.class] = roots[j.root].label + } + } + for _, c := range order { + j := refs[first[c]] + if n := more[c]; n > 0 { + j.detail += fmt.Sprintf("; %d more final reference(s) of this class", n) + if next[c] != "" { + j.detail += ", next under " + next[c] + } + } + v.finding(mk(j)) + } + return len(order) > 0 +} + +// count counts an object that yields no finding but had a bad outcome (bad) +// or a problem under a reference seen (problem: those references' roots), +// once: root deleted when a snapshot that is gone carried such a reference, +// otherwise superseded. +func (v *verifier) count(problem []string, bad bool, gone map[string]bool) { + if len(problem) == 0 && !bad { + return + } + for _, r := range problem { + if gone[r] { + v.res.RootDeletedDuringVerify++ + return + } + } + v.res.SupersededDuringVerify++ +} + +func sortedKeys[T any](m map[string]T) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { + out := make([]uint64, 0, len(m)) + for g := range m { + out = append(out, g) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// verifyPacer spaces reads so they average at most rate bytes per second. +type verifyPacer struct { + mu sync.Mutex + rate int64 // <= 0: unpaced + next time.Time +} + +func (p *verifyPacer) wait(ctx context.Context, n int64) error { + if p == nil || p.rate <= 0 || n <= 0 { + return ctx.Err() + } + p.mu.Lock() + now := time.Now() + if p.next.Before(now) { + p.next = now + } + start := p.next + p.next = p.next.Add(time.Duration(float64(n) / float64(p.rate) * float64(time.Second))) + p.mu.Unlock() + d := time.Until(start) + if d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func findingLess(a, b VerifyFinding) bool { + if a.Root != b.Root { + return a.Root < b.Root + } + if (a.Index == nil) != (b.Index == nil) { + return a.Index == nil // a root's and its segments' findings first + } + if as, bs := ptrOr(a.Segment), ptrOr(b.Segment); as != bs { + return as < bs + } + if ai, bi := ptrOr(a.Index), ptrOr(b.Index); ai != bi { + return ai < bi + } + if a.Key != b.Key { + return a.Key < b.Key + } + return a.Class < b.Class +} + +func ptrOr(p *uint64) uint64 { + if p == nil { + return 0 + } + return *p +} diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go new file mode 100644 index 0000000000..407b223b36 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -0,0 +1,2036 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A geometry with three segments' worth of chunks (one segment covers a +// logical GiB: 32768 chunks of 32 KiB), so a test can damage one segment +// and see the others still checked. +var verifyGeo = Geometry{NumBlocks: 3 * 32768 * 8, BlockSize: 4096, ChunkBlocks: 8} + +const ( + verifyChunkBytes = 8 * 4096 + verifyPer = 32768 // chunks per segment at verifyGeo +) + +// countingBlobs counts reads per fid, and fails reads of a fid on request +// with a transient (not "not found") error. +type countingBlobs struct { + gcBlobs + mu sync.Mutex + gets map[string]int + fail map[string]int // reads of fid still to fail; negative: every read +} + +var errTransient = errors.New("read tcp 127.0.0.1:8080: connection reset by peer") + +func (b *countingBlobs) Get(ctx context.Context, fid string) ([]byte, error) { + b.mu.Lock() + b.gets[fid]++ + n := b.fail[fid] + if n > 0 { + b.fail[fid] = n - 1 + } + b.mu.Unlock() + if n != 0 { + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, errTransient) + } + return b.gcBlobs.Get(ctx, fid) +} + +// failReads makes the next n reads of fid fail (n < 0: all of them). +func (b *countingBlobs) failReads(fid string, n int) { + b.mu.Lock() + defer b.mu.Unlock() + b.fail[fid] = n +} + +func (b *countingBlobs) reads(fid string) int { + b.mu.Lock() + defer b.mu.Unlock() + return b.gets[fid] +} + +type verifyFixture struct { + t *testing.T + f *fakeFiler + b gcBlobs + cb *countingBlobs + c *Catalog + tag int +} + +func newVerifyFixture(t *testing.T, vols ...string) *verifyFixture { + t.Helper() + fx := &verifyFixture{t: t, f: newFakeFiler(), b: gcBlobs{newFakeBlobs()}} + fx.cb = &countingBlobs{gcBlobs: fx.b, gets: map[string]int{}, fail: map[string]int{}} + c, err := NewCatalog(manifestFilerBlobs{fx.f, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + fx.c = c + for _, vol := range vols { + if err := fx.f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(context.Background(), vol, verifyGeo); err != nil { + t.Fatal(err) + } + } + return fx +} + +func verifyData(fill byte) []byte { + b := make([]byte, verifyChunkBytes) + for i := range b { + b[i] = fill + byte(i%7) + } + return b +} + +// publish installs a new HEAD for vol: the current chunks when keep is set, +// with set written under fresh keys over them. +func (fx *verifyFixture) publish(vol string, set map[uint64][]byte, keep bool) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: max(cur.RemoteLSN, 42) + 1, Chunks: map[uint64]storage.ChunkRef{}} + if keep { + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + } + for idx, data := range set { + fx.tag++ + key := fmt.Sprintf("chunks/t%d/c%d", fx.tag, idx) + if err := r.Put(ctx, key, data); err != nil { + fx.t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// binding returns the directory and name of a qualified key's binding. +func bindingOf(t *testing.T, qkey string) (string, string) { + t.Helper() + owner, own, ok := strings.Cut(strings.TrimPrefix(qkey, "@"), "/") + if !ok || !strings.HasPrefix(qkey, "@") { + t.Fatalf("key %q is not owner-qualified", qkey) + } + return path.Join(catBase, owner, keysDir), url.PathEscape(own) +} + +func (fx *verifyFixture) fid(qkey string) string { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + e, err := fx.f.LookupEntry(context.Background(), dir, name) + if err != nil { + fx.t.Fatalf("binding of %s: %v", qkey, err) + } + return string(e.Extended[extFid]) +} + +func (fx *verifyFixture) deleteBinding(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + if err := fx.f.DeleteEntry(context.Background(), dir, name, nil); err != nil { + fx.t.Fatal(err) + } +} + +func (fx *verifyFixture) tombstone(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + fx.f.bumpExtended(path.Join(dir, name), extGCDeleted, "done") +} + +// needle edits the stored bytes of fid (nil deletes the needle). +func (fx *verifyFixture) needle(fid string, edit func([]byte) []byte) { + fx.t.Helper() + fx.b.mu.Lock() + defer fx.b.mu.Unlock() + d, ok := fx.b.data[fid] + if !ok { + fx.t.Fatalf("no needle %s", fid) + } + if out := edit(append([]byte(nil), d...)); out == nil { + delete(fx.b.data, fid) + } else { + fx.b.data[fid] = out + } +} + +func flipByte(d []byte) []byte { d[len(d)/2] ^= 0xff; return d } +func truncate(d []byte) []byte { return d[:len(d)-4096] } +func dropNeedle([]byte) []byte { return nil } + +func (fx *verifyFixture) verify(vol string, opts VerifyOptions) VerifyResult { + fx.t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, vol, opts) + if err != nil { + fx.t.Fatalf("verify %s %+v: %v", vol, opts, err) + } + if !res.Complete { + fx.t.Fatalf("verify %s: incomplete without an error: %+v", vol, res) + } + return res +} + +// classes renders findings as "CLASS@index" (or "CLASS@seg"), in order. +func classes(res VerifyResult) []string { + var out []string + for _, f := range res.Findings { + switch { + case f.Index != nil: + out = append(out, fmt.Sprintf("%s@%d", f.Class, *f.Index)) + case f.Segment != nil: + out = append(out, fmt.Sprintf("%s@seg%d", f.Class, *f.Segment)) + default: + out = append(out, f.Class) + } + } + return out +} + +func wantClasses(t *testing.T, what string, res VerifyResult, want ...string) { + t.Helper() + got := classes(res) + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s: findings %v, want %v\n%+v", what, got, want, res.Findings) + } + n := 0 + for _, c := range res.FindingsByClass { + n += c + } + if n != len(res.Findings) { + t.Fatalf("%s: findingsByClass %v does not count %d findings", what, res.FindingsByClass, len(res.Findings)) + } +} + +func allDepths() []VerifyDepth { return []VerifyDepth{VerifyMeta, VerifyBindings, VerifyData} } + +// A healthy volume with three segments and a snapshot verifies clean at +// every depth; the shared segments are read once. +func TestVerify_CleanVolumeAllDepths(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + res := fx.verify("v1", VerifyOptions{Depth: d, AllSnapshots: true}) + wantClasses(t, string(d), res) + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen || len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s1/") || + res.SegmentsChecked != 6 || res.SegmentReads != 3 || res.ChunksChecked != 6 || res.DistinctChunks != 3 { + t.Fatalf("%s: summary %+v", d, res) + } + wantRead := 0 + if d == VerifyData { + wantRead = 3 + } + if res.DistinctChunksRead != wantRead || res.BytesRead != int64(wantRead*verifyChunkBytes) { + t.Fatalf("%s: read %d chunks, %d bytes; want %d chunks", d, res.DistinctChunksRead, res.BytesRead, wantRead) + } + } +} + +// The gap the default depth closes: GC's mark never looks a rooted key up, +// so a HEAD key whose binding is missing passes it; verify reports it. +func TestVerify_MissingBindingGCPassesVerifyReports(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.deleteBinding(h.Chunks[1].Key) + + now := time.Now().Add(24 * time.Hour) + g, err := NewCollector(fx.c, fx.b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, + IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) + if err != nil { + t.Fatal(err) + } + if _, err := g.Preview(context.Background()); err != nil { + t.Fatalf("GC mark: %v; the gap is that it passes", err) + } + + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta})) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "default depth", res, "BINDING_MISSING@1") + f := res.Findings[0] + if res.Depth != VerifyBindings || f.Volume != "v1" || f.Root != headLabel(h.Gen) || f.Owner != "v1" || !strings.HasPrefix(h.Chunks[1].Key, "@v1/"+f.Key) { + t.Fatalf("finding %+v (depth %s)", f, res.Depth) + } +} + +// A flipped byte is invisible to metadata; depth data catches it. +func TestVerify_FlippedByteDataOnly(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), flipByte) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "CONTENT_MISMATCH@0") + if res.Findings[0].FID != fx.fid(h.Chunks[0].Key) { + t.Fatalf("finding fid %q", res.Findings[0].FID) + } +} + +// A reference is judged by its hash first: a needle truncated in the store +// no longer matches its reference (CONTENT_MISMATCH); a needle that matches +// its reference but is not a chunk long is SIZE_MISMATCH. +func TestVerify_TruncatedNeedleSizeMismatch(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[1].Key), truncate) + wantClasses(t, "truncated in the store", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "CONTENT_MISMATCH@1") + + fx = newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)[:verifyChunkBytes-4096]}, false) + wantClasses(t, "short but as referenced", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") +} + +func TestVerify_MissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "NEEDLE_MISSING@0") + // The store said "not found": that answer is not retried. + if res.ReadRetries != 0 || res.ChunksNotRead != 0 || fx.cb.reads(fx.fid(h.Chunks[0].Key)) != 1 { + t.Fatalf("not-found needle: %d retries, %d not read, %d reads; want 0, 0, 1", + res.ReadRetries, res.ChunksNotRead, fx.cb.reads(fx.fid(h.Chunks[0].Key))) + } +} + +// A read that fails once with an error other than "not found" is retried +// and then verifies: no finding. +func TestVerify_TransientReadIsRetried(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + chunk, seg := fx.fid(h.Chunks[0].Key), fx.fid(h.Segments[0].Key) + fx.cb.failReads(chunk, 1) + fx.cb.failReads(seg, 1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "transient", res) + if res.ReadRetries != 2 || res.ChunksNotRead != 0 || res.DistinctChunksRead != 2 || fx.cb.reads(chunk) != 2 || fx.cb.reads(seg) != 2 { + t.Fatalf("transient errors: %d retries, %d not read, %d chunks read, reads chunk %d segment %d; want 2, 0, 2, 2, 2", + res.ReadRetries, res.ChunksNotRead, res.DistinctChunksRead, fx.cb.reads(chunk), fx.cb.reads(seg)) + } +} + +// A read that keeps failing with an error other than "not found" is +// READ_ERROR (not verified), never NEEDLE_MISSING or SEGMENT_UNREADABLE. +func TestVerify_PersistentReadErrorIsNotAMissingNeedle(t *testing.T) { + t.Run("chunk", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid := fx.fid(h.Chunks[0].Key) + fx.cb.failReads(fid, -1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "chunk read error", res, "READ_ERROR@0") + f := res.Findings[0] + if res.ChunksNotRead != 1 || res.ReadRetries != 2 || fx.cb.reads(fid) != 3 || f.FID != fid || + !strings.Contains(f.Detail, "not verified") || !strings.Contains(f.Detail, errTransient.Error()) { + t.Fatalf("chunk read error: %d not read, %d retries, %d reads, finding %+v", res.ChunksNotRead, res.ReadRetries, fx.cb.reads(fid), f) + } + }) + t.Run("segment", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + fx.cb.failReads(fx.fid(h.Segments[0].Key), -1) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "segment read error", res, "READ_ERROR@seg0") + if res.ChunksNotRead != 1 || res.ChunksChecked != 1 { + t.Fatalf("segment read error: %+v", res) + } + }) +} + +// SWFS reports a needle absent (ErrBlobNotFound) only when every location +// answers 404; the error text is what it was before. +func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + missing, broken := server(http.StatusNotFound), server(http.StatusInternalServerError) + // dropped closes every connection without an answer: a transport error. + dropped := func() string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + }() + statusOf := map[string]int{missing: http.StatusNotFound, broken: http.StatusInternalServerError} + for _, tc := range []struct { + name string + hosts []string + notFound bool + }{ + {"every location 404", []string{missing, missing}, true}, + {"one location 500", []string{missing, broken}, false}, + {"only 500", []string{broken}, false}, + // Only the last answer is 404: still not proof of absence. + {"500 then 404", []string{broken, missing}, false}, + {"transport error then 404", []string{dropped, missing}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var locs []*filerpb.Location + for _, h := range tc.hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + c := startFakeFiler(t, &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: locs}}}}) + _, err := c.Get(context.Background(), "7,0000dead") + last := tc.hosts[len(tc.hosts)-1] + status := statusOf[last] + if err == nil || errors.Is(err, ErrBlobNotFound) != tc.notFound || err.Error() != fmt.Sprintf("chunkstore: read 7,0000dead: http %d from %s", status, last) { + t.Fatalf("Get: %v (not found %v), want not found %v", err, errors.Is(err, ErrBlobNotFound), tc.notFound) + } + }) + } +} + +// volumeAt is a LookupVolume answer placing volume vid at hosts. +func volumeAt(vid string, hosts ...string) *filerpb.LookupVolumeResponse { + var locs []*filerpb.Location + for _, h := range hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + return &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{vid: {Locations: locs}}} +} + +func (f *fakeFilerGRPC) volumeLookups() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.volLookups +} + +// Cached locations can be stale (the volume moved): 404 from every cached +// location is not proof of absence. Get looks the volume up again and reads +// from the fresh locations; only 404 from every fresh location is +// ErrBlobNotFound. A read the cache serves makes no lookup. +func TestSWFS_GetStaleCachedLocationLooksUpAgain(t *testing.T) { + body := []byte("needle bytes") + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + if status == http.StatusOK { + _, _ = w.Write(body) + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc, alsoMissing := server(http.StatusNotFound), server(http.StatusOK), server(http.StatusNotFound) + const fid = "7,0000dead" + for _, tc := range []struct { + name string + cached []string // nil: nothing cached + fresh string + wantBody bool + wantLookups int + }{ + {"cached location 404, fresh location has it", []string{oldLoc}, newLoc, true, 1}, + {"cached and fresh locations 404", []string{oldLoc}, alsoMissing, false, 1}, + {"warm cache", []string{newLoc}, newLoc, true, 0}, + {"nothing cached, fresh location 404", nil, alsoMissing, false, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeFilerGRPC{lookupVol: volumeAt("7", tc.fresh)} + c := startFakeFiler(t, f) + if tc.cached != nil { + c.mu.Lock() + c.vidCache["7"] = tc.cached + c.mu.Unlock() + } + b, err := c.Get(context.Background(), fid) + if n := f.volumeLookups(); n != tc.wantLookups { + t.Fatalf("Get made %d volume lookups, want %d (err %v)", n, tc.wantLookups, err) + } + if tc.wantBody { + if err != nil || string(b) != string(body) { + t.Fatalf("Get: %q, %v; want the needle from %s", b, err, tc.fresh) + } + return + } + if !errors.Is(err, ErrBlobNotFound) || err.Error() != "chunkstore: read "+fid+": http 404 from "+tc.fresh { + t.Fatalf("Get: %v (not found %v); want ErrBlobNotFound from the fresh location %s", err, errors.Is(err, ErrBlobNotFound), tc.fresh) + } + }) + } +} + +// A volume that moved after its location was cached is not missing: depth +// data through SWFS reads every needle from the new location, no finding. +func TestVerify_MovedVolumeIsNotAMissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var mu sync.Mutex + moved := false + serve := func(old bool) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gone := old && moved + mu.Unlock() + fx.b.mu.Lock() + d, ok := fx.b.data[strings.TrimPrefix(r.URL.Path, "/")] + fx.b.mu.Unlock() + if gone || !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(d) + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc := serve(true), serve(false) + vid, _, _ := strings.Cut(fx.fid(h.Chunks[0].Key), ",") + f := &fakeFilerGRPC{lookupVol: volumeAt(vid, oldLoc)} + sw := startFakeFiler(t, f) + ctx := context.Background() + // Warm the location cache at the old location, then move the volume. + if _, err := sw.Get(ctx, fx.fid(h.Chunks[0].Key)); err != nil { + t.Fatal(err) + } + mu.Lock() + moved = true + mu.Unlock() + f.mu.Lock() + f.lookupVol = volumeAt(vid, newLoc) + f.mu.Unlock() + + cat, err := NewCatalog(manifestFilerBlobs{fx.f, sw}, catBase) + if err != nil { + t.Fatal(err) + } + res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + wantClasses(t, "moved volume", res) + if res.DistinctChunksRead != 2 || res.SegmentReads != 1 { + t.Fatalf("read %d chunks, %d segments; want 2, 1", res.DistinctChunksRead, res.SegmentReads) + } +} + +// A root that names a binding GC tombstoned: the chunk is gone or going. +func TestVerify_TombstonedBinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.tombstone(h.Chunks[0].Key) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{}), "BINDING_TOMBSTONED@0") + // No read of a tombstoned binding's needle: one finding, not two. + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "BINDING_TOMBSTONED@0") + if res.DistinctChunksRead != 1 { + t.Fatalf("read %d chunks, want only the sound one", res.DistinctChunksRead) + } +} + +// A corrupt segment (its content no longer matches the root's reference: a +// mismatch for that root) and a segment whose binding is gone are each a +// finding; the pass goes on to the other segments and their chunks. +func TestVerify_UnreadableSegmentContinues(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + fx.needle(fx.fid(h.Segments[0].Key), flipByte) + fx.deleteBinding(h.Segments[1].Key) + fx.deleteBinding(h.Chunks[2*verifyPer].Key) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "BINDING_MISSING@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) + if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { + t.Fatalf("summary %+v", res) + } + if !strings.Contains(res.Findings[0].Detail, "SHA-256") || res.Findings[0].Key != h.Segments[0].Key { + t.Fatalf("corrupt segment finding %+v", res.Findings[0]) + } +} + +// A chunk that leaves HEAD and is collected while the pass runs is not a +// finding when no root names it at the final read (a bad outcome is then +// counted as superseded during verify; read content has no reference left +// to compare with); under a snapshot that still names it, it is one. +func TestVerify_SupersededDuringPass(t *testing.T) { + type damage struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + } + cases := []damage{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"binding tombstoned", VerifyBindings, func(fx *verifyFixture, k string) { + fx.tombstone(k) + fx.needle(fx.fid(k), dropNeedle) + }, FindingBindingTombstoned}, + {"needle deleted", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) }, FindingNeedleMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, withSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/snapshot=%v", tc.name, withSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if withSnap { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + } + old := h.Chunks[0].Key + hooked := 0 + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: withSnap} + opts.hook = func(stage string) { + if stage != verifyHookHeadWalked { + return + } + hooked++ + // After verify read HEAD: the owner replaces chunk 0 and GC + // collects the old one. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if !withSnap { + wantClasses(t, "HEAD only", res) + } else { + wantClasses(t, "with the snapshot", res, tc.class+"@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("finding root %q, want the snapshot", res.Findings[0].Root) + } + } + superseded := 0 + if !withSnap { + superseded = 1 // a problem under a reference seen, and no finding + } + // The closing read sees the owner's new HEAD: it is the final view. + if hooked != 1 || res.SupersededDuringVerify != superseded || len(res.HeadGens) != 2 || res.HeadGens[0] != h.Gen { + t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, res.HeadGens, superseded, h.Gen) + } + }) + } + } +} + +// A miss under a snapshot is a finding only while that attempt is still +// active at the final read: a snapshot deleted during the pass, whose chunk +// is then collected, is listed as not fully covered, its bad chunk counted +// as root deleted during verify, not reported. +func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { + cases := []struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + }{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingContentMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, deleteSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/deleted=%v", tc.name, deleteSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + s, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) + if err != nil { + t.Fatal(err) + } + // HEAD moves on before the pass: only the snapshot names the old chunk 0. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + old := h.Chunks[0].Key + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: true} + opts.hook = func(stage string) { + if stage != verifyHookRootsWalked { + return + } + if deleteSnap { + if st, err := fx.c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { + t.Errorf("delete s1: %q %v", st, err) + } + } + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if len(res.Snapshots) != 1 { + t.Fatalf("snapshots checked %v", res.Snapshots) + } + if !deleteSnap { + wantClasses(t, "active snapshot", res, tc.class+"@0") + if res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 || !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("active snapshot: %+v", res) + } + return + } + wantClasses(t, "deleted snapshot", res) + // The gone snapshot carried the only problem reference. + if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || + len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { + t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", + res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) + } + }) + } + } +} + +// A chunk named by HEAD (superseded during the pass) and by a snapshot that +// is still active is one finding, under the snapshot (and not counted as +// superseded: a root still names it). +func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true} + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + } + res := fx.verify("v1", opts) + wantClasses(t, "shared chunk", res, "NEEDLE_MISSING@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 0 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 0, 0", + res.Findings[0].Root, res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } +} + +// A HEAD that advances mid-pass: the result lists both generations, only +// the segment whose key changed is read again, and the references checked +// are the final view's. +func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { + for _, d := range []VerifyDepth{VerifyBindings, VerifyData} { + t.Run(string(d), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: d, RefreshInterval: time.Minute} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.publish("v1", map[uint64][]byte{verifyPer: verifyData(7)}, true) + } + } + fx.c.SetClock(tickingClock(time.Minute)) // past the refresh interval at every read + res := fx.verify("v1", opts) + wantClasses(t, "refresh", res) + if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if h2.Segments[0] != h1.Segments[0] || h2.Segments[2] != h1.Segments[2] || h2.Segments[1] == h1.Segments[1] { + t.Fatal("fixture: the new HEAD should change only segment 1") + } + if res.SegmentReads != 4 || res.SegmentsChecked != 6 { + t.Fatalf("segment reads %d (checked %d); want 3 + 1 changed", res.SegmentReads, res.SegmentsChecked) + } + if res.DistinctChunks != 4 || res.ChunksChecked != 3 { + t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new, 3 final references", res.DistinctChunks, res.ChunksChecked) + } + if d == VerifyData && (res.DistinctChunksRead != 4 || fx.cb.reads(fx.fid(h2.Chunks[verifyPer].Key)) != 1) { + t.Fatalf("read %d chunks; want 4, the new one included", res.DistinctChunksRead) + } + }) + } +} + +// A chunk shared by HEAD and two snapshots is fetched once. +func TestVerify_DedupSharedChunkReadOnce(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + for _, n := range []string{"s1", "s2"} { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: n, RequestID: "r-" + n}, h); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true}) + wantClasses(t, "dedup", res) + if res.ChunksChecked != 6 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 || len(res.Snapshots) != 2 { + t.Fatalf("summary %+v", res) + } + for _, idx := range []uint64{0, 1} { + if n := fx.cb.reads(fx.fid(h.Chunks[idx].Key)); n != 1 { + t.Fatalf("chunk %d read %d times, want once", idx, n) + } + } + // One named snapshot works the same way. + res = fx.verify("v1", VerifyOptions{Depth: VerifyBindings, Snapshot: "s2"}) + if len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s2/") || res.ChunksChecked != 4 { + t.Fatalf("named snapshot: %+v", res) + } + if _, err := fx.c.Verify(context.Background(), "v1", VerifyOptions{Snapshot: "nope"}); CodeOf(err) != CodeSnapshotNotFound { + t.Fatalf("missing snapshot: %v", err) + } +} + +// A fork's qualified keys are checked in the owner volume's keys/, and its +// fork record against the parent snapshot. +func TestVerify_ForkQualifiedKeysAndRecord(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + wantClasses(t, "clean fork "+string(d), fx.verify("v2", VerifyOptions{Depth: d})) + } + // The fork wrote no binding of its own: every chunk resolves to v1. + fx.deleteBinding(h.Chunks[1].Key) + res := fx.verify("v2", VerifyOptions{}) + wantClasses(t, "fork, parent binding gone", res, "BINDING_MISSING@1") + if res.Findings[0].Owner != "v1" || res.Findings[0].Volume != "v2" { + t.Fatalf("finding %+v, want owner v1 in volume v2", res.Findings[0]) + } + + // A fork record whose digest is not the parent snapshot's. + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v2"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.Fork.HeadSHA256 = strings.Repeat("0", 64) + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v2"), e, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "tampered fork record", res, "FORK_RECORD_MISMATCH") + if res.Findings[0].Owner != "v1" || !strings.Contains(res.Findings[0].Detail, "s1") { + t.Fatalf("finding %+v", res.Findings[0]) + } +} + +// A fork whose source volume was deleted afterwards has nothing to compare +// its fork record with. That is not damage: no finding, and the result +// says the source is gone. While the source volume still exists, a missing +// parent snapshot attempt is a finding. +func TestVerify_ForkSourceVolumeDeleted(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + // The parent's snapshot attempts vanish, the source volume remains. + dir := path.Join(catBase, "v1", snapsDir, "s1") + es, err := fx.f.ListEntries(ctx, dir, "", "", 100) + if err != nil || len(es) == 0 { + t.Fatalf("attempts of s1: %d, %v", len(es), err) + } + for _, e := range es { + if err := fx.f.DeleteEntry(ctx, dir, e.GetName(), nil); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "attempts gone, source present", res, "FORK_RECORD_MISMATCH") + if res.ForkSourceGone { + t.Fatal("ForkSourceGone set while the source volume exists") + } + // Now the source volume record goes too. + if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), volumeName, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "source volume deleted", res) + if !res.ForkSourceGone { + t.Fatal("ForkSourceGone not set") + } +} + +// Intent bookkeeping: an old capture intent below HEAD's epoch naming keys +// HEAD does not reference is reported; one naming a key HEAD binds, a +// current one and a copy intent are not. +func TestVerify_IntentStale(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + root := path.Join(catBase, "v1") + headKey := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + stale, err := putIntent(ctx, fx.f, root, storage.ChunkIntent{Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{"chunks/lost/k"}}) + if err != nil { + t.Fatal(err) + } + for _, in := range []storage.ChunkIntent{ + {Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{headKey}}, // HEAD binds its key + {Gen: 2, Epoch: 1, Holder: "h1", Keys: []string{"chunks/next/k"}}, // the current epoch + {Gen: 0, Epoch: 0, Holder: "snapshot:v1/s9/1-0000000000000000", Keys: []string{"x/y"}}, // a copy intent + } { + if _, err := putIntent(ctx, fx.f, root, in); err != nil { + t.Fatal(err) + } + } + wantClasses(t, "young intents", fx.verify("v1", VerifyOptions{})) + fx.c.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + res := fx.verify("v1", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "old intents", res, "INTENT_STALE") + if res.Findings[0].Root != "intent "+stale { + t.Fatalf("stale intent finding %+v, want intent %s", res.Findings[0], stale) + } +} + +// recordingStore counts every write the catalog makes through it. +type recordingStore struct { + Filer + blobs *countingBlobs + mu sync.Mutex + creates, updates, deletes int + blobPuts, blobDeletes, reads int +} + +func (r *recordingStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, o bool) error { + r.mu.Lock() + r.creates++ + r.mu.Unlock() + return r.Filer.CreateEntry(ctx, dir, e, o) +} +func (r *recordingStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, x map[string][]byte) error { + r.mu.Lock() + r.updates++ + r.mu.Unlock() + return r.Filer.UpdateEntry(ctx, dir, e, x) +} +func (r *recordingStore) DeleteEntry(ctx context.Context, dir, name string, x map[string][]byte) error { + r.mu.Lock() + r.deletes++ + r.mu.Unlock() + return r.Filer.DeleteEntry(ctx, dir, name, x) +} +func (r *recordingStore) Put(ctx context.Context, d []byte) (string, error) { + r.mu.Lock() + r.blobPuts++ + r.mu.Unlock() + return r.blobs.Put(ctx, d) +} +func (r *recordingStore) Get(ctx context.Context, fid string) ([]byte, error) { + r.mu.Lock() + r.reads++ + r.mu.Unlock() + return r.blobs.Get(ctx, fid) +} +func (r *recordingStore) DeleteBlob(ctx context.Context, fid string) error { + r.mu.Lock() + r.blobDeletes++ + r.mu.Unlock() + return r.blobs.DeleteBlob(ctx, fid) +} + +// Verify writes nothing, at any depth, also on the miss, superseded and +// refresh paths and for a fork. +func TestVerify_ReadOnlyAtEveryDepth(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2), verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + if _, err := putIntent(ctx, fx.f, path.Join(catBase, "v1"), storage.ChunkIntent{Gen: 1, Holder: "old", Keys: []string{"k/old"}}); err != nil { + t.Fatal(err) + } + fx.needle(fx.fid(h.Chunks[1].Key), flipByte) + rec := &recordingStore{Filer: fx.f, blobs: fx.cb} + cat, err := NewCatalog(rec, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + for _, d := range allDepths() { + for _, vol := range []string{"v1", "v2"} { + opts := VerifyOptions{Depth: d, AllSnapshots: true, RefreshInterval: time.Millisecond} + opts.hook = func(stage string) { + if vol == "v1" && stage == verifyHookHeadWalked { + // Writes by the owner (through the fixture, not the + // recorder): a new HEAD, and the old chunk 0 collected. + r, _ := NewChunkRemote(fx.f, fx.b, path.Join(catBase, "v1")) + cur, err := r.GetHead(ctx) + if err != nil { + t.Error(err) + return + } + oldFid := fx.fid(cur.Chunks[0].Key) + fx.publish("v1", map[uint64][]byte{0: verifyData(byte(10 + len(d)))}, true) + fx.needle(oldFid, dropNeedle) + time.Sleep(3 * time.Millisecond) + } + } + res, err := cat.Verify(ctx, vol, opts) + if err != nil || !res.Complete { + t.Fatalf("%s %s: %v", d, vol, err) + } + if d == VerifyData && rec.reads == 0 { + t.Fatalf("%s %s: no blob reads recorded; the recorder is not in the path", d, vol) + } + } + } + if rec.creates+rec.updates+rec.deletes+rec.blobPuts+rec.blobDeletes != 0 { + t.Fatalf("verify wrote: %d creates, %d updates, %d deletes, %d blob puts, %d blob deletes", + rec.creates, rec.updates, rec.deletes, rec.blobPuts, rec.blobDeletes) + } +} + +// A chunk index past the end of VOLUME's geometry is a GEOMETRY finding. +func TestVerify_GeometryOutsideVolume(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 2 * verifyPer: verifyData(2)}, false) + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v1"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.NumBlocks = 2 * verifyPer * 8 + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta}), fmt.Sprintf("GEOMETRY@%d", 2*verifyPer)) +} + +// A HEAD that does not decode is a finding, not a failure to run. +func TestVerify_InvalidHeadRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bad HEAD", res, "ROOT_INVALID") + if len(res.HeadGens) != 0 { + t.Fatalf("covered gens %v of an invalid HEAD", res.HeadGens) + } +} + +// Only an inability to continue stops the pass: the result then says it is +// incomplete and keeps what was covered. +func TestVerify_ContextEndedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + opts := VerifyOptions{Depth: VerifyData} + opts.hook = func(stage string) { cancel() } + res, err := fx.c.Verify(ctx, "v1", opts) + if !errors.Is(err, context.Canceled) || res.Complete || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("cancelled pass: %v, %+v", err, res) + } + if _, err := fx.c.Verify(context.Background(), "nope", VerifyOptions{}); CodeOf(err) != CodeNotChunkVolume { + t.Fatalf("missing volume: %v", err) + } +} + +// heldReads holds the read of one needle open until the reader's context +// ends (or the test releases it), and counts the reads in progress. +type heldReads struct { + Blobs + fid string + onEnter func() // runs once, when the held read has started + entered chan struct{} // closed when the held read has started + once sync.Once + + released chan struct{} // closed by release: the escape when cancellation fails + releaseOnce sync.Once + + mu sync.Mutex + active int + ended error // the held read's context error, once its context ended +} + +func newHeldReads(b Blobs, fid string) *heldReads { + return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{}), released: make(chan struct{})} +} + +func (h *heldReads) release() { h.releaseOnce.Do(func() { close(h.released) }) } + +// verifyEscape bounds a test's wait for a Verify that should return at +// once; it only turns a hang into a failure, it is not a success criterion. +const verifyEscape = 30 * time.Second + +type verifyOutcome struct { + res VerifyResult + err error +} + +// verifyBounded runs cat.Verify in a goroutine and returns its result, or +// fails the test when it has not returned within verifyEscape. The cleanup, +// registered before the launch, releases the held read and joins the call. +func verifyBounded(t *testing.T, cat *Catalog, ctx context.Context, opts VerifyOptions, held *heldReads) (VerifyResult, error) { + t.Helper() + done := make(chan verifyOutcome, 1) + t.Cleanup(func() { + held.release() + select { + case out := <-done: + done <- out + case <-time.After(verifyEscape): + t.Error("Verify did not return even after its held read was released") + } + }) + go func() { + res, err := cat.Verify(ctx, "v1", opts) + done <- verifyOutcome{res, err} + }() + select { + case out := <-done: + done <- out // for the cleanup's join + return out.res, out.err + case <-time.After(verifyEscape): + t.Fatalf("Verify did not return within %s: the read in progress was not cancelled and joined", verifyEscape) + return VerifyResult{}, nil + } +} + +func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { + h.mu.Lock() + h.active++ + h.mu.Unlock() + defer func() { + h.mu.Lock() + h.active-- + h.mu.Unlock() + }() + if fid != h.fid { + return h.Blobs.Get(ctx, fid) + } + h.once.Do(func() { + close(h.entered) + if h.onEnter != nil { + h.onEnter() + } + }) + select { + case <-ctx.Done(): + case <-h.released: + return nil, fmt.Errorf("chunkstore: read %s: released by the test", fid) + } + h.mu.Lock() + h.ended = ctx.Err() + h.mu.Unlock() + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, ctx.Err()) +} + +func (h *heldReads) state() (active int, ended error) { + h.mu.Lock() + defer h.mu.Unlock() + return h.active, h.ended +} + +var errFilerDown = errors.New("filer: connection refused") + +// tickingClock advances by step at every reading: with a refresh interval +// of step, a pass refreshes HEAD at every opportunity, without waiting. +func tickingClock(step time.Duration) func() time.Time { + var mu sync.Mutex + now := time.Now() + return func() time.Time { + mu.Lock() + defer mu.Unlock() + now = now.Add(step) + return now + } +} + +// headFailsDuringRead fails HEAD reads made while the held read is in +// progress. The first HEAD read after the chunk key listing passes (it is +// the refresh before the first chunk, the held one, is handed to a reader); +// later ones wait until the held read has started, then fail. +type headFailsDuringRead struct { + Filer + root, keys string + entered <-chan struct{} + released <-chan struct{} // the test's escape + + mu sync.Mutex + listed bool + after int // HEAD reads since the listing +} + +func (f *headFailsDuringRead) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if dir == f.keys { + f.mu.Lock() + f.listed = true + f.mu.Unlock() + } + return f.Filer.ListEntries(ctx, dir, prefix, after, limit) +} + +func (f *headFailsDuringRead) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + n := 0 + if f.listed { + f.after++ + n = f.after + } + f.mu.Unlock() + if n >= 2 { + select { + case <-f.entered: + return nil, errFilerDown + case <-ctx.Done(): + return nil, ctx.Err() + case <-f.released: + return nil, errors.New("released by the test") + } + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD refresh that fails while a chunk read is in progress stops that +// read at once: Verify returns the filer's error (not the cancellation it +// caused in the reader), incomplete, with no read left running, and long +// before the caller's own deadline. +func TestVerify_FailedRefreshCancelsReadInProgress(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), + entered: held.entered, released: held.released} + cat, err := NewCatalog(manifestFilerBlobs{filer, held}, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + // The caller's deadline tells a read cancelled by the failed refresh + // from one that ran into it: Verify must end well before it. + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}, held) + active, ended := held.state() + if !errors.Is(err, errFilerDown) || !strings.Contains(err.Error(), "refresh HEAD") { + t.Fatalf("verify: %v; want the HEAD refresh error", err) + } + if ctx.Err() != nil || !errors.Is(ended, context.Canceled) { + t.Fatalf("held read ended with %v (caller context %v); want cancelled by the failed refresh", ended, ctx.Err()) + } + if res.Complete || active != 0 { + t.Fatalf("complete %v, %d reads still running; want incomplete, none", res.Complete, active) + } +} + +// Cancelling the caller's context while a chunk read is in progress ends +// that read and the pass: incomplete, the cancellation reported, no read +// left running. +func TestVerify_CancelDuringReadJoinsReaders(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + cat, err := NewCatalog(manifestFilerBlobs{fx.f, held}, catBase) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + held.onEnter = cancel + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}, held) + active, ended := held.state() + select { + case <-held.entered: + default: + t.Fatal("the held read never started") + } + if !errors.Is(err, context.Canceled) || res.Complete || !errors.Is(ended, context.Canceled) || active != 0 { + t.Fatalf("verify: %v, complete %v; held read ended with %v, %d reads still running", err, res.Complete, ended, active) + } + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("covered gens %v, want [%d]", res.HeadGens, h.Gen) + } +} + +// republish installs a new HEAD for vol with the current chunk references +// as edit leaves them (keys are not uploaded again). +func (fx *verifyFixture) republish(vol string, edit func(map[uint64]storage.ChunkRef)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: cur.RemoteLSN + 1, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + edit(next.Chunks) + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// wrongHash flips the reference SHA-256 of chunk idx, keeping its key. +func wrongHash(idx uint64) func(map[uint64]storage.ChunkRef) { + return func(c map[uint64]storage.ChunkRef) { + ref := c[idx] + ref.SHA256[0] ^= 0xff + c[idx] = ref + } +} + +// beforeRead runs fn once, before the first read of fid. +type beforeRead struct { + Blobs + fid string + fn func() + once sync.Once +} + +func (b *beforeRead) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == b.fid { + b.once.Do(b.fn) + } + return b.Blobs.Get(ctx, fid) +} + +// A final reference to a chunk under the same key but with another SHA-256 +// is a finding: at depth data it is compared with the content read once for +// that chunk (the chunk is not read again), below data with the other final +// references. A reference only an earlier HEAD view carried is not compared +// (detail "": no finding). +func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { + for _, tc := range []struct { + name string + depth VerifyDepth + when string // "walked": HEAD changes once the first view is walked; "read": once chunk 0 was read; "snapshot": before the pass + detail string + }{ + {"refreshed HEAD, data, before the read", VerifyData, "walked", "needle SHA-256"}, + {"refreshed HEAD, data, after the read", VerifyData, "read", "needle SHA-256"}, + {"refreshed HEAD, bindings", VerifyBindings, "walked", ""}, + {"snapshot, data", VerifyData, "snapshot", "needle SHA-256"}, + {"snapshot, bindings", VerifyBindings, "snapshot", "disagree"}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid0 := fx.fid(h1.Chunks[0].Key) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + cat := fx.c + switch tc.when { + case "walked": + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.republish("v1", wrongHash(0)) + } + } + case "read": + // One reader: chunk 0 is read completely before chunk 1 is + // handed out, so its content is known when HEAD changes. + br := &beforeRead{Blobs: fx.cb, fid: fx.fid(h1.Chunks[1].Key), fn: func() { h2 = fx.republish("v1", wrongHash(0)) }} + var err error + if cat, err = NewCatalog(manifestFilerBlobs{fx.f, br}, catBase); err != nil { + t.Fatal(err) + } + case "snapshot": + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h1); err != nil { + t.Fatal(err) + } + h2 = fx.republish("v1", wrongHash(0)) + opts.AllSnapshots = true + } + cat.SetClock(tickingClock(time.Minute)) + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + if tc.detail == "" { + wantClasses(t, tc.name, res) + return + } + wantClasses(t, tc.name, res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + wantRoot := headLabel(h2.Gen) + if tc.when == "snapshot" && tc.depth != VerifyData { + // HEAD is walked first; the snapshot's reference is the one + // that disagrees with it. + wantRoot = "snapshot s1/" + } + if !strings.HasPrefix(f.Root, wantRoot) || !strings.Contains(f.Detail, tc.detail) || f.Key == "" { + t.Fatalf("finding %+v; want under %q, detail with %q", f, wantRoot, tc.detail) + } + if tc.when != "snapshot" && (len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen) { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if tc.depth == VerifyData && (res.DistinctChunksRead != 2 || fx.cb.reads(fid0) != 1) { + t.Fatalf("read %d chunks, chunk 0 %d times; want 2, chunk 0 once", res.DistinctChunksRead, fx.cb.reads(fid0)) + } + }) + } +} + +// A chunk read once whose final references (HEAD and an active snapshot) +// carry two different wrong SHA-256s is one CONTENT_MISMATCH, under HEAD, +// whose detail counts the other differing reference and names its root. +func TestVerify_TwoWrongReferencesAreOneFinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + h2 := fx.republish("v1", wrongHash(0)) // the snapshot keeps this wrong hash + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h2); err != nil { + t.Fatal(err) + } + h3 := fx.republish("v1", func(c map[uint64]storage.ChunkRef) { // HEAD: another wrong hash, same key + ref := c[0] + ref.SHA256[1] ^= 0xff + c[0] = ref + }) + if h3.Chunks[0].Key != h1.Chunks[0].Key || h3.Chunks[0].SHA256 == h2.Chunks[0].SHA256 || h2.Chunks[0].SHA256 == h1.Chunks[0].SHA256 { + t.Fatal("fixture: one key, three different reference hashes") + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1}) + wantClasses(t, "two wrong references", res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + if f.Root != headLabel(h3.Gen) || !strings.Contains(f.Detail, "1 more") || !strings.Contains(f.Detail, "snapshot s1/") { + t.Fatalf("finding %+v; want under %q, detail counting 1 more differing reference under the snapshot", f, headLabel(h3.Gen)) + } + if n := fx.cb.reads(fx.fid(h1.Chunks[0].Key)); n != 1 { + t.Fatalf("chunk read %d times, want once", n) + } +} + +// A schedule point: where a world event lands relative to the pass. +type schedPoint string + +const ( + atWalked schedPoint = "walked" // after the first HEAD view, before any check + atChecked schedPoint = "checked" // after the first batch of checks has settled + atClosing schedPoint = "closing" // just before the first closing read + atDuring schedPoint = "during" // while chunk K's read is in progress +) + +// verifyFixture.schedule runs a data-depth pass over v1 whose owner applies +// steps[i] at points[i] (several steps at one point run in order). HEAD is +// re-read at every opportunity; fidK is the chunk whose read is "during". +func (fx *verifyFixture) schedule(fidK string, steps []func(), points []schedPoint) VerifyResult { + fx.t.Helper() + var mu sync.Mutex + pending := map[schedPoint][]func(){} + for i, p := range points { + pending[p] = append(pending[p], steps[i]) + } + fire := func(p schedPoint) { + mu.Lock() + fs := pending[p] + delete(pending, p) + mu.Unlock() + for _, f := range fs { + f() + } + } + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + opts.hook = func(stage string) { + switch stage { + case verifyHookHeadWalked: + fire(atWalked) + case verifyHookBatchChecked: + fire(atChecked) + case verifyHookClosingRead: + fire(atClosing) + } + } + during := &beforeRead{Blobs: fx.cb, fid: fidK, fn: func() { fire(atDuring) }} + cat, err := NewCatalog(manifestFilerBlobs{fx.f, during}, catBase) + if err != nil { + fx.t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + fx.t.Fatalf("verify: %v, %+v", err, res) + } + if len(pending) != 0 { + fx.t.Fatalf("schedule points never reached: %v", pending) + } + return res +} + +// The same owner events in different interleavings with the pass's checks +// and HEAD reads give the same findings: the findings are computed at the +// end, from each chunk's one outcome and the roots at the final read. K is +// chunk 0 (index 0), L chunk 1; "bad" means K's needle is missing. +func TestVerify_SchedulesGiveTheSameFindings(t *testing.T) { + moveK := func(c map[uint64]storage.ChunkRef) { c[1] = c[0]; delete(c, 0) } + addK1 := func(c map[uint64]storage.ChunkRef) { c[1] = c[0] } + dropK := func(c map[uint64]storage.ChunkRef) { delete(c, 0) } + type edit = func(c map[uint64]storage.ChunkRef) + for _, tc := range []struct { + name string + bad bool + edits []edit // the owner's publishes, in order (nil: restore K at index 0) + interleave [][]schedPoint + want []string + superseded int + finalGenStep int // findings are under the HEAD this many publishes after the first (all of them) + }{ + {"K moves from index 0 to 1, its check fails", true, []edit{moveK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"a reference to K arrives after K settled bad", true, []edit{addK1, dropK}, + [][]schedPoint{{atWalked, atWalked}, {atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 2}, + {"K is bad, a refresh keeps index 0 and adds index 1", true, []edit{addK1}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@0"}, 0, 1}, + {"settlement and refresh overlap", true, []edit{moveK}, + [][]schedPoint{{atDuring}, {atWalked}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"K is named, not named, named again (bad)", true, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@0", "ROOT_INVALID@0"}, 0, 2}, + {"K is named, not named, named again (good)", false, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"ROOT_INVALID@0"}, 0, 2}, + {"K is bad and the final view does not name it", true, []edit{dropK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, nil, 1, 1}, + } { + for _, points := range tc.interleave { + t.Run(fmt.Sprintf("%s/%v", tc.name, points), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + k := h1.Chunks[0] + fidK := fx.fid(k.Key) + if tc.bad { + fx.needle(fidK, dropNeedle) + } + var last storage.ChunkHead + steps := make([]func(), len(tc.edits)) + for i, e := range tc.edits { + if e == nil { + e = func(c map[uint64]storage.ChunkRef) { c[0] = k } + } + steps[i] = func() { last = fx.republish("v1", e) } + } + res := fx.schedule(fidK, steps, points) + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root != headLabel(last.Gen) || f.Key == "" { + t.Fatalf("finding %+v; want under %q (the final HEAD view)", f, headLabel(last.Gen)) + } + } + if res.SupersededDuringVerify != tc.superseded || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want %d, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify, tc.superseded) + } + if res.HeadGens[len(res.HeadGens)-1] != last.Gen { + t.Fatalf("covered gens %v; want the last one %d", res.HeadGens, last.Gen) + } + // One check per chunk, however often HEAD names it again. + if n := fx.cb.reads(fidK); n != 1 { + t.Fatalf("chunk K read %d times, want once", n) + } + }) + } + } +} + +// A publish that lands while the pass makes its closing read is not missed: +// the read names a chunk not seen before, so the pass checks it and reads +// again; a bad new chunk is a finding, not a clean pass. +func TestVerify_PublishDuringClosingReadIsChecked(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var h2 storage.ChunkHead + steps := []func(){func() { + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + }} + res := fx.schedule(fx.fid(h1.Chunks[0].Key), steps, []schedPoint{atClosing}) + wantClasses(t, "publish during the closing read", res, "NEEDLE_MISSING@2") + if res.Findings[0].Root != headLabel(h2.Gen) || fx.cb.reads(fx.fid(h2.Chunks[2].Key)) != 1 { + t.Fatalf("finding %+v, new chunk read %d times; want under %q, read once", res.Findings[0], fx.cb.reads(fx.fid(h2.Chunks[2].Key)), headLabel(h2.Gen)) + } + if len(res.HeadGens) != 2 || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } +} + +// An owner that publishes a new chunk before every closing read keeps the +// pass from closing: after ClosingRounds such reads the result is +// incomplete (never clean), with its reason and the findings computed from +// what was checked. +func TestVerify_ClosingRoundsExhaustedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + reads := 0 + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookClosingRead { + reads++ + fx.publish("v1", map[uint64][]byte{uint64(2 + reads): verifyData(byte(10 + reads))}, true) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != VerifyIncompleteRounds { + t.Fatalf("verify: %v, complete %v, incomplete %q; want %s, incomplete for the closing rounds", err, res.Complete, res.Incomplete, CodeVerifyIncomplete) + } + if reads != DefaultVerifyClosingRounds { + t.Fatalf("%d closing reads, want %d", reads, DefaultVerifyClosingRounds) + } + wantClasses(t, "partial findings", res, "NEEDLE_MISSING@0") +} + +// retagSnapshot rewrites one field of the document of the attempt snapshot +// name resolves to, leaving it otherwise valid. +func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { + fx.t.Helper() + ctx := context.Background() + ref, ok, err := fx.c.resolveSnap(ctx, vol, name) + if err != nil || !ok || ref.entry == nil { + fx.t.Fatalf("snapshot %s/%s: %v %v", vol, name, ok, err) + } + dir := path.Join(catBase, vol, snapsDir, name) + e, err := fx.f.LookupEntry(ctx, dir, ref.rec.Attempt) + if err != nil { + fx.t.Fatal(err) + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(e.Content, &doc); err != nil { + fx.t.Fatal(err) + } + if doc[field], err = json.Marshal(value); err != nil { + fx.t.Fatal(err) + } + if e.Content, err = json.Marshal(doc); err != nil { + fx.t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, dir, e, nil); err != nil { + fx.t.Fatal(err) + } + return ref.rec.Attempt +} + +// A snapshot is checked under the name and volume it was found at. A +// document that names another snapshot or volume is ROOT_INVALID, and a +// miss under that still published attempt is reported under the name it +// was found at, never excused as a snapshot deleted during the pass. +func TestVerify_SnapshotDocumentNamingAnotherSnapshot(t *testing.T) { + for _, tc := range []struct { + name, field, value string + opts VerifyOptions + }{ + {"named, another name", "name", "s2", VerifyOptions{Snapshot: "s1"}}, + {"all, another name", "name", "s2", VerifyOptions{AllSnapshots: true}}, + {"named, another volume", "volume_id", "v9", VerifyOptions{Snapshot: "s1"}}, + {"all, another volume", "volume_id", "v9", VerifyOptions{AllSnapshots: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD moves on: only the snapshot names the old chunk 0, whose binding goes. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + attempt := fx.retagSnapshot("v1", "s1", tc.field, tc.value) + fx.deleteBinding(h.Chunks[0].Key) + res := fx.verify("v1", tc.opts) + wantClasses(t, tc.name, res, "ROOT_INVALID", "BINDING_MISSING@0") + label := "snapshot s1/" + attempt + if res.Findings[0].Root != label || res.Findings[1].Root != label || !strings.Contains(res.Findings[0].Detail, tc.value) { + t.Fatalf("findings %+v; want both under %q", res.Findings, label) + } + if len(res.Snapshots) != 1 || res.Snapshots[0] != "s1/"+attempt || res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 { + t.Fatalf("snapshots %v, root deleted %d, deleted %v; want [s1/%s], 0, none", + res.Snapshots, res.RootDeletedDuringVerify, res.SnapshotsDeletedDuringVerify, attempt) + } + }) + } +} + +// The closing read decides the final view: a HEAD that is gone, or that +// does not decode, leaves no HEAD root and makes the pass incomplete; it +// never closes on an earlier view. A bad chunk only that HEAD named is then +// counted as superseded, not reported. +func TestVerify_ClosingReadWithoutUsableHeadIsIncomplete(t *testing.T) { + for _, tc := range []struct { + name string + bad bool // chunk 0's needle is missing + undecoded bool // the closing read finds a HEAD that does not decode (else none) + want []string + reason VerifyIncomplete + superseded int + }{ + {"HEAD gone, bad chunk", true, false, nil, VerifyIncompleteHeadAbsent, 1}, + {"HEAD gone, good chunks", false, false, nil, VerifyIncompleteHeadAbsent, 0}, + {"HEAD does not decode", true, true, []string{"ROOT_INVALID"}, VerifyIncompleteHeadInvalid, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if tc.bad { + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + done := false + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage != verifyHookClosingRead || done { + return + } + done = true + if tc.undecoded { + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + } else if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), headName, nil); err != nil { + t.Error(err) + } + } + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != tc.reason { + t.Fatalf("verify: %v, complete %v, incomplete %q; want incomplete %q", err, res.Complete, res.Incomplete, tc.reason) + } + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root == headLabel(h.Gen) { + t.Fatalf("finding %+v under the HEAD the closing read no longer returned", f) + } + } + if res.SupersededDuringVerify != tc.superseded { + t.Fatalf("superseded %d, want %d", res.SupersededDuringVerify, tc.superseded) + } + }) + } +} + +// casHead installs a HEAD whose segment references edit changes, without +// writing segments (the current HEAD is read without resolving them, so it +// may already carry a wrong reference). +func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.ChunkSegment)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, ok, err := fx.c.ReadHead(ctx, vol) + if err != nil || !ok { + fx.t.Fatalf("HEAD of %s: %v %v", vol, ok, err) + } + next := cur + next.Chunks = nil + next.RemoteLSN = cur.RemoteLSN + 1 + next.Segments = map[uint64]storage.ChunkSegment{} + for g, s := range cur.Segments { + next.Segments[g] = s + } + edit(next.Segments) + next.ManifestChunkCount = 0 + for _, s := range next.Segments { + next.ManifestChunkCount += s.Count + } + if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { + fx.t.Fatal(err) + } + return next +} + +// A segment is one object per (owner, key), read once: HEAD and an active +// snapshot naming one segment key with different reference hashes share its +// one outcome. A failed read is one READ_ERROR, under HEAD, counted once; a +// readable segment is used by the root whose reference matches its content, +// and the other root gets one mismatch finding. +func TestVerify_SegmentIsOneObjectPerKey(t *testing.T) { + for _, readFails := range []bool{true, false} { + t.Run(fmt.Sprintf("read fails=%v", readFails), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD names the same segment key with another reference hash. + h2 := fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + s.SHA256[0] ^= 0xff + segs[0] = s + }) + segFid := fx.fid(h.Segments[0].Key) + if readFails { + fx.cb.failReads(segFid, -1) + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyBindings, AllSnapshots: true}) + wantReads := 1 + if readFails { + wantClasses(t, "segment read fails", res, "READ_ERROR@seg0") + wantReads = verifyReadAttempts // one read, with its retries + if res.ChunksNotRead != 1 { + t.Fatalf("chunksNotRead %d, want 1", res.ChunksNotRead) + } + } else { + wantClasses(t, "segment matches the snapshot only", res, "CONTENT_MISMATCH@seg0") + // The snapshot's reference matches: its chunks are walked and checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 { + t.Fatalf("chunks checked %d, distinct %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks) + } + } + if f := res.Findings[0]; f.Root != headLabel(h2.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q for the segment key", f, headLabel(h2.Gen)) + } + if n := fx.cb.reads(segFid); n != wantReads { + t.Fatalf("segment read %d times, want %d", n, wantReads) + } + }) + } +} + +// headLookups counts the HEAD reads a pass makes. +type headLookups struct { + Filer + root string + mu sync.Mutex + n int +} + +func (f *headLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + f.n++ + f.mu.Unlock() + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +func (f *headLookups) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.n +} + +// The quiet closing read is the final view: no HEAD read follows it, and a +// publication that lands right after it is not part of this pass. +func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + filer := &headLookups{Filer: fx.f, root: path.Join(catBase, "v1")} + cat, err := NewCatalog(manifestFilerBlobs{filer, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + beforeRound, atClose := -1, -1 + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + switch stage { + case verifyHookClosingRead: + if beforeRound < 0 { + beforeRound = filer.count() // before the closing round reads anything + } + case verifyHookClosed: + atClose = filer.count() + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + if beforeRound < 0 || atClose < 0 { + t.Fatal("the quiet closing read was never reached") + } + // The closing round reads HEAD exactly once, and nothing reads it after. + if n := filer.count(); n-beforeRound != 1 { + t.Fatalf("%d HEAD reads from the start of the closing round to the end of the pass, want 1", n-beforeRound) + } + wantClasses(t, "publication after the quiet read", res) + if res.HeadGens[len(res.HeadGens)-1] != h.Gen || h2.Gen <= h.Gen { + t.Fatalf("covered gens %v (published %d after the close); want the quiet read's %d last", res.HeadGens, h2.Gen, h.Gen) + } +} + +// HEAD and an active snapshot name one segment key; the snapshot's reference +// is valid, HEAD's is changed by edit. Whichever reference the pass meets +// first, the findings are the same: each reference is judged against the +// segment's one outcome at the end, nothing about a reference is kept. +func TestVerify_SegmentFindingsDoNotDependOnOrder(t *testing.T) { + for _, tc := range []struct { + name string + edit func(s *storage.ChunkSegment) + want string + }{ + {"HEAD's reference has the right hash and wrong fields", func(s *storage.ChunkSegment) { s.Count++ }, "SEGMENT_UNREADABLE@seg0"}, + {"HEAD's reference has a wrong hash", func(s *storage.ChunkSegment) { s.SHA256[0] ^= 0xff }, "CONTENT_MISMATCH@seg0"}, + } { + for _, headFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/HEAD's reference first=%v", tc.name, headFirst), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + var bad storage.ChunkHead + breakHead := func() { + bad = fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + tc.edit(&s) + segs[0] = s + }) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1} + if headFirst { + breakHead() // the pass starts on HEAD's changed reference + } else { + // The pass first meets the valid reference (HEAD and the + // snapshot share it); the changed one comes at the closing read. + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + breakHead() + } + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res, tc.want) + if f := res.Findings[0]; f.Root != headLabel(bad.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q", f, headLabel(bad.Gen)) + } + // The snapshot's valid reference is used: its chunks are checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 { + t.Fatalf("chunks checked %d, distinct %d, read %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks, res.DistinctChunksRead) + } + if n := fx.cb.reads(fx.fid(h.Segments[0].Key)); n != 1 { + t.Fatalf("segment read %d times, want once", n) + } + }) + } + } +} + +// A problem under a reference that the final view no longer carries is not +// a finding, but it is counted once (superseded): the segment HEAD named +// with a wrong hash and then dropped; the segment HEAD named with a wrong +// hash and then named again soundly; a chunk read whose content a dropped +// reference did not match. +func TestVerify_DroppedReferenceProblemIsCounted(t *testing.T) { + wrongSegHash := func(segs map[uint64]storage.ChunkSegment) { s := segs[0]; s.SHA256[0] ^= 0xff; segs[0] = s } + for _, tc := range []struct { + name string + setup func(fx *verifyFixture) (before, during func()) + }{ + {"segment with a wrong hash, then dropped", func(fx *verifyFixture) (func(), func()) { + fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { delete(segs, 0) }) } + }}, + {"segment with a wrong hash, then named soundly", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { segs[0] = h.Segments[0] }) } + }}, + {"chunk read, a dropped reference did not match it", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.republish("v1", wrongHash(0)) }, + func() { fx.republish("v1", func(c map[uint64]storage.ChunkRef) { c[0] = h.Chunks[0] }) } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + before, during := tc.setup(fx) + before() + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + during() + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res) + if res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want 1, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go new file mode 100644 index 0000000000..fee3162129 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go @@ -0,0 +1,102 @@ +package durable + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestAttachReadinessWaitFailsFastOnTerminalState pins that an I/O waiting for +// chunk attachment returns at once, without another readiness wait, when an +// observer install failed, readiness was withdrawn or a fence is seen. +func TestAttachReadinessWaitFailsFastOnTerminalState(t *testing.T) { + for _, tc := range []struct { + name string + // before runs before the read; afterRefusal runs between the first gate + // refusal and the wait; whileWaiting runs once the read is waiting. + before func(t *testing.T, b *StorageBackend) + afterRefusal func(b *StorageBackend) + whileWaiting func(b *StorageBackend) + want error + wantWaits int32 + }{ + { + name: "observer install failed", + before: func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }, + want: frontend.ErrNotReady, + }, + { + name: "fence seen after the attach refusal", + afterRefusal: func(b *StorageBackend) { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + }, + want: frontend.ErrStalePrimary, + }, + { + name: "readiness withdrawn while waiting", + whileWaiting: func(b *StorageBackend) { b.SetOperational(false, "host drain") }, + want: frontend.ErrNotReady, + wantWaits: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + b.setChunkAttachPending("attachment pending") + if tc.before != nil { + tc.before(t, b) + } + if tc.afterRefusal != nil { + b.testAfterAttachRefusal = func() { tc.afterRefusal(b) } + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var waits atomic.Int32 + waiting, resume := make(chan struct{}), make(chan struct{}) + b.testBeforeReadReadyWait = func() { + if waits.Add(1) == 1 && tc.whileWaiting != nil { + close(waiting) + <-resume + return + } + // A wait the rule forbids: end it now instead of after 3 s. + cancel() + } + result := make(chan error, 1) + go func() { + _, err := b.Read(ctx, 0, make([]byte, 4096)) + result <- err + }() + if tc.whileWaiting != nil { + select { + case <-waiting: + case <-time.After(3 * time.Second): + t.Fatal("read never waited for attachment readiness") + } + tc.whileWaiting(b) + close(resume) + } + var err error + select { + case err = <-result: + case <-time.After(5 * time.Second): + t.Fatal("read did not return") + } + if got := waits.Load(); got != tc.wantWaits { + t.Fatalf("read waited %d times for readiness, want %d (err=%v)", got, tc.wantWaits, err) + } + if !errors.Is(err, tc.want) { + t.Fatalf("err=%v, want %v", err, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/plain_detach_closed_test.go b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go new file mode 100644 index 0000000000..07740f2329 --- /dev/null +++ b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go @@ -0,0 +1,20 @@ +package durable + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestPlainDetachStopRefusesClosedBackend pins that the plain-detach stop of a +// closed backend returns ErrBackendClosed instead of reporting a clean stop. +func TestPlainDetachStopRefusesClosedBackend(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + if err := b.Close(); err != nil { + t.Fatal(err) + } + if err := b.stopPlainDetachIfIdle(); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("plain-detach stop of a closed backend: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go new file mode 100644 index 0000000000..541e1feb39 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go @@ -0,0 +1,162 @@ +package durable + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// heldReadStore parks each ReadContext call on its LBA until the test releases +// that LBA, so every Read stays an admitted I/O for as long as the test needs. +type heldReadStore struct { + storage.LogicalStorage + entered chan uint32 + release map[uint32]chan struct{} +} + +func newHeldReadStore(lbas ...uint32) *heldReadStore { + s := &heldReadStore{entered: make(chan uint32, len(lbas)), release: make(map[uint32]chan struct{}, len(lbas))} + for _, lba := range lbas { + s.release[lba] = make(chan struct{}) + } + return s +} + +func (s *heldReadStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) { + s.entered <- lba + select { + case <-s.release[lba]: + return make([]byte, 4096), nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (s *heldReadStore) Read(lba uint32) ([]byte, error) { + return s.ReadContext(context.Background(), lba) +} + +func (s *heldReadStore) NextLSN() uint64 { return 1 } + +// precopyTestBackend is an operational backend over store with a matching +// healthy projection, so admission depends only on the state under test. +func precopyTestBackend(store storage.LogicalStorage) *StorageBackend { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.SetOperational(true, "serving") + return b +} + +// startHeldReads starts one Read per LBA and returns once every one of them is +// admitted and parked inside storage. Cleanup releases and joins them. +func startHeldReads(t *testing.T, b *StorageBackend, store *heldReadStore, lbas ...uint32) <-chan error { + t.Helper() + done := make(chan error, len(lbas)) + for _, lba := range lbas { + go func(off int64) { + _, err := b.Read(context.Background(), off, make([]byte, 4096)) + done <- err + }(int64(lba) * 4096) + } + t.Cleanup(func() { + for _, ch := range store.release { + select { + case <-ch: + default: + close(ch) + } + } + _ = b.Close() + }) + for range lbas { + select { + case <-store.entered: + case <-time.After(3 * time.Second): + t.Fatal("read never reached storage") + } + } + return done +} + +// installedPause waits until BeginPrecopyPause has installed its pause and +// returns the pause's drain channel. +func installedPause(t *testing.T, b *StorageBackend) <-chan struct{} { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for { + b.mu.Lock() + p := b.precopy + b.mu.Unlock() + if p != nil { + return p.drained + } + if time.Now().After(deadline) { + t.Fatal("pre-copy pause was never installed") + } + time.Sleep(time.Millisecond) + } +} + +type pauseResult struct { + resume func() + err error +} + +func beginPauseAsync(ctx context.Context, b *StorageBackend) <-chan pauseResult { + out := make(chan pauseResult, 1) + go func() { + resume, err := b.BeginPrecopyPause(ctx) + out <- pauseResult{resume, err} + }() + return out +} + +// TestPrecopyDrainWaitsForEveryAdmittedIO pins that a pre-copy pause reports +// its drain done only after every I/O admitted before it has finished, not +// when the first of several completes. +func TestPrecopyDrainWaitsForEveryAdmittedIO(t *testing.T) { + store := newHeldReadStore(0, 1) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0, 1) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pause := beginPauseAsync(ctx, b) + drained := installedPause(t, b) + + close(store.release[0]) + if err := <-reads; err != nil { + t.Fatalf("first admitted read: %v", err) + } + // The first read has returned, so its admission release has run. + select { + case <-drained: + t.Fatal("drain reported done while a second admitted I/O is still in flight") + default: + } + select { + case r := <-pause: + t.Fatalf("pause returned while a second admitted I/O is still in flight: err=%v", r.err) + default: + } + + close(store.release[1]) + if err := <-reads; err != nil { + t.Fatalf("second admitted read: %v", err) + } + select { + case r := <-pause: + if r.err != nil { + t.Fatalf("drain after the last admitted I/O: %v", r.err) + } + r.resume() + case <-time.After(3 * time.Second): + t.Fatal("drain not reported done after the last admitted I/O finished") + } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume did not reopen admission: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go new file mode 100644 index 0000000000..1acde5c023 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go @@ -0,0 +1,80 @@ +package durable + +import ( + "context" + "testing" + "time" +) + +// TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose pins that a pre-copy +// drain still pending when the backend loses readiness or is closed ends with +// an error and never reports a clean drain. +func TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + // bound is the drain's caller context, as the pre-copy caller gives it. + bound time.Duration + spoil func(b *StorageBackend) + }{ + {"readiness lost", 3 * time.Second, func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + // Close does not signal the drain; the waiter ends at its own bound. + {"closed", 200 * time.Millisecond, func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + store := newHeldReadStore(0) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0) + ctx, cancel := context.WithTimeout(context.Background(), tc.bound) + defer cancel() + pause := beginPauseAsync(ctx, b) + installedPause(t, b) + + tc.spoil(b) + close(store.release[0]) + <-reads + select { + case r := <-pause: + if r.err == nil { + r.resume() + t.Fatal("drain reported clean after the backend became unusable") + } + case <-time.After(tc.bound + 3*time.Second): + t.Fatal("drain waiter did not end") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("failed drain left its pause installed") + } + }) + } +} + +// TestPrecopyFinalStopRefusedAfterReadinessLossOrClose pins that the final +// pre-copy stop refuses to commit a freeze when the backend lost readiness or +// was closed after the drain completed. +func TestPrecopyFinalStopRefusedAfterReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(b *StorageBackend) + }{ + {"readiness lost", func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + {"closed", func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + tc.spoil(b) + if b.TryStopIO("chunk pre-copy: final detached cut") { + t.Fatal("final stop committed a freeze on an unusable backend") + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go new file mode 100644 index 0000000000..fb8b5b3bb2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go @@ -0,0 +1,81 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" +) + +type refusingRebaser struct{} + +func (refusingRebaser) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (refusingRebaser) Sync(context.Context, uint64) error { return nil } +func (refusingRebaser) RebaseShipLSN(uint64) error { + return errors.New("injected: ship LSN cannot follow the store") +} + +// TestPrecopyPauseRefusedOnUnusableBackend pins that a pre-copy pause never +// begins on a backend that is closed, not operational, has a failed observer +// install, or already has a pause installed. +func TestPrecopyPauseRefusedOnUnusableBackend(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(t *testing.T, b *StorageBackend) + }{ + {"observer install failed", func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }}, + {"closed", func(t *testing.T, b *StorageBackend) { _ = b.Close() }}, + {"not operational", func(t *testing.T, b *StorageBackend) { b.SetOperational(false, "host drain") }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + tc.spoil(t, b) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err == nil { + resume() + t.Fatal("pre-copy pause began on an unusable backend") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("refused pause left a pause installed") + } + }) + } + + t.Run("already paused", func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + b.mu.Lock() + first := b.precopy + b.mu.Unlock() + second, err := b.BeginPrecopyPause(ctx) + if err == nil { + second() + t.Fatal("second pre-copy pause began while one is installed") + } + b.mu.Lock() + current := b.precopy + b.mu.Unlock() + if current != first { + t.Fatal("refused second pause replaced the installed pause") + } + resume() + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume of the first pause did not reopen admission: %v", err) + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 06dbe352ee..39f54d80c2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -199,6 +199,16 @@ type ProviderConfig struct { // call back into the provider. OnChunkDetach func(volumeID string) uint64 OnChunkDetachResumed func(volumeID string, attempt uint64) + // ChunkOnPublishSettled, optional, is called once per confirmed + // publication of a chunk volume's HEAD, with the HEAD before and after it + // (storage.ChunkLayerConfig.OnPublishSettled): serialized, in publication + // order, outside the capture lock, by the volume's one registered drainer + // (whichever publishing caller is draining; a publisher may return before + // its own report is delivered). ctx ends when the volume's layer closes; + // after that no report is dequeued, though one already dequeued may still + // be delivered. It must return without blocking and without remote calls: + // enqueue work to your own worker (it is a guest-visible wait on detach). + ChunkOnPublishSettled func(ctx context.Context, volumeID string, prev, next storage.ChunkHead) // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c194a39e8..c418aa15d4 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -376,6 +376,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} } cfg := storage.ChunkLayerConfig{ + OnPublishSettled: p.publishSettledHook(volumeID), ChunkBlocks: p.cfg.ChunkBlocks, RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), HeadCoolingWindow: p.cfg.ChunkHeadCoolingWindow, @@ -389,6 +390,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, COWSpillLimit: p.cfg.ChunkCOWSpillLimit, + COWSpillFree: spillFree(p.cfg.StorageRoot), CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { @@ -1303,3 +1305,12 @@ func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next st defer end() return r.builder.PrepareManifest(c, base, next, chunkBytes) } + +// publishSettledHook adapts ChunkOnPublishSettled to one volume's layer. +func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Context, storage.ChunkHead, storage.ChunkHead) { + hook := p.cfg.ChunkOnPublishSettled + if hook == nil { + return nil + } + return func(ctx context.Context, prev, next storage.ChunkHead) { hook(ctx, volumeID, prev, next) } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index bbea2993a2..74526bc5b6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -4,6 +4,7 @@ package durable_test import ( "context" + "fmt" "sync" "sync/atomic" "testing" @@ -164,6 +165,44 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { } } +// ChunkOnPublishSettled sees every confirmed publication of a volume, with +// its volume id and the HEAD before and after it; a no-op capture is not one. +func TestWALStoreChunk_PublishSettledHook(t *testing.T) { + remote := storage.NewMemChunkRemote() + var mu sync.Mutex + var got []string + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkOnPublishSettled: func(_ context.Context, volumeID string, prev, next storage.ChunkHead) { + mu.Lock() + got = append(got, fmt.Sprintf("%s:%d->%d", volumeID, prev.Gen, next.Gen)) + mu.Unlock() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s := openRecovered(t, p) + for i, lba := range []uint32{1, 0, pcChunkBlocks + 1} { + if lba != 0 { + if _, err := s.Write(lba, block(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != "v1:0->1" || got[1] != "v1:1->2" { + t.Fatalf("reports %v; want [v1:0->1 v1:1->2] (the middle capture changed nothing)", got) + } +} + // gatedCASRemote holds the next HEAD CAS, once armed, until it is released // (or its context ends), and reports when that CAS started. type gatedCASRemote struct { diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go new file mode 100644 index 0000000000..6956c2d0f5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -0,0 +1,74 @@ +package durable + +import ( + "context" + "errors" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// chunkRestorer is the chunk layer's independent-restore surface. +type chunkRestorer interface { + HydrateAllAt(ctx context.Context, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (storage.OwnProgress, error) +} + +func (p *DurableProvider) restorer(volumeID string) (chunkRestorer, error) { + _, layer, err := p.chunkHandle(volumeID) + if err != nil { + return nil, err + } + r, ok := layer.(chunkRestorer) + if !ok { + return nil, fmt.Errorf("durable: volume %s: chunk layer has no restore surface: %w", volumeID, ErrNotChunkVolume) + } + return r, nil +} + +// HydrateVolume makes every HEAD-named absent chunk of volumeID local +// (M6.Restore.Restoring>Hydrating), paced to bytesPerSecond, under the +// host limiter's BackgroundFill class. +func (p *DurableProvider) HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.HydrateProgress{}, err + } + return r.HydrateAllAt(hostlimit.WithClass(ctx, hostlimit.BackgroundFill), bytesPerSecond) +} + +// OwnVolumeBatch runs one bounded cut of volumeID that re-uploads up to n +// local chunks with foreign HEAD keys under own keys +// (M6.Restore.Owning>Owning). +func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.OwnProgress{}, err + } + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() + return r.OwnBatch(ctx, n, foreign) +} + +// ErrProviderClosed refuses work admitted after Close. +var ErrProviderClosed = errors.New("durable: provider closed") + +// GoOwned runs fn on its own goroutine inside the provider's lifetime: its +// ctx ends when Close starts, and Close waits for fn to return before it +// closes any store. A restore driver runs this way, so it never outlives the +// volume it drives. +func (p *DurableProvider) GoOwned(fn func(ctx context.Context)) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrProviderClosed + } + p.inflight.Add(1) + p.mu.Unlock() + go func() { + defer p.inflight.Done() + fn(p.closeCtx) + }() + return nil +} diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go new file mode 100644 index 0000000000..5f57567ab5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -0,0 +1,81 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// A goroutine started with GoOwned sees its ctx end when Close starts, and +// Close returns only after it has returned (ordering witnessed by sequence +// numbers); after Close nothing is admitted. +func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) + if err != nil { + t.Fatal(err) + } + var seq, settledAt, closedAt atomic.Int64 + started, cancelled, release, closed := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + releaseOnce := sync.OnceFunc(func() { close(release) }) + startClose := sync.OnceFunc(func() { // one Close, launched by the body or by cleanup + go func() { + _ = p.Close() + closedAt.Store(seq.Add(1)) + close(closed) + }() + }) + t.Cleanup(func() { // registered before launch: always cancels, releases and joins + startClose() + releaseOnce() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("cleanup: Close did not return") + } + }) + if err := p.GoOwned(func(ctx context.Context) { + close(started) + <-ctx.Done() + close(cancelled) + <-release // held settlement: Close must wait for this + settledAt.Store(seq.Add(1)) + }); err != nil { + t.Fatal(err) + } + wait := func(ch <-chan struct{}, d time.Duration, what string) bool { + t.Helper() + select { + case <-ch: + return true + case <-time.After(d): + return false + } + } + if !wait(started, 5*time.Second, "start") { + t.Fatal("the owned goroutine never started") + } + startClose() + if !wait(cancelled, 5*time.Second, "cancel") { + t.Fatal("Close did not cancel the owned goroutine's ctx") + } + // Adverse schedule for a Close that does not join: give it time to + // return while the goroutine is still held. + if wait(closed, 200*time.Millisecond, "early close") { + t.Fatal("Close returned while the owned goroutine was still held") + } + releaseOnce() + if !wait(closed, 5*time.Second, "close") { + t.Fatal("Close did not return after the owned goroutine returned") + } + if s, c := settledAt.Load(), closedAt.Load(); s == 0 || c <= s { + t.Fatalf("Close returned (seq %d) before the owned goroutine settled (seq %d)", c, s) + } + if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { + t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_linux.go b/seaweed-block/core/frontend/durable/spill_free_linux.go new file mode 100644 index 0000000000..92843c70ff --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux.go @@ -0,0 +1,17 @@ +//go:build linux + +package durable + +import "syscall" + +// spillFree returns the free bytes available to an unprivileged writer on +// the filesystem holding dir (the COW side files). +func spillFree(dir string) func() (int64, error) { + return func() (int64, error) { + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + return 0, err + } + return int64(st.Bavail) * int64(st.Bsize), nil + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_linux_test.go b/seaweed-block/core/frontend/durable/spill_free_linux_test.go new file mode 100644 index 0000000000..2bd3081dec --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux_test.go @@ -0,0 +1,29 @@ +//go:build linux + +package durable + +import ( + "syscall" + "testing" +) + +// The provider's spill free-space reader reports the bytes an unprivileged +// writer has on the storage root's filesystem. +func TestSpillFree_ReadsTheStorageRootFilesystem(t *testing.T) { + dir := t.TempDir() + free, err := spillFree(dir)() + if err != nil { + t.Fatal(err) + } + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + want := int64(st.Bavail) * int64(st.Bsize) + if free <= 0 || free > 2*want+1<<30 || want > 2*free+1<<30 { + t.Fatalf("spill free %d bytes; statfs says %d", free, want) + } + if _, err := spillFree(dir + "/missing")(); err == nil { + t.Fatal("a missing storage root read as free space") + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_other.go b/seaweed-block/core/frontend/durable/spill_free_other.go new file mode 100644 index 0000000000..7ba44e278c --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package durable + +// spillFree is nil off Linux: the COW spill cap is the configured one. +func spillFree(string) func() (int64, error) { return nil } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c6cd4f7525..913f74efb0 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -238,6 +238,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -603,8 +604,9 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog + p ChunkProvider + cat *chunkstore.Catalog + restores restoreRuns } // NewChunkControl serves the routes from a durable provider (cut, detach) @@ -637,6 +639,14 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } + // The share begins before the cut that produces the sealed HEAD. + if g := c.cat.ShareGuard(); g != nil { + token, err := g.Begin(ctx, volumeID) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + sreq.ShareToken = token + } // A named seal is urgent even without a minimum LSN. r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 87f19228ea..71a16b3e89 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -6,6 +6,7 @@ package volume import ( "context" + "errors" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -96,3 +97,57 @@ func TestChunkControl_InvalidLabelRefusedBeforeCutting(t *testing.T) { t.Fatalf("snapshot with an invalid label: %v (cuts %d); want invalid_label without a cut", err, fp.cuts) } } + +// ownerGuard records, at Begin, how many cuts the provider had taken. +type ownerGuard struct { + cutsAtBegin []int + finishes []string + fp *fakeChunkProvider + beginErr error +} + +func (g *ownerGuard) Begin(context.Context, string) (string, error) { + g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts) + if g.beginErr != nil { + return "", g.beginErr + } + return "owner", nil +} + +func (g *ownerGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + g.finishes = append(g.finishes, vol+":"+token) + return nil +} + +// The owner's seal begins the share BEFORE the cut that produces the sealed +// HEAD, and the catalog finishes it with that token (no second Begin). +func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err != nil { + t.Fatal(err) + } + if len(g.cutsAtBegin) != 1 || g.cutsAtBegin[0] != 0 || fp.cuts != 1 { + t.Fatalf("Begin saw %v cuts (cuts now %d); want one Begin before the one cut", g.cutsAtBegin, fp.cuts) + } + if len(g.finishes) != 1 || g.finishes[0] != "v1:owner" { + t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes) + } +} + +// A refused Begin stops the owner's seal before its cut: no cut, no Finish, +// no snapshot. +func TestChunkControl_SnapshotBeginRefusedCutsNothing(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp, beginErr: errors.New("share refused")} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if fp.cuts != 0 || len(g.finishes) != 0 { + t.Fatalf("cuts %d finishes %v after a refused Begin; want none", fp.cuts, g.finishes) + } +} diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go new file mode 100644 index 0000000000..94521f0134 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -0,0 +1,246 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Independent restore driver (M6.Restore). A restored volume serves at once; +// the driver then makes every chunk local (Restoring>Hydrating), re-uploads +// the chunks whose HEAD keys name another volume under the volume's own keys +// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the +// batches may overlap), and writes the independence marker once HEAD holds +// no foreign ref (Owning>Independent). Every decision is read from the +// target's own facts (its VOLUME, HEAD and marker), never from the source, so +// a rerun after a crash resumes where the remote state is, and a deleted +// source snapshot or volume is a normal state. + +// Restore quantities (invariants.md Part E). +const ( + DefaultRestoreBatchChunks = 64 + DefaultRestoreBytesPerSecond = 64 << 20 +) + +// RestoreProvider is the chunk layer's restore surface for an attached volume. +type RestoreProvider interface { + HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) +} + +// RestoreConfig bounds one restore run; zero fields take the defaults. +type RestoreConfig struct { + BatchChunks int + BytesPerSecond int64 +} + +// Restore phases. +const ( + RestoreHydrating = "hydrating" + RestoreOwning = "owning" + RestoreIndependent = "independent" + RestoreFailed = "failed" +) + +// RestoreStatus is the body of /chunk/restore. +type RestoreStatus struct { + VolumeID string `json:"volumeID"` + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` // chunks the walker made local + Owned int `json:"owned"` // chunks re-uploaded under own keys + Foreign int `json:"foreign"` // HEAD chunks still naming another volume + NotLocal int `json:"notLocal"` // of those, not local yet + Batches int `json:"batches"` // batch cuts run + MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) + ErrorCode string `json:"errorCode,omitempty"` + ErrorText string `json:"error,omitempty"` +} + +// foreignKey reports whether key names another volume's object: an +// owner-qualified key whose owner is not vol. +func foreignKey(vol string) func(string) bool { + own := "@" + vol + "/" + return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } +} + +var ( + errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") + errNotRestore = errors.New("restore: not a restore") +) + +// runRestore drives one restore of vol to independence, reporting progress. +func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { + if cfg.BatchChunks <= 0 { + cfg.BatchChunks = DefaultRestoreBatchChunks + } + if cfg.BytesPerSecond <= 0 { + cfg.BytesPerSecond = DefaultRestoreBytesPerSecond + } + st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { + return st, err + } else if ok { + st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen + return st, nil + } + v, ok, err := cat.ReadVolume(ctx, vol) + if err != nil { + return st, err + } + if !ok || v.Origin != chunkstore.OriginRestore { + return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) + } + foreign := foreignKey(vol) + for stalls := 0; ; { + h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) + st.Filled += h.Filled + report(st) + if err != nil { + return st, err + } + st.Phase = RestoreOwning + progressed := h.Filled > 0 + for { + o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) + st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal + if o.Owned > 0 { + st.Batches++ + progressed = true + } + report(st) + if err != nil { + return st, err + } + if o.Remaining == 0 { + m, err := cat.MarkIndependent(ctx, vol) + if err != nil { + return st, err + } + st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false + report(st) + return st, nil + } + if o.Owned == 0 { + break // what is left is not local: walk again + } + } + if !progressed { + if stalls++; stalls > 2 { + return st, errRestoreStuck + } + } else { + stalls = 0 + } + } +} + +// restoreRuns holds at most one running restore per volume and the last +// status of each. +type restoreRuns struct { + mu sync.Mutex + runs map[string]*RestoreStatus +} + +// Restore reports vol's restore status and, with start, starts a run unless +// one is running (POST /chunk/restore). A run outlives the request but not +// the serving provider (RestoreOwner); it ends independent, or failed with +// the error (a later start resumes from the target's remote facts). +func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { + p, ok := c.p.(RestoreProvider) + owner, owned := c.p.(RestoreOwner) + if !ok || !owned { + return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) + } + c.restores.mu.Lock() + defer c.restores.mu.Unlock() + if c.restores.runs == nil { + c.restores.runs = map[string]*RestoreStatus{} + } + cur := c.restores.runs[vol] + if cur != nil && (cur.Running || !start) { + return *cur, nil + } + if !start { + return RestoreStatus{VolumeID: vol}, nil + } + st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + c.restores.runs[vol] = st + report := func(s RestoreStatus) { + c.restores.mu.Lock() + *st = s + c.restores.mu.Unlock() + } + run := func(ctx context.Context) { + final, err := runRestore(ctx, c.cat, p, vol, RestoreConfig{}, report) + final.Running = false + if err != nil { + _, code, _ := chunkErrorCode(err) + final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() + } + report(final) + } + if err := owner.GoOwned(run); err != nil { + delete(c.restores.runs, vol) + return RestoreStatus{}, err + } + return *st, nil +} + +// RestoreOwner runs the driver inside the serving volume's lifetime: the +// driver's ctx ends when the owner closes, and the owner waits for it +// (DurableProvider.GoOwned). +type RestoreOwner interface { + GoOwned(fn func(ctx context.Context)) error +} + +// handleChunkRestore serves GET /chunk/restore?volume=V (status) and +// POST /chunk/restore {"volumeID": V} (start or join a run; with +// "statusOnly": true, status only). Both answer 200 with the status. +func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { + method := http.MethodGet + if r.Method == http.MethodPost { + method = http.MethodPost + } + if !s.chunkAdmit(w, r, method) { + return + } + vol := r.URL.Query().Get("volume") + if method == http.MethodPost { + var req struct { + VolumeID string `json:"volumeID"` + StatusOnly bool `json:"statusOnly"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + vol = req.VolumeID + if req.StatusOnly { + method = http.MethodGet + } + } + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + rc, ok := ctl.(interface { + Restore(context.Context, string, bool) (RestoreStatus, error) + }) + if !ok { + writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") + return + } + st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, st) +} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go new file mode 100644 index 0000000000..d70420b8b4 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -0,0 +1,394 @@ +package volume + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const restoreBase = "/swblock/chunks" + +var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + +// sourceReadGuard fails every catalog read of the source volume's own +// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable +// (hydration reads the source's chunks through T's qualified refs). +type sourceReadGuard struct { + *adapterManifestFiler + armed bool + reads []string +} + +func (g *sourceReadGuard) denied(dir string) bool { + src := path.Join(restoreBase, "v1") + return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) +} + +func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, path.Join(dir, name)) + return nil, errors.New("test: the restore driver read the source") + } + return g.adapterManifestFiler.LookupEntry(ctx, dir, name) +} + +func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, dir) + return nil, errors.New("test: the restore driver listed the source") + } + return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) +} + +// fakeRestoreProvider stands in for the chunk layer: the walk makes every +// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. +type fakeRestoreProvider struct { + r *chunkstore.ChunkRemote + local bool + hydrations int + batches int + failAtBatch int // a batch with this 1-based number fails (0: never) + mu sync.Mutex + entered chan struct{} // if set, HydrateVolume signals entry and + gate chan struct{} // then waits for gate or its ctx +} + +func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.mu.Lock() + p.hydrations++ + entered, gate := p.entered, p.gate + p.mu.Unlock() + if entered != nil { + entered <- struct{}{} + select { + case <-gate: + case <-ctx.Done(): + return storage.HydrateProgress{}, ctx.Err() + } + } + if bps != DefaultRestoreBytesPerSecond { + return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) + } + if p.local { + return storage.HydrateProgress{}, nil + } + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.HydrateProgress{}, err + } + p.local = true + return storage.HydrateProgress{Filled: len(h.Chunks)}, nil +} + +func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.OwnProgress{}, err + } + var todo []uint64 + for idx, ref := range h.Chunks { + if foreign(ref.Key) { + todo = append(todo, idx) + } + } + sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) + if !p.local || len(todo) == 0 { + nl := 0 + if !p.local { + nl = len(todo) + } + return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil + } + p.batches++ + if p.batches == p.failAtBatch { + return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") + } + next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + next.Chunks[idx] = ref + } + owned := 0 + for _, idx := range todo { + if owned == n { + break + } + data, err := p.r.Get(ctx, h.Chunks[idx].Key) + if err != nil { + return storage.OwnProgress{}, err + } + key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) + if err := p.r.Put(ctx, key, data); err != nil { + return storage.OwnProgress{}, err + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + owned++ + } + next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + return storage.OwnProgress{}, err + } + if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + return storage.OwnProgress{}, err + } + for _, id := range intents { + _ = p.r.DeleteIntent(ctx, id) + } + return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil +} + +// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores +// it into v2; it returns the guard filer, the catalog and v2's provider. +func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { + t.Helper() + ctx := context.Background() + f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} + cat, err := chunkstore.NewCatalog(f, restoreBase) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { + t.Fatal(err) + } + r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r1.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := 0; idx < chunks; idx++ { + data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) + data[0] = byte(0x60 + idx) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r1.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range intents { + _ = r1.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { + t.Fatal(err) + } + r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) + if err != nil { + t.Fatal(err) + } + return f, cat, &fakeRestoreProvider{r: r2} +} + +func noReport(RestoreStatus) {} + +// The driver walks, cuts bounded batches until no foreign ref is left and +// writes the marker, reading only the target's facts (Restoring>Hydrating> +// Owning>Owning>Independent). +func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { + f, cat, p := restoreFixtureHost(t, 5) + f.armed = true // from here, any read of the source's catalog entries fails + ctx := context.Background() + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil { + t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) + } + if len(f.reads) != 0 { + t.Fatalf("the driver read the source: %v", f.reads) + } + if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { + t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) + } + m, ok, err := cat.ReadIndependence(ctx, "v2") + if err != nil || !ok || m.HeadGen != st.MarkedGen { + t.Fatalf("marker: %+v ok=%v %v", m, ok, err) + } + again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) + if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { + t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) + } +} + +// A failed batch leaves HEAD as it was; the next run resumes from the +// target's HEAD and finishes. +func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 5) + ctx := context.Background() + p.failAtBatch = 2 + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err == nil || st.Owned != 2 || st.Foreign != 3 { + t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) + } + if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { + t.Fatal("marker written with foreign refs left") + } + p.failAtBatch = 0 + st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) + } +} + +// Only a restore volume is driven. +func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 1) + if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { + t.Fatalf("driving the source volume: %v, want not a restore", err) + } +} + +// testOwner runs owned goroutines until close, which cancels and joins them +// (bounded), like DurableProvider.Close. +type testOwner struct { + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +func newTestOwner(t *testing.T) *testOwner { + o := &testOwner{} + o.ctx, o.cancel = context.WithCancel(context.Background()) + t.Cleanup(func() { o.close(t) }) + return o +} + +func (o *testOwner) GoOwned(fn func(context.Context)) error { + o.wg.Add(1) + go func() { defer o.wg.Done(); fn(o.ctx) }() + return nil +} + +func (o *testOwner) close(t *testing.T) { + o.cancel() + done := make(chan struct{}) + go func() { o.wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("owned restore run did not return after close") + } +} + +// restoreOnlyProvider is a ChunkProvider (cut and detach unused) with the +// restore surface and an owner. +type restoreOnlyProvider struct { + *fakeRestoreProvider + *testOwner +} + +func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { + return storage.ChunkCutResult{}, errors.New("unused") +} +func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return storage.ChunkCutResult{}, 0, errors.New("unused") +} + +func waitRestore(t *testing.T, ctl *chunkControl, vol string) RestoreStatus { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(context.Background(), vol, false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + return st + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// POST /chunk/restore starts one background run: a second start while the +// first is held joins it (one walk), and the run is reported to the end. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 2), make(chan struct{}) + release := func() { + select { + case <-p.gate: + default: + close(p.gate) + } + } + t.Cleanup(release) // registered before launch; the owner joins after it + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + if st, err := ctl.Restore(ctx, "v2", true); err != nil || !st.Running { + t.Fatalf("second start while the first runs: %+v %v, want it joined", st, err) + } + release() + st := waitRestore(t, ctl, "v2") + p.mu.Lock() + walks := p.hydrations + p.mu.Unlock() + if walks != 1 || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("walks=%d status %+v, want one run to independence", walks, st) + } +} + +// Closing the serving owner cancels a run held in a provider call and joins +// it: the run ends failed and publishes no marker after the close. +func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // opened only at teardown + // Registered after the owner: it runs first, so a run that ignored the + // owner's cancel (the red case) is released before the owner's join. + t.Cleanup(func() { close(p.gate) }) + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + owner.close(t) // cancel and bounded join, like DurableProvider.Close + st, err := ctl.Restore(context.Background(), "v2", false) + if err != nil || st.Running || st.Phase != RestoreFailed { + t.Fatalf("status after the owner closed: %+v %v, want a finished failed run", st, err) + } + if _, ok, _ := cat.ReadIndependence(context.Background(), "v2"); ok { + t.Fatal("a marker was published after the owner closed") + } +} + +var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/core/storage/chunk_base_v3.go b/seaweed-block/core/storage/chunk_base_v3.go index b908fe6eff..07b9190d55 100644 --- a/seaweed-block/core/storage/chunk_base_v3.go +++ b/seaweed-block/core/storage/chunk_base_v3.go @@ -29,7 +29,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { } l.stMu.Unlock() if refusal != nil { - l.capMu.Unlock() + l.unlockCap() done() return nil, fmt.Errorf("storage: BASE transition refused: %w", refusal) } @@ -56,7 +56,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { if d.BaseState == BaseInstalled && presenceDurable && l.s.OwnerChunkAttachDurableV3() { l.s.AllowBaseRetirementV3() } - l.capMu.Unlock() + l.unlockCap() done() }, nil } diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index c9fc09dc5c..35144e34ff 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -21,6 +21,62 @@ const cutCOWMemoryLimit = DefaultCutPayloadMemoryBudget // defaultCOWSpillLimit caps a copy window's side-file bytes by default. const defaultCOWSpillLimit = 1 << 30 + +// cowSpillFreeReserve is the free space a cut's side file never takes, +// on top of leaving half of the rest. +const cowSpillFreeReserve = 1 << 30 + +var ( + // errCutNoRoom: the free space leaves this cut no side-file room. + errCutNoRoom = errors.New("storage: no room to cut") + // errCutFreeUnreadable: the free space could not be read, so this cut + // has no side-file room. + errCutFreeUnreadable = errors.New("storage: free space unreadable") +) + +// cowSpillCap is one cut's side-file cap. cause is set when the free space +// made it zero: errCutNoRoom or errCutFreeUnreadable. +type cowSpillCap struct { + bytes int64 + cause error +} + +// cowSpillLimit is this cut's side-file cap: COWSpillLimit, lowered to +// half the free space minus cowSpillFreeReserve when COWSpillFree is set. +// A read error gives a cap of 0 with its own cause. +func (l *chunkLayerImpl) cowSpillLimit() cowSpillCap { + limit := l.cfg.COWSpillLimit + if l.cfg.COWSpillFree == nil { + return cowSpillCap{bytes: limit} + } + free, err := l.cfg.COWSpillFree() + if err != nil { + return cowSpillCap{cause: fmt.Errorf("%w: %w", errCutFreeUnreadable, err)} + } + c := cowSpillCap{bytes: max(0, min(limit, free/2-cowSpillFreeReserve))} + if c.bytes == 0 { + c.cause = errCutNoRoom + } + return c +} + +// readCutSpill reads this cut's side-file cap once, for both the staging +// bound and the copy window, and records it in the stats. +func (l *chunkLayerImpl) readCutSpill() cowSpillCap { + c := l.cowSpillLimit() + reason := "" + switch { + case errors.Is(c.cause, errCutFreeUnreadable): + reason = "free_space_unreadable" + case errors.Is(c.cause, errCutNoRoom): + reason = "no_room_to_cut" + } + l.stMu.Lock() + l.stats.COWSpillCap, l.stats.COWSpillCapReason = c.bytes, reason + l.stMu.Unlock() + return c +} + const ( cowPending uint8 = iota cowCopying @@ -68,6 +124,7 @@ type cutCOWWindow struct { memory int64 spillBytes int64 // bytes written to the side file; at most spillLimit spillLimit int64 + spillCause error // why spillLimit is 0, when the free space made it so chunkBytes int64 memoryLimit int64 saverSlots chan struct{} @@ -143,12 +200,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() { } // The caller owns captureMu exclusive, so no writer can miss this publication. -func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) { +func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) { size := uint64(l.blockSize) * l.chunkBlocks if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) } - w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cfg.COWSpillLimit, chunkBytes: int64(size)} + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)} w.ctx, w.cancel = context.WithCancel(context.Background()) _, reserved, limit := l.cutPayloadWorkers() savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size)))) @@ -373,6 +430,9 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error // The side file is sparse but its saved chunks are real bytes on the // volume's filesystem: abort the cut (retried) instead of filling it. w.mu.Unlock() + if w.spillCause != nil { + return fmt.Errorf("%w: %w: %w: COW spill cap is 0", errCutCOWAborted, errCutCOWCapacity, w.spillCause) + } return fmt.Errorf("%w: %w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, errCutCOWCapacity, w.spillLimit) } else { w.spillBytes += w.chunkBytes diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go new file mode 100644 index 0000000000..eefd41798b --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -0,0 +1,225 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "sync/atomic" + "testing" +) + +// The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read +// from COWSpillFree on every call. A cap of 0 carries its cause: no room +// (the free space is within the reserve) or a read error, which is not +// reported as a full disk. Without COWSpillFree the configured cap applies. +func TestCOWSpillLimit_FromFreeSpace(t *testing.T) { + l := &chunkLayerImpl{cfg: ChunkLayerConfig{COWSpillLimit: 4 << 30}} + if got := l.cowSpillLimit(); got.bytes != 4<<30 || got.cause != nil { + t.Fatalf("no free-space reader: cap %+v, want the configured 4 GiB", got) + } + var free atomic.Int64 + var reads atomic.Int64 + var fail atomic.Bool + l.cfg.COWSpillFree = func() (int64, error) { + reads.Add(1) + if fail.Load() { + return 1 << 40, errors.New("statfs failed") + } + return free.Load(), nil + } + for _, c := range []struct { + free, want int64 + cause error + }{ + {100 << 30, 4 << 30, nil}, // plenty: the configured cap + {6 << 30, 2 << 30, nil}, // 6 GiB free: half is 3, minus the 1 GiB reserve + {2 << 30, 0, errCutNoRoom}, // half the free space is all reserve + {1 << 30, 0, errCutNoRoom}, // below the reserve: never negative + {10<<30 + 2, 4 << 30, nil}, // the configured cap still bounds it + {3 << 30, (3<<30)/2 - (1 << 30), nil}, // 1.5 GiB - 1 GiB + } { + free.Store(c.free) + if got := l.cowSpillLimit(); got.bytes != c.want || !errors.Is(got.cause, c.cause) || (c.cause == nil) != (got.cause == nil) { + t.Fatalf("free %d: cap %+v, want %d (cause %v)", c.free, got, c.want, c.cause) + } + } + if reads.Load() != 6 { + t.Fatalf("free space read %d times for 6 calls; want once per call", reads.Load()) + } + fail.Store(true) + if got := l.cowSpillLimit(); got.bytes != 0 || !errors.Is(got.cause, errCutFreeUnreadable) || errors.Is(got.cause, errCutNoRoom) { + t.Fatalf("free-space read error: cap %+v, want 0 with cause free_space_unreadable (not no room)", got) + } +} + +// Each cut reads the free space once, for both the staging bound and the +// window, and shows the cap in the stats: the configured cap with ample +// free space; 0 with reason no_room_to_cut when the free space is within +// the reserve (the cut still completes by staging before the barrier); +// 0 with reason free_space_unreadable when the read fails. +func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) { + s, l, _, gate := cowFixture(t) + gate.unblock() + var free, reads atomic.Int64 + var fail atomic.Bool + l.cfg.COWSpillFree = func() (int64, error) { + reads.Add(1) + if fail.Load() { + return 0, errors.New("statfs failed") + } + return free.Load(), nil + } + for i, c := range []struct { + free int64 + fail bool + cap int64 + reason string + }{ + {100 << 30, false, l.cfg.COWSpillLimit, ""}, + {1 << 30, false, 0, "no_room_to_cut"}, + {100 << 30, true, 0, "free_space_unreadable"}, + } { + free.Store(c.free) + fail.Store(c.fail) + if _, err := s.Write(uint32(i*ctChunkBlocks+1), makeBlock(ctBlockSize, byte(0x60+i))); err != nil { + t.Fatal(err) + } + before := reads.Load() + if _, err := l.Cut(context.Background()); err != nil { + t.Fatalf("cut %d (free %d, read error %v): %v; want it to complete by staging, not refuse", i, c.free, c.fail, err) + } + if st := l.Stats(); len(st.CutsAborted) != 0 { + t.Fatalf("cut %d: aborts %v; want none", i, st.CutsAborted) + } + if n := reads.Load() - before; n != 1 { + t.Fatalf("cut %d read the free space %d times; want once", i, n) + } + if st := l.Stats(); st.COWSpillCap != c.cap || st.COWSpillCapReason != c.reason { + t.Fatalf("cut %d: stats cap %d reason %q; want %d %q", i, st.COWSpillCap, st.COWSpillCapReason, c.cap, c.reason) + } + } +} + +// The cap the window holds is the one this cut read: with the free space +// within the reserve (or unreadable) the copy window opens with a cap of 0 +// and that cause, straight from the reader. The window is caught open by +// holding its copy of chunk 0: staging runs with the read gate disarmed, +// and the stage hook re-dirties chunk 0 each round and arms the gate after +// the second, so the barrier leaves chunk 0 to the window. +func TestCutCOWV3_WindowGetsTheCutsReadCap(t *testing.T) { + for _, c := range []struct { + name string + read func() (int64, error) + cause error + }{ + {"no room", func() (int64, error) { return 1 << 30, nil }, errCutNoRoom}, + {"unreadable", func() (int64, error) { return 0, errors.New("statfs failed") }, errCutFreeUnreadable}, + } { + t.Run(c.name, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + gate.mu.Lock() + gate.armed = false + gate.mu.Unlock() + l.cfg.COWSpillFree = c.read + l.testAfterStageHook = func(round int) { + if _, err := s.Write(1, makeBlock(ctBlockSize, byte(0x70+round))); err != nil { + t.Error(err) + } + if round == 1 { + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + } + } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + if w == nil { + t.Fatal("no copy window open while its copy is held") + } + w.mu.Lock() + limit, cause := w.spillLimit, w.spillCause + w.mu.Unlock() + if limit != 0 || !errors.Is(cause, c.cause) { + t.Fatalf("window cap %d cause %v; want 0 and %v from the cut's read", limit, cause, c.cause) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut with the window held") + if err := <-cutErr; err != nil { + t.Fatalf("cut: %v; want it to complete (the held copy needs no spill)", err) + } + }) + } +} + +// A save that meets a zero cap aborts the cut under the cap's own cause: +// no_room_to_cut or free_space_unreadable, not cow_capacity; the guest +// write completes and the next cut is not blocked. +func TestCutCOWV3_ZeroCapAbortIsCountedByItsCause(t *testing.T) { + for _, c := range []struct { + cause error + reason string + }{ + {errCutNoRoom, "no_room_to_cut"}, + {fmt.Errorf("%w: %w", errCutFreeUnreadable, errors.New("statfs failed")), "free_space_unreadable"}, + } { + t.Run(c.reason, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the in-memory budget is used + w.spillLimit, w.spillCause = 0, c.cause + w.mu.Unlock() + writeDone := make(chan struct{}) + writeErr := make(chan error, 1) + // Registered before the writer starts: release the copier and + // join the writer (bounded) whatever the test's outcome. + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "zero-cap writer cleanup") }) + go func() { + defer close(writeDone) + _, err := s.Write(5, makeBlock(ctBlockSize, 0xd7)) + writeErr <- err + }() + cowWaitSignal(t, writeDone, "guest write at a zero cap") + if err := <-writeErr; err != nil { + t.Fatal("guest write refused at a zero cap:", err) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut at a zero cap") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !errors.Is(err, c.cause) { + t.Fatalf("cut at a zero cap: %v, want an abort carrying %v", err, c.cause) + } + if st := l.Stats(); st.CutsAborted[c.reason] != 1 || st.CutsAborted["cow_capacity"] != 0 { + t.Fatalf("aborts %v; want one %s and no cow_capacity", st.CutsAborted, c.reason) + } + }) + } +} + +// The staging bound follows the free space read at the cut: with ample +// free space the fixture's two dirty chunks are within the bound and go to +// the barrier unstaged; with free space below the reserve the cap is 0, so +// the cut pre-uploads them in a staging round before the barrier. +func TestCutCOWV3_LowFreeSpaceStagesBeforeTheBarrier(t *testing.T) { + for _, c := range []struct { + name string + free int64 + wantStaged bool + }{ + {"ample free space", 100 << 30, false}, + {"free space below the reserve", 1 << 30, true}, + } { + t.Run(c.name, func(t *testing.T) { + _, l, _, gate := cowFixture(t) + gate.unblock() + l.cfg.COWSpillFree = func() (int64, error) { return c.free, nil } + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + if staged := r.Stats.StageRounds > 0 && r.Stats.StagedChunks >= 2; staged != c.wantStaged { + t.Fatalf("free %d: %d staging rounds, %d staged chunks; want staged=%v", c.free, r.Stats.StageRounds, r.Stats.StagedChunks, c.wantStaged) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 3cac8535be..6e66f07433 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -58,7 +58,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return err } ref, had := head.Chunks[c.idx] - if !c.zero && !(had && ref.SHA256 == c.sum) { + if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) { c.key, c.size = keys[i], len(c.data) once.Do(func() { intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) diff --git a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go index bf141d776b..7fae795b32 100644 --- a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go @@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) { for i := 0; i < candidates; i++ { pending[uint64(i)] = true } - w, err := l.installCOWWindow(pending, nil, nil) + w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index 34b469a152..97a0b0784b 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -129,13 +129,15 @@ type deadlineProgressRemote struct { *fakeChunkRemote completed int calls int + interrupt context.CancelCauseFunc } func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error { r.calls++ - if r.completed == 2 { + if r.completed == 2 && r.interrupt != nil { + r.interrupt(context.DeadlineExceeded) <-ctx.Done() - return ctx.Err() + return context.Cause(ctx) } err := r.fakeChunkRemote.Put(ctx, key, b) if err == nil { @@ -164,11 +166,17 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { for pass := 0; pass < 3; pass++ { r.completed = 0 r.calls = 0 - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - result, err := l.Cut(ctx) - cancel() + // Expire at the third PUT event, not one second after setup. This + // witnesses two completed immutable uploads even on a loaded host. + ctx, cancel := context.WithCancelCause(context.Background()) + r.interrupt = nil if pass < 2 { - if !errors.Is(err, context.DeadlineExceeded) { + r.interrupt = cancel + } + result, err := l.Cut(ctx) + cancel(nil) + if pass < 2 { + if !errors.Is(err, context.DeadlineExceeded) || r.calls != 3 || r.completed != 2 { t.Fatalf("pass %d did not reach injected deadline: %v", pass, err) } if f.stats().head.Gen != base { diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 5655491ec5..17fae0e4b3 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -47,7 +47,16 @@ var ( // or on a fill error that is not a retryable pending state; the caller may // call it again. func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { + return l.HydrateAllAt(ctx, 0) +} + +// HydrateAllAt is HydrateAll paced to at most bytesPerSecond of fill payload +// (one chunk per fill), counted from its start; 0 means unpaced. The pace +// applies before admission, so a paced walker holds no permit while it waits. +func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) (HydrateProgress, error) { var p HydrateProgress + start := time.Now() + started := int64(0) // fills started, for the pace walk, stop := context.WithCancelCause(ctx) defer stop(nil) backoff := hydrateAllMinBackoff @@ -89,6 +98,21 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error } continue } + if bytesPerSecond > 0 && started > 0 { + due := start.Add(time.Duration(float64(started*int64(l.chunkBlocks)*int64(l.blockSize)) / float64(bytesPerSecond) * float64(time.Second))) + if d := time.Until(due); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-walk.Done(): + t.Stop() + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + t.Stop() + return quit(errChunkLayerClosed) + } + } + } release, err := l.admitFill(walk, stop) if err != nil { p.Deferred++ @@ -110,6 +134,7 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error if f == nil { continue // resolved meanwhile } + started++ select { case <-f.done: case <-walk.Done(): diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index b184105503..9efd0c2d57 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -406,3 +406,54 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { t.Fatalf("absent after the walk: %d, want 0", n) } } + +// The walker's byte pace bounds the fill rate: 8 chunks at 4 chunks/s take +// at least (8-1)/4 s. +func TestHydrateAll_PacedByByteRate(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &timedBudget{} + layer.cfg.Budget = budget // admission times witness the pace + rate := int64(4 * ctChunkBytes) + origin := time.Now() // a lower bound of the walker's own pace start + p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) + want := ctNumBlocks / ctChunkBlocks + if err != nil || p.Remaining != 0 || p.Filled != want { + t.Fatalf("paced walk: %+v %v, want all %d chunks filled", p, err, want) + } + gets := 0 + for _, n := range countGets(remote) { + gets += n + } + if gets != want { + t.Fatalf("%d remote Gets, want %d", gets, want) + } + budget.mu.Lock() + defer budget.mu.Unlock() + if len(budget.at) != want { + t.Fatalf("%d admissions, want %d", len(budget.at), want) + } + for i := 1; i < len(budget.at); i++ { + // fill i is admitted no earlier than i chunks at the rate after the + // walker started, and the walker started after origin + due := origin.Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due) { + t.Fatalf("fill %d admitted %v after the call, before its pace time %v", i, budget.at[i].Sub(origin), due.Sub(origin)) + } + } +} + +// timedBudget admits every fill and records when. +type timedBudget struct { + mu sync.Mutex + at []time.Time +} + +func (b *timedBudget) Admit(context.Context, int64, func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.at = append(b.at, time.Now()) + return uint64(len(b.at)), nil +} +func (b *timedBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *timedBudget) Release(uint64) {} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ed9ec97b5..c7d7b2c21a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -69,7 +69,12 @@ type chunkLayerImpl struct { ctx context.Context // cancelled by Close cancel context.CancelFunc - wg sync.WaitGroup // captures and fills in flight + // settled: confirmed publications not yet reported to + // cfg.OnPublishSettled, in publication order; settledDraining: a caller + // is delivering them (both stMu). + settled []headTransition + settledDraining bool + wg sync.WaitGroup // captures and fills in flight cowMu sync.Mutex // window admission only; never held during reads or joins cow *cutCOWWindow @@ -116,6 +121,9 @@ type chunkLayerImpl struct { dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed allDirty bool // a BASE block landed: every chunk is dirty + // own names the chunks OwnBatch re-uploads under this layer's own keys in + // the cut it runs (set and cleared under capMu, read under stMu). + own map[uint64]bool cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -405,6 +413,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { absent[idx] = true } } + l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() for idx, e := range l.s.v3.mapEntries { @@ -531,12 +540,12 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func func (l *chunkLayerImpl) BeginBaseInstall() error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet) } func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if cp := l.s.CheckpointLSN(); cp < frontier { return fmt.Errorf("storage: EndBaseInstall: frontier %d is not durable (checkpoint %d)", frontier, cp) } @@ -595,7 +604,7 @@ func (l *chunkLayerImpl) admit() (err error) { func (l *chunkLayerImpl) Cut(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return l.captureLocked(ctx, false) } @@ -609,7 +618,7 @@ func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) { func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() l.stMu.Lock() fenced, detached := l.fenced, l.detached != nil l.stMu.Unlock() @@ -765,8 +774,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch var staged map[uint64]stagedChunk var intents []string _, guestFrozen := FrozenDetachFromContext(ctx) + spill := l.readCutSpill() if !guestFrozen { - staged, intents, err = l.stage(ctx, &st) + staged, intents, err = l.stage(ctx, &st, spill.bytes) } if st.UploadedBytes > 0 { st.PayloadNs += time.Since(stageStart).Nanoseconds() @@ -911,7 +921,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch { var w *cutCOWWindow windowStart := time.Now() - w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) + w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill) if copyErr == nil { w.budget = budget } @@ -973,7 +983,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: + case c.zero && !had, unchangedFromHead(c, ref, had): st.UnchangedChunks++ continue case c.zero: @@ -1165,7 +1175,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return r, nil } @@ -1186,7 +1196,7 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { // successful cancel. resolvePending would re-propose the detach instead. func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return detachApplied, r, nil } @@ -1243,6 +1253,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, ch l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN cut.Head = copyHead(cur) l.detached = &cut @@ -1371,6 +1382,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN if wasDetach { cut.Head = copyHead(cur) @@ -1405,6 +1417,10 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error switch { case errors.Is(err, errCutSaverCapacity): abortReason = "saver_capacity" + case errors.Is(err, errCutFreeUnreadable): + abortReason = "free_space_unreadable" + case errors.Is(err, errCutNoRoom): + abortReason = "no_room_to_cut" case errors.Is(err, errCutCOWCapacity): abortReason = "cow_capacity" case errors.Is(err, errCutBudgetRevoked): @@ -1540,10 +1556,10 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { // stage uploads large native dirty sets through logical reads, before fixing H. // It stops when the spill-budget remainder is reached or a round makes no // progress. Versions/HEAD generation bind every reusable immutable result. -func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { +func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, []string, error) { // Leave at most half the side budget exposed at the barrier. Streaming // staging uses no local payload file, even for a much larger image. - bound := int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) + bound := int(spillCap / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) staged := map[uint64]stagedChunk{} var intents []string @@ -1651,6 +1667,7 @@ func (l *chunkLayerImpl) abortCut(all bool) { func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) { l.stMu.Lock() defer l.stMu.Unlock() + l.noteSettled(l.head, head) l.head, l.remoteLSN, l.pending = copyHead(head), h, nil l.reusable = nil l.inflight = map[uint64]bool{} @@ -1679,7 +1696,7 @@ func isAllZero(b []byte) bool { func (l *chunkLayerImpl) EvictChunk(idx uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if idx >= l.numChunks { return fmt.Errorf("%w: chunk %d out of range", errChunkEvictRefused, idx) } @@ -1858,7 +1875,13 @@ func (l *chunkLayerImpl) Close() error { if w != nil { w.join() } + if h := testCloseJoinHook; h != nil { + h() // tests: Close has cancelled the layer and now joins its owners, the drainer among them + } l.wg.Wait() + if h := testCloseJoinedHook; h != nil { + h() // tests: the join returned + } l.stMu.Lock() protected := make(map[string]bool, len(l.pendingIntents)) for _, id := range l.pendingIntents { diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index 86dd77f065..4be2a15173 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -170,9 +170,16 @@ func TestChunkLayer_C2_StalledUploadDoesNotGateLocal(t *testing.T) { } // C3 no torn chunk: chunks are copied under the capture barrier, so every -// HEAD ever installed equals the image at its RemoteLSN even while a writer -// keeps overwriting the same chunk and flushing. Overlap is forced: each -// round holds the upload until the writer has completed rounds after it. +// HEAD ever installed equals the image at its RemoteLSN while the same chunk +// is overwritten and flushed. Each upload-entry event precedes three complete +// writer rounds, and the upload is released only after those rounds finish. +// Complementary capture/barrier witnesses: +// TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut parks a writer on a held +// local copy and checks its exclusion from the at-H image; +// TestChunkPrecopy_RedirtiedStagedChunkIsRecopied checks an overwrite between +// staging and the barrier (both WAL-resident and flushed); +// TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier checks that the barrier +// includes the admitted writer completed by its pre-barrier drain. func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() @@ -183,88 +190,50 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { } mustSyncFlush(t, s) - stop := make(chan struct{}) - var stopOnce sync.Once - stopWriter := func() { stopOnce.Do(func() { close(stop) }) } - progress := make(chan struct{}, 1024) - werr := make(chan error, 1) - var rounds atomic.Int64 - t.Cleanup(func() { - stopWriter() - select { - case <-werr: - case <-time.After(ctLocalBound): - t.Errorf("writer not joined within %v", ctLocalBound) + // The test goroutine is the writer: each upload-entry event is followed + // by three complete write/sync/flush rounds before that upload is released. + // This proves overlap without a throughput deadline or free-running writer. + writes := 0 + writeRound := func() { + lba := uint32(writes % ctChunkBlocks) + w.write(t, s, lba, byte(writes)) + if _, err := s.Sync(); err != nil { + t.Fatal(err) } - }) - go func() { - defer close(werr) - for i := 0; ; i++ { - select { - case <-stop: - return - default: - } - lba := uint32(i % ctChunkBlocks) - data := makeBlock(ctBlockSize, byte(i)) - lsn, err := s.Write(lba, data) - if err == nil { - w.record(lsn, lba, data) - _, err = s.Sync() - } - if err == nil { - err = s.flusher.flushOnce() - // A concurrent cut can invalidate a prepared checkpoint map; - // the production worker retries this explicit stale-proof outcome. - if errors.Is(err, ErrMapCoverageStale) { - err = nil - } - } - if err != nil { - werr <- err - return - } - rounds.Add(1) - select { - case progress <- struct{}{}: - default: - } + if err := s.flusher.flushOnce(); err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) } - }() - + writes++ + } for round := 0; round < 5; round++ { entered, release := holdPuts(t, f) done := startCapture(t, layer) - waitKey(t, entered, "held upload") - for len(progress) > 0 { - <-progress + select { + case <-entered: + case err := <-done: + t.Fatalf("round %d Capture ended before upload entry: %v", round, err) } - for need := 0; need < 3; need++ { // the writer must advance while the upload is held - select { - case <-progress: - case <-time.After(ctLocalBound): - t.Fatalf("round %d: writer made no progress while an upload was held", round) - } + for need := 0; need < 3; need++ { + writeRound() + } + select { + case err := <-done: + t.Fatalf("round %d Capture ended before upload release: %v", round, err) + default: } release() - if err := waitErr(t, done, "held capture"); err != nil { + if err := <-done; err != nil { t.Fatalf("round %d Capture: %v", round, err) } } for i := 0; i < 20; i++ { + writeRound() if _, err := layer.Capture(ctTimeout(t)); err != nil { t.Fatalf("free-running Capture %d: %v", i, err) } } - stopWriter() - if err := waitErr(t, werr, "writer"); err != nil { - t.Fatalf("writer: %v", err) - } - if rounds.Load() < 15 { - t.Fatalf("writer completed only %d rounds; overlap not established", rounds.Load()) - } - // Each held round installs a HEAD; a free-running capture with no new - // LSN since the last cut is idle and may skip its CAS. + // Every held and subsequent unheld capture has new writes. Retain the + // historical minimum of five held HEADs plus one unheld HEAD. if n := len(f.installedHeads()); n < 6 { t.Fatalf("%d HEADs installed, want the 5 held rounds plus at least one free-running", n) } diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go new file mode 100644 index 0000000000..6b004e08ee --- /dev/null +++ b/seaweed-block/core/storage/chunk_own.go @@ -0,0 +1,142 @@ +package storage + +import ( + "context" + "sort" +) + +// OwnProgress reports one OwnBatch call. +// - Owned: foreign chunks this call's cut re-uploaded under own keys. +// - Remaining: chunks HEAD still names with a foreign key after the call. +// - NotLocal: of those, chunks not local yet (the hydrate walker fills them). +type OwnProgress struct { + Owned int + Remaining int + NotLocal int +} + +// OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n +// chunks, lowest index first, whose HEAD key is foreign (foreign reports +// whether a key names another volume's object) and that are local (present, +// or every block written locally), and cuts +// with them as candidates: each is uploaded under a new own key under the +// cut's intent and published by the cut's one HEAD CAS, even when its bytes +// equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut +// is an ordinary cut, so guest writes since the last HEAD go with it. With +// nothing to own it runs no cut. A failed cut leaves HEAD as it was; the next +// call picks again from the current HEAD. +func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (OwnProgress, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + l.stMu.Lock() + var picked []uint64 + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + if len(picked) < n && l.chunkLocalLocked(idx) { + picked = append(picked, idx) + } + } + if len(picked) == 0 { + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + return p.OwnProgress, nil + } + l.own = make(map[uint64]bool, len(picked)) + for _, idx := range picked { + l.own[idx] = true + // A payload remembered from an earlier failed cut that matched HEAD + // was never uploaded (no key, data discarded): reusing it would skip + // the re-own upload. Drop it, so this cut reads and uploads the chunk. + if sc, ok := l.reusable[idx]; ok && sc.key == "" { + delete(l.reusable, idx) + } + } + l.stMu.Unlock() + _, err := l.captureLocked(ctx, false) + l.stMu.Lock() + l.own = nil + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + if err == nil { + for _, idx := range picked { + if ref, ok := p.head[idx]; !ok || !foreign(ref.Key) { + p.Owned++ + } + } + } + return p.OwnProgress, err +} + +type ownCount struct { + OwnProgress + head map[uint64]chunkRef +} + +// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. +func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { + c := ownCount{head: l.head.Chunks} + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c.Remaining++ + if !l.chunkLocalLocked(idx) { + c.NotLocal++ + } + } + return c +} + +func sortedForeign(chunks map[uint64]chunkRef, foreign func(string) bool) []uint64 { + var out []uint64 + for idx, ref := range chunks { + if foreign(ref.Key) { + out = append(out, idx) + } + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// owning reports whether chunk idx is re-owned by the running OwnBatch cut: +// it is uploaded under a new own key even when its bytes equal HEAD's. +func (l *chunkLayerImpl) owning(idx uint64) bool { + l.stMu.Lock() + defer l.stMu.Unlock() + return l.own[idx] +} + +// addOwnCandidatesLocked adds the running OwnBatch's chunks to a cut's +// candidates: a re-own reads the local copy, so an absent chunk is left out. +// Caller holds stMu. +func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { + for idx := range l.own { + if l.chunkLocalLocked(idx) { + out[idx] = true + } + } +} + +// chunkLocalLocked reports whether a re-own can read chunk idx without a +// fetch: it is present, or absent with every block written locally (a guest +// overwrite flushed before the walker reached it). Caller holds stMu. +func (l *chunkLayerImpl) chunkLocalLocked(idx uint64) bool { + if !l.absent[idx] { + return true + } + first := idx * l.chunkBlocks + for i := uint64(0); i < l.chunkBlocks; i++ { + b := first + i + if b >= uint64(l.s.NumBlocks()) { + break + } + if !l.localBlocks[b] { + return false + } + } + return true +} + +// unchangedFromHead reports whether a captured chunk equals HEAD's and was +// not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to +// HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so +// it is published like a changed chunk. +func unchangedFromHead(c capturedChunk, ref chunkRef, had bool) bool { + return had && !c.zero && ref.SHA256 == c.sum && c.key == "" +} diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go new file mode 100644 index 0000000000..75e8496a76 --- /dev/null +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -0,0 +1,192 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" +) + +func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } + +func ownCtx(t *testing.T) context.Context { return boundedCtx(t, context.Background()) } + +// M6.Restore.Owning>Owning: each batch is one cut that re-uploads at most n +// foreign chunks under own keys, the image unchanged, until none is left. +func TestOwnBatch_BoundedBatchesReplaceEveryForeignKey(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + want := remote.imageOf(t, before.head) + if p, err := layer.HydrateAll(ownCtx(t)); err != nil || p.Remaining != 0 { + t.Fatalf("hydrate: %+v %v", p, err) + } + total := ctNumBlocks / ctChunkBlocks + left := total + for left > 0 { + puts := remote.stats().puts + cas := remote.stats().cas + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + if err != nil { + t.Fatal(err) + } + step := min(3, left) + if p.Owned != step || p.Remaining != left-step || p.NotLocal != 0 { + t.Fatalf("batch: %+v, want %d owned and %d remaining", p, step, left-step) + } + if got := remote.stats().puts - puts; got != step { + t.Fatalf("batch uploaded %d chunks, want exactly %d (bounded)", got, step) + } + if got := remote.stats().cas - cas; got != 1 { + t.Fatalf("batch made %d HEAD CAS, want one", got) + } + left -= step + } + after := remote.stats().head + for idx, ref := range after.Chunks { + if seedForeign(ref.Key) { + t.Fatalf("chunk %d still foreign after the last batch: %s", idx, ref.Key) + } + } + if !bytes.Equal(remote.imageOf(t, after), want) { + t.Fatal("owning changed the volume image") + } + cas := remote.stats().cas + if p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign); err != nil || p != (OwnProgress{}) || remote.stats().cas != cas { + t.Fatalf("nothing left to own must run no cut: %+v %v", p, err) + } +} + +// A chunk not local yet is never fetched by a batch: it waits for the walker. +func TestOwnBatch_SkipsChunksNotLocal(t *testing.T) { + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + total := ctNumBlocks / ctChunkBlocks + if err != nil || p.Owned != 0 || p.Remaining != total || p.NotLocal != total { + t.Fatalf("batch before any hydration: %+v %v", p, err) + } + after := remote.stats() + if after.cas != before.cas || after.gets != before.gets { + t.Fatalf("a batch with nothing local cut or fetched: cas %d->%d gets %d->%d", before.cas, after.cas, before.gets, after.gets) + } +} + +// A batch is an ordinary cut: a guest write since the last HEAD goes with it. +func TestOwnBatch_CarriesGuestWrites(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks*6+1, makeBlock(ctBlockSize, 0xAB)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.OwnBatch(ownCtx(t), 2, seedForeign); err != nil { + t.Fatal(err) + } + img := remote.imageOf(t, remote.stats().head) + off := (ctChunkBlocks*6 + 1) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xAB)) { + t.Fatal("the guest write did not reach HEAD with the batch") + } +} + +// A chunk whose every block the guest overwrote and flushed before the walker +// reached it stays absent but is fully local: a batch owns it with no fetch +// (codex01 #340 S1: otherwise nothing ever cuts it and the driver stalls). +func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + const idx = 3 + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(idx*ctChunkBlocks+i, makeBlock(ctBlockSize, 0xC0+byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[idx] + layer.stMu.Unlock() + if !absent { + t.Fatal("fixture: the overwritten chunk must still be absent") + } + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + seedKey := remote.stats().head.Chunks[idx].Key + // The stall needs this chunk to be the only foreign one left: then no + // other pick triggers the cut that would carry its guest write. + onlyThis := func(key string) bool { return key == seedKey } + p, err := layer.OwnBatch(ownCtx(t), 3, onlyThis) + if err != nil || p.Owned != 1 || p.Remaining != 0 { + t.Fatalf("batch with only the fully overwritten chunk foreign: %+v %v, want it owned", p, err) + } + if n := countGets(remote)[seedKey]; n != 0 { + t.Fatalf("the fully overwritten chunk was fetched %d times", n) + } + img := remote.imageOf(t, remote.stats().head) + for i := 0; i < ctChunkBlocks; i++ { + off := (idx*ctChunkBlocks + i) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xC0+byte(i))) { + t.Fatalf("block %d of the overwritten chunk is not the guest's in HEAD", i) + } + } +} + +// A failed ordinary cut remembers an equal-to-HEAD chunk without a key; the +// next batch must still upload it under an own key (codex01 #340 S2). +func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + same := makeBlock(ctBlockSize, 0x40) // block 0 rewritten with HEAD's own bytes + if _, err := s.Write(0, same); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0xEE)); err != nil { // chunk 1 changed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + remote.mu.Lock() + remote.failPut = errors.New("test: put refused") + remote.mu.Unlock() + failCtx, cancelFail := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelFail() + if _, err := layer.Cut(failCtx); err == nil { + t.Fatal("fixture: the ordinary cut must fail") + } + remote.mu.Lock() + remote.failPut = nil + remote.mu.Unlock() + layer.stMu.Lock() + sc, kept := layer.reusable[0] + layer.stMu.Unlock() + if !kept || sc.key != "" { + t.Fatalf("fixture: the failed cut must remember chunk 0 equal and keyless: kept=%v key=%q", kept, sc.key) + } + p, err := layer.OwnBatch(ownCtx(t), 1, seedForeign) + if err != nil || p.Owned != 1 { + t.Fatalf("batch after the failed cut: %+v %v, want chunk 0 owned", p, err) + } + if k := remote.stats().head.Chunks[0].Key; seedForeign(k) { + t.Fatalf("chunk 0 still names the foreign key %s", k) + } + if !bytes.Equal(remote.imageOf(t, remote.stats().head)[:ctBlockSize], same) { + t.Fatal("chunk 0's bytes changed") + } +} diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go index 49822ee959..7803020e59 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut.go +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -17,7 +17,7 @@ var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil) func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() // delivers the cut's OnPublishSettled report after the lock l.stMu.Lock() last := l.stats.LastCutNs l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 2a7a0e4655..526e52c9e7 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -160,7 +160,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if err := l.lockPrecopy(ctx); err != nil { return ChunkCutResult{}, err } - defer l.capMu.Unlock() + defer l.unlockCap() defer func() { if result.Precopy.Frozen && !result.Precopy.IsReplay() { l.RememberDetachReport(result.Precopy) diff --git a/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go new file mode 100644 index 0000000000..c7e84cdc6e --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go @@ -0,0 +1,47 @@ +package storage + +import ( + "errors" + "testing" +) + +// TestPrecopyRoundLoopRetriesOnlyNamedErrors pins that a failed rolling +// pre-copy round starts another round only after a COW abort, an unavailable +// remote or a HEAD precondition failure; any other error ends the loop at once. +func TestPrecopyRoundLoopRetriesOnlyNamedErrors(t *testing.T) { + errNotPrimary := errors.New("test: not primary") + for _, tc := range []struct { + name string + first error + rounds int + }{ + {"other error", errNotPrimary, 1}, + {"COW aborted", errCutCOWAborted, 2}, + {"remote unavailable", errChunkRemoteUnavailable, 2}, + {"HEAD precondition", errChunkHeadPrecondition, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + // Every round fails at capture admission: the first with the error + // under test, any later one with an error that is never retried. + calls := 0 + l.cfg.CaptureAllowed = func() error { + calls++ + if calls == 1 { + return tc.first + } + return errNotPrimary + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { + t.Error("refused rounds reached the final stop") + return true + }) + if !errors.Is(err, errNotPrimary) { + t.Fatalf("err=%v, want the non-retried refusal", err) + } + if calls != tc.rounds || len(r.Precopy.Rounds) != tc.rounds { + t.Fatalf("rounds: admission calls=%d reported=%d, want %d", calls, len(r.Precopy.Rounds), tc.rounds) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go new file mode 100644 index 0000000000..5be9c0093f --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go @@ -0,0 +1,25 @@ +package storage + +import ( + "testing" + "time" +) + +// TestPrecopySampleHistoryKeepsNewest32 pins that the pre-copy cost sample +// history is bounded at 32 entries and keeps the newest ones. +func TestPrecopySampleHistoryKeepsNewest32(t *testing.T) { + l := &chunkLayerImpl{} + const taken = 40 + for i := 1; i <= taken; i++ { + // The fixed cost carries the sample's order. + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i)) + } + if len(l.precopySamples) != 32 { + t.Fatalf("sample history holds %d entries, want 32", len(l.precopySamples)) + } + for j, s := range l.precopySamples { + if want := time.Duration(taken - 32 + 1 + j); s.fixed != want { + t.Fatalf("sample %d has fixed=%s, want %s (newest 32 kept in order)", j, s.fixed, want) + } + } +} diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go new file mode 100644 index 0000000000..2895433cca --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -0,0 +1,72 @@ +package storage + +// headTransition is one confirmed publication: HEAD moved from prev to next. +type headTransition struct{ prev, next chunkHead } + +// noteSettled records a confirmed publication for OnPublishSettled, in +// publication order. l.stMu held; prev is the HEAD the layer held before +// next. +func (l *chunkLayerImpl) noteSettled(prev, next chunkHead) { + if l.cfg.OnPublishSettled == nil || next.Gen == prev.Gen { // a no-op cut publishes nothing + return + } + l.settled = append(l.settled, headTransition{prev: copyHead(prev), next: copyHead(next)}) +} + +// unlockCap releases the capture lock, then delivers the publications +// recorded so far. +func (l *chunkLayerImpl) unlockCap() { + l.capMu.Unlock() + l.runPublishSettled() +} + +// runPublishSettled delivers recorded publications to OnPublishSettled one +// at a time, in publication order, outside the capture and state locks. One +// caller at a time drains the queue (any other caller only leaves its +// reports queued for it, so a hook that publishes again cannot deadlock); +// the drainer is registered with Close. Once Close has begun, no further +// report is dequeued and the rest are dropped; a report already dequeued +// may still reach the hook, and Close waits for it. +func (l *chunkLayerImpl) runPublishSettled() { + hook := l.cfg.OnPublishSettled + if hook == nil { + return + } + l.stMu.Lock() + if l.settledDraining || len(l.settled) == 0 { + l.stMu.Unlock() + return + } + if l.closed { + l.settled = nil + l.stMu.Unlock() + return + } + l.settledDraining = true + l.wg.Add(1) // under stMu while not closed: Close's wait covers this drain + l.stMu.Unlock() + defer l.wg.Done() + for { + l.stMu.Lock() + if l.closed { + l.settled = nil + } + if len(l.settled) == 0 { + l.settledDraining = false + l.stMu.Unlock() + return + } + t := l.settled[0] + l.settled = l.settled[1:] + l.stMu.Unlock() + hook(l.ctx, t.prev, t.next) + } +} + +// testCloseJoinHook, set only by tests, runs in Close after the layer is +// cancelled and before it joins its owners (the active drainer among them). +var testCloseJoinHook func() + +// testCloseJoinedHook, set only by tests, runs in Close when that join has +// returned. +var testCloseJoinedHook func() diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go new file mode 100644 index 0000000000..186c7b25fc --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -0,0 +1,366 @@ +package storage + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +type settledLog struct { + mu sync.Mutex + got [][2]uint64 // {prev gen, next gen} + // capFree records, per call, whether the capture lock was free. + capFree []bool +} + +func (s *settledLog) hook(l *chunkLayerImpl) func(context.Context, ChunkHead, ChunkHead) { + return func(_ context.Context, prev, next ChunkHead) { + free := l.capMu.TryLock() + if free { + l.capMu.Unlock() + } + s.mu.Lock() + s.got = append(s.got, [2]uint64{prev.Gen, next.Gen}) + s.capFree = append(s.capFree, free) + s.mu.Unlock() + } +} + +func (s *settledLog) snapshot() ([][2]uint64, []bool) { + s.mu.Lock() + defer s.mu.Unlock() + return append([][2]uint64(nil), s.got...), append([]bool(nil), s.capFree...) +} + +func attachWithSettled(t *testing.T, f *fakeChunkRemote) (*WALStore, *chunkLayerImpl, *settledLog) { + t.Helper() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + log := &settledLog{} + layer.cfg.OnPublishSettled = log.hook(layer) + return s, layer, log +} + +// Each confirmed publication is reported once, with the HEAD before and +// after it, after the capture lock is released; a no-op cut reports nothing. +func TestChunkPublishSettled_ReportsEachPublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { // nothing new: no-op + t.Fatal(err) + } + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, free := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } + for i, ok := range free { + if !ok { + t.Fatalf("report %d ran under the capture lock", i) + } + } +} + +// A CAS whose outcome was unknown, found applied by a later cut, is reported +// when it is settled, before that cut's own publication. +func TestChunkPublishSettled_ReportsALatePublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("HEAD unreadable") } + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut with an unresolved CAS succeeded") + } + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v before the CAS was resolved", got) + } + f.mu.Lock() + f.failGet = nil + f.mu.Unlock() + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, _ := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want the late publication 0->1, then 1->2", got) + } +} + +// A closing layer drops reports it has not run; without a hook nothing is +// recorded. +func TestChunkPublishSettled_ClosedAndUnset(t *testing.T) { + f := newFakeChunkRemote() + _, layer, log := attachWithSettled(t, f) + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + if err := layer.Close(); err != nil { + t.Fatal(err) + } + layer.runPublishSettled() + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v after Close", got) + } + + s2, _ := newChunkTestStore(t) + plain := mustAttach(t, s2, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + w.write(t, s2, 2, 0x22) + if _, err := plain.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + plain.stMu.Lock() + n := len(plain.settled) + plain.stMu.Unlock() + if n != 0 { + t.Fatalf("%d publications recorded without a hook", n) + } +} + +func waitClosed(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// worker is a goroutine a test launches. Its bounded join (after release, +// if given) is registered as cleanup before it starts, so a failing test +// never leaves it running; the result is read once and kept. +type worker struct { + name string + done chan error + once sync.Once + err error + ok bool +} + +func launch(t *testing.T, name string, release func(), f func() error) *worker { + t.Helper() + w := &worker{name: name, done: make(chan error, 1)} + t.Cleanup(func() { + if release != nil { + release() + } + if _, ok := w.result(10 * time.Second); !ok { + t.Errorf("%s never returned", name) + } + }) + go func() { w.done <- f() }() + return w +} + +// result waits up to d for the worker; ok is false on timeout. +func (w *worker) result(d time.Duration) (error, bool) { + w.once.Do(func() { + select { + case w.err = <-w.done: + w.ok = true + case <-time.After(d): + } + }) + if !w.ok { + w.once = sync.Once{} // a timed-out wait may be retried + } + return w.err, w.ok +} + +func (w *worker) mustReturn(t *testing.T) { + t.Helper() + err, ok := w.result(10 * time.Second) + if !ok { + t.Fatalf("%s did not return", w.name) + } + if err != nil { + t.Fatalf("%s: %v", w.name, err) + } +} + +// Overlapping publishers: while the first report's hook is held, a second +// publisher's cut completes and returns; its report is delivered after the +// first, never concurrently with it. +func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var once, rel sync.Once + releaseHook := func() { rel.Do(func() { close(release) }) } + var mu sync.Mutex + var got [][2]uint64 + active, maxActive := 0, 0 + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + active++ + maxActive = max(maxActive, active) + got = append(got, [2]uint64{prev.Gen, next.Gen}) + first := len(got) == 1 + mu.Unlock() + if first { + once.Do(func() { close(entered) }) + <-release + } + mu.Lock() + active-- + mu.Unlock() + } + w := newWriteLog() + w.write(t, s, 2, 0x22) + a := launch(t, "the first publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) + waitClosed(t, entered, "the first report") + w.write(t, s, 9, 0x29) + b := launch(t, "the second publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) + if err, ok := b.result(10 * time.Second); !ok { + t.Fatal("the second publisher waited on the first report's hook") + } else if err != nil { + t.Fatal(err) + } + mu.Lock() + n := len(got) + mu.Unlock() + if n != 1 { + t.Fatalf("%d reports delivered while the first was held; want 1", n) + } + releaseHook() + a.mustReturn(t) + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} || maxActive != 1 { + t.Fatalf("reports %v (max concurrent %d); want [0->1 1->2], one at a time", got, maxActive) + } +} + +// Close during the first of two queued reports: the first hook sees its +// context end, Close reaches its join of the active drainer and waits there +// (witnessed, not timed), and the second report is never delivered. +func TestChunkPublishSettled_CloseDropsUnstartedReports(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var rel sync.Once + releaseHook := func() { rel.Do(func() { close(release) }) } + joining := make(chan struct{}) + var joinOnce sync.Once + var order []string // "hook returned" and "Close joined", in the order they happened + var orderMu sync.Mutex + note := func(e string) { orderMu.Lock(); order = append(order, e); orderMu.Unlock() } + testCloseJoinHook = func() { joinOnce.Do(func() { close(joining) }) } + testCloseJoinedHook = func() { note("Close joined") } + t.Cleanup(func() { testCloseJoinHook, testCloseJoinedHook = nil, nil }) + var hookCtx context.Context + var mu sync.Mutex + calls := 0 + layer.cfg.OnPublishSettled = func(ctx context.Context, _, _ ChunkHead) { + mu.Lock() + calls++ + n := calls + if n == 1 { + hookCtx = ctx + } + mu.Unlock() + if n == 1 { + close(entered) + <-release + note("hook returned") + } + } + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 0}, next: chunkHead{Gen: 1}}, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + drainer := launch(t, "the drainer", releaseHook, func() error { layer.runPublishSettled(); return nil }) + waitClosed(t, entered, "the first report") + closer := launch(t, "Close", releaseHook, layer.Close) + mu.Lock() + ctx := hookCtx + mu.Unlock() + waitClosed(t, ctx.Done(), "Close cancelling the hook's context") + waitClosed(t, joining, "Close reaching its join of the drainer") + releaseHook() + drainer.mustReturn(t) + closer.mustReturn(t) + orderMu.Lock() + seq := append([]string(nil), order...) + orderMu.Unlock() + if len(seq) != 2 || seq[0] != "hook returned" || seq[1] != "Close joined" { + t.Fatalf("order %v; want the running hook to return before Close's join does", seq) + } + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("%d reports delivered; want the second dropped after Close began", calls) + } +} + +// A hook may publish again: its own report follows, in order, with no +// deadlock. +func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + var mu sync.Mutex + var got [][2]uint64 + nested := false + // One cancellation covers the outer cut and the cut its hook makes; + // cleanup cancels it before the bounded join. + cutCtx, cancelCuts := context.WithCancel(context.Background()) + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + got = append(got, [2]uint64{prev.Gen, next.Gen}) + again := !nested + nested = true + mu.Unlock() + if again { + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(cutCtx); err != nil { + t.Errorf("cut from the hook: %v", err) + } + } + } + w.write(t, s, 2, 0x22) + cut := launch(t, "a cut whose hook publishes", cancelCuts, func() error { _, err := layer.Cut(cutCtx); return err }) + if err, ok := cut.result(10 * time.Second); !ok { + t.Fatal("a hook that publishes deadlocked") + } else if err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } +} + +// A periodic cut (CutUnlessCutSince) reports its publication like any other +// cut, after the capture lock is released, before it returns. +func TestChunkPublishSettled_PeriodicCutReports(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 3, 0x33) + if _, skipped, err := layer.CutUnlessCutSince(ctTimeout(t), 0); err != nil || skipped { + t.Fatalf("periodic cut: skipped=%v err=%v", skipped, err) + } + got, free := log.snapshot() + if len(got) != 1 || got[0] != [2]uint64{0, 1} || !free[0] { + t.Fatalf("periodic cut reports %v (capture lock free %v); want one report 0->1 with the lock free", got, free) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index c8461ba69a..d467960d7a 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -310,6 +310,22 @@ func validChunkIntentID(id string) bool { // chunkLayerConfig configures one attachment. type chunkLayerConfig struct { + // OnPublishSettled, when set, is called once per confirmed publication + // (a cut, a detach, or an earlier unresolved CAS found applied), with the + // HEAD before and after it (INV-PUBLISH-SETTLED-001). Calls are + // serialized and in publication order, outside the capture lock, on + // whichever publishing caller is draining the reports (a publisher may + // return before its own report is delivered by the drainer). The drainer + // is registered with Close; ctx ends with Close. Once Close has begun no + // further report is dequeued; a report already dequeued may still reach + // the hook after Close began (Close then waits for it). + // + // The hook MUST return without blocking and without remote calls; enqueue + // work to your own worker. It runs on the cut or detach caller's + // goroutine, before a detach returns: its duration is a guest-visible wait + // (Part C wait sites). While a hook stalls, later reports queue without a + // bound. A hook may publish again (its report is delivered after). + OnPublishSettled func(ctx context.Context, prev, next ChunkHead) // ChunkBlocks is the number of consecutive blocks per chunk (1024 for // 4 KiB blocks and 4 MiB chunks). ChunkBlocks uint32 @@ -382,6 +398,11 @@ type chunkLayerConfig struct { // retries), never publishes a partial image or refuses the guest mutation. // 0 defaults to defaultCOWSpillLimit; negative is refused. COWSpillLimit int64 + // COWSpillFree, optional, returns the free bytes of the filesystem that + // holds the side file. When set, it is read at each cut and that cut's + // spill cap is min(COWSpillLimit, free/2 - 1 GiB), at least 0; an error + // counts as no free space. + COWSpillFree func() (int64, error) // testReconcileHold, set only by this package's tests, holds the // reconciler before each slice until a token is received or the @@ -481,7 +502,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached - CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read PendingUnresolved bool // an unresolved HEAD proposal is held now @@ -498,6 +519,12 @@ type chunkLayerStats struct { // AbsentChunks is the number of HEAD-named chunks still absent with a // block not local (what HydrateAll would still fetch); 0 = fully local. AbsentChunks int + // COWSpillCap is the last cut's side-file cap in bytes, read once per + // cut; COWSpillCapReason is why it is 0, when the free space made it so: + // no_room_to_cut (half the free space is within the 1 GiB reserve) or + // free_space_unreadable (the free space could not be read). + COWSpillCap int64 + COWSpillCapReason string `json:",omitempty"` } // chunkCutResult is the outcome of one successful cut. diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d5318a20df..930b5f18c0 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -244,13 +244,15 @@ stateDiagram-v2 [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline Forking --> Aborted: GC tombstones the HEAD - Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys - Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Restoring --> Hydrating: driver starts the paced walker + Hydrating --> Owning: batch cuts start (the walker may still run) + Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys + Owning --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] Aborted --> [*]: target deleted ``` -Snapshots of the target are refused in `Forking` and `Restoring`. +Snapshots of the target are refused until `Independent`. The driver (`core/host/volume/chunk_restore.go`) runs these steps from the target's own facts; `POST /chunk/restore` starts it and `sw-block ops chunk restore` calls it. ### Attached-volume scheduling diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c3e72366fc..ed1961e51c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -25,8 +25,11 @@ The design is described in three documents, and this one collects their machines - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) - [M5 The cut pipeline](#m5-the-cut-pipeline) - [M6 Chunk lifecycle](#m6-chunk-lifecycle) + - [M7. Host background-cut admission](#m7-host-background-cut-admission) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) +- [Part D. Wait ownership](#part-d-wait-ownership) +- [Part E. Quantities](#part-e-quantities) --- @@ -58,7 +61,7 @@ stateDiagram-v2 | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| 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` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | @@ -93,7 +96,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001` | @@ -242,7 +245,7 @@ stateDiagram-v2 |---|---|---|---| | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | +| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | @@ -250,7 +253,7 @@ stateDiagram-v2 | Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | | Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | -| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | | Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | @@ -293,7 +296,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | -| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | +| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | +| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | +| restore (Owning) | Independent | M6.Restore.Owning>Independent: the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-001` | | restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -305,7 +311,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | intent live | removed (catalog) | the operation's create is confirmed or can never apply; the delete outlives the caller's cancellation but is bounded by `dropIntentTimeout` | `core/frontend/chunkstore/catalog.go` `dropIntent` | `INV-CAT-INTENT-DROP-BOUNDED-001` | | intent live | expired | conservative elapsed age exceeds the TTL after pairwise clock skew, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001`, `INV-GC-CLOCK-SKEW-001` | | — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks separated by more than grace plus clock skew, binding age exceeds grace plus skew plus one-second timestamp precision, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-CLOCK-SKEW-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks separated by more than grace plus clock skew, binding age exceeds grace plus skew plus one-second timestamp precision, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-CLOCK-SKEW-001`, `INV-GC-DELETE-EXACT-FID-001`, `INV-GC-GRACE-RESTART-001` | | tombstoned, DELETE rejected | tombstoned, retry later; continue other bindings | definite HTTP400 is reported per object; no success recorded for the rejected fid; complete mark coverage is saved before returning partial failure; cancellation, unknown/other DELETE errors and metadata errors still stop the pass | `core/frontend/chunkstore/gc.go` `Collector.run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `INV-GC-DELETE-PROGRESS-001` | | tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | @@ -382,7 +388,11 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger +<<<<<<< HEAD 137 rows: 117 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 122 new. +======= +160 rows: 138 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 145 new. +>>>>>>> origin/main The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -461,13 +471,18 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +<<<<<<< HEAD | `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | +======= +| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | +>>>>>>> origin/main Notes: - `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. - `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). - `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. +- `INV-MASTER-JOURNAL-ISOLATION-001`: a refused heartbeat gets FailedPrecondition. A new placement is either a workspace placement or one the product loop plans. Work the node already has means: the node serves by durable state (a placement slot or a current authority line that names it), a repeated identical placement, or the retry of an issued move. Without strict mode, co-location only raises an alarm. ### B.3 Core: replication and replica roles @@ -499,10 +514,11 @@ Notes: | `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | | `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | | `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`) | — | ACTIVE | +| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | @@ -513,9 +529,10 @@ Notes: Notes: -- `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply) before it reads or writes; read-only commands and modes do not run it. +- `INV-WS-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-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. Verify reports a violation it observes during a pass (a key HEAD named, then dropped, then named again is `ROOT_INVALID`): `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`), the named-again cases. - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. - `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. - `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). @@ -539,10 +556,12 @@ Notes: | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | | `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE | +| `INV-CUT-READ-LOGICAL-001` | Every cut read of a chunk (COW copy, COW save and pre-copy staging) resolves each block through the dirty map first, validates the whole WAL record it read and re-resolves on a mismatch, and reads the extent only for a block with no dirty entry; no cut path reads the extent region directly. | M5 Stage / Copy | `core/storage/chunk_cut_cow.go` `readCOWChunk`, `readLocalBlock`; `core/storage/chunk_layer.go` `readChunk`; `core/storage/walstore_v3.go` `readDirtyV3Into` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`); `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE | | `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE | +| `INV-CUT-GUEST-BOUNDED-WAIT-001` | Inside an open cut window, a guest write to a candidate chunk waits only for local work, never for a remote fetch or upload: at most 250 ms for a saver slot (then only the cut aborts) and one local capture of the chunk's at-H image. | M5 OpenWindow → Copy (guest write during Copy / Upload) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `claim`, `acquireSaver`, `readCOWChunk`, `fillMissing` | `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained` (`core/storage/chunk_cut_cow_fill_test.go`) | `CutCOW2` `Blocked` defines which writes wait; remote I/O is not modelled | ACTIVE | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | -| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | +| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SpillCapAbortsTheCut` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | | `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | | `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | @@ -558,6 +577,8 @@ Notes: - `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). +- `INV-CUT-READ-LOGICAL-001`: the staging clause (`readChunk` through `WALStore.Read`) is enforced by reading; no test captures WAL-only bytes through a staging round. +- `INV-CUT-GUEST-BOUNDED-WAIT-001`: the capture a write waits for is its own or that of the chunk's current copier or saver. Lazily absent blocks are left to the copier, which fills them from the base HEAD after it releases the entry. - `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. @@ -575,20 +596,47 @@ Notes: | `INV-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | +| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie), never a rebuilt one. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`); `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and past its age bound, and restarts when a mark finds it rooted or its binding changed; a deleting snapshot attempt roots its keys until its deleting time is past the grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE | +| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | 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/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | +| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE | | `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | No finding is reported for a chunk or segment that no root of the final view names: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk and reads each segment key at most once per pass: a settled object is never checked again, however often or under whatever reference a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle`, `segment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is the closing read itself, one that names no chunk the pass had not seen, with no read after it. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_QuietClosingReadIsTheFinalView`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk or segment key and class, computed only at Reconcile from the outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile`, `reconcileSegment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ORDER-FREE-001` | Findings and counters are a function of the outcomes, the references seen and the final view, not of the order of reads. | M6 (reader) | `core/frontend/chunkstore/verify.go` `judgeChunk`, `judgeSegment`, `reconcile` | `TestVerify_SegmentFindingsDoNotDependOnOrder`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CLOSE-BOUND-001` | A pass completes only on a closing read that returns a decodable HEAD naming no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise it is incomplete, with its reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `readHead`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | -| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`nc_red_SnapDuringRestore`) | ACTIVE | | `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | -| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | +| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | +| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: +- `INV-GC-DELETE-EXACT-FID-001`: what happens after a rejected or failed delete is `INV-GC-DELETE-PROGRESS-001`. The tombstone-before-delete order is asserted only through a rejected delete; on a successful delete it is enforced by reading. The cookie check itself is done by the SeaweedFS volume server, not by this repository. +- `INV-GC-GRACE-RESTART-001`: "past the grace" means past the grace plus the clock-skew bound of `INV-GC-CLOCK-SKEW-001`. The restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test. +- `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code. +- `INV-FORK-FROM-SEALED-001`: the case of a name whose attempt is still in flight (name record present, attempt entry absent) is enforced by reading; no test forks during a held snapshot create. - `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. +- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists. +- `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing. +- `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it. +- `ChunkRemote.ReclaimKey` is the Collector's per-key step (`reclaimBinding`) exported, not a new admission: `INV-GC-REACHABLE-001` (reachability and the two-mark grace) stays the Collector's, and a `ReclaimKey` caller must itself know nothing references the key. The step keeps `INV-CHUNK-WRITE-ONCE-001`: the binding is tombstoned, its exact fid deleted, and the binding kept for ever, never rebound; owner-qualified keys are refused. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing @@ -639,6 +687,11 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| | `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (other platforms retain fsync). The selected mode and reason are logged and exposed in durable status without mid-life reselection. Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`), `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB | + +Notes: + +- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call. ## Part C. Change rules @@ -651,6 +704,14 @@ How a fix or a feature is calibrated against this model: 5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. 6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. +### C.W Wait sites (SYSTEM-MATH Part C) + +One row per wait in the data and control paths. Guest-visible rows on one path must sum to at most 5 s. + +| Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible | +|---|---|---|---|---|---|---| +| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | + Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. ### Dark v3 offline reader (row12a) @@ -672,3 +733,9 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. + +## Part E. Quantities + +| Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap | +|---|---|---|---|---|---| +| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; the free space is read once per cut and that cap bounds both staging and the copy window; off Linux, the configured cap. Shown per cut in the layer stats (`COWSpillCap`, `COWSpillCapReason`: `no_room_to_cut` when the free space is within the reserve, `free_space_unreadable` when the read fails) | the saver: `core/storage/chunk_cut_cow.go` `readCutSpill`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (retryable), counted as `cow_capacity`, or as `no_room_to_cut` / `free_space_unreadable` when the free space made the cap 0; the guest write completes and nothing partial is published | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5dc3e958cf..2dee559ccc 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -118,7 +118,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | -| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. Claim-era model: `ClaimUntilHead` selects the fork claim as it was before fork claims were removed (`INV-SNAP-DELETE-ANY-ORDER-001`), the strict variant keeps it until independent; the code no longer claims, and the no-claim variant ships with the restore driver. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S10 | `RestoreIndependence` | Independent restore: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | | S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla index 796850fe6a..66b87257ff 100644 --- a/seaweed-block/docs/spec/RestoreIndependence.tla +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -1,7 +1,6 @@ ------------------------------ MODULE RestoreIndependence ------------------------------ (***************************************************************************) -(* Independent restore: restore a snapshot into a volume that ends up *) -(* owning all its chunks, with no lineage to the source. *) +(* Independent restore of a snapshot into a new volume. *) (* Source volume V with HEAD and one sealed snapshot S; target T restored *) (* from S. T's HEAD maps indexes to fids; a fid is owned by V (a "@V/" *) (* ref) or by T. Steps: 0 claim S; 1 fork (T HEAD = S's fids, all V-owned) *) @@ -12,8 +11,14 @@ (* no root reaches) may run at any point; V may be deleted at any point; *) (* the restore process may crash and a new owner resumes from REMOTE facts *) (* only (forced move). Mutants are constants (FALSE = the design). *) -(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) +(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) (* spec models only what the restore adds, not the superseded list/grace. *) +(* NOCLAIM: with NoClaim = TRUE claims are removed; *) +(* a snapshot delete never looks at a fork. Safety of the ForkBegin.. *) +(* ForkEnd window comes from two time rules on one clock: (D) ForkEnd only *) +(* while now < readAt + D, else ForkFail; (G) a deleted S stays a GC root *) +(* while now < delAt + G. With NoClaim = FALSE nothing below changes the *) +(* old model (Tick, ForkFail, ForkNotFound disabled; new variables fixed). *) (***************************************************************************) EXTENDS Integers, FiniteSets, TLC @@ -33,7 +38,15 @@ CONSTANTS RetentionIgnoresMarker, \* after the marker, V's retention still treats T as holding S \* ---- added in review (r0.1) ---- ClaimUntilHead, \* r0.2 OPTION 1: the claim is dropped when T's HEAD is published (today's fork semantics) - NoIntent \* uploaded batch fids are not rooted by an intent before the HEAD CAS + NoIntent, \* uploaded batch fids are not rooted by an intent before the HEAD CAS + \* ---- NOCLAIM variant; old cfgs: NoClaim = FALSE, D = G = MaxTick = 0, the three below TRUE ---- + NoClaim, \* TRUE: no claim ever holds S; DeleteS needs only slive; time rules D and G apply + D, \* fork deadline: ForkEnd only while now < readAt + D (read only when NoClaim) + G, \* grace: a deleted S stays a root while now < delAt + G (read only when NoClaim) + MaxTick, \* bound of the clock (Tick is enabled only when NoClaim) + ForkChecksDeadline,\* design TRUE; mutant FALSE = ForkEnd at any time + DeletedRooted, \* design TRUE; mutant FALSE = a deleted S stops being a root at once + ResumeRereads \* design TRUE; mutant FALSE = a resume in the fork window reuses the old read (fresh deadline, S not re-read) Idx == 1..NIdx VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i @@ -41,6 +54,7 @@ TF == [i \in Idx |-> <<"T", i>>] \* T's own fid for index i Fids == {VF[i] : i \in Idx} \cup {TF[i] : i \in Idx} \* r0.1: "no HEAD yet" is a function too (TLC cannot compare a function with a string) NoHead == [i \in Idx |-> <<"N", i>>] +None == -1 \* nc: "no tick" encoding for readAt / delAt VARIABLES store, \* Fids -> "none" | "pres" | "del" @@ -54,40 +68,70 @@ VARIABLES tsnap, \* a snapshot of T (its fid set), {} if none gclist, \* fids put on a GC list (rule 8 check) localdone,\* local "restore done" flag of the current owner (ResumeLocal mutant) - crashes, gcs + crashes, gcs, + \* ---- nc (all fixed at their Init value when NoClaim = FALSE) ---- + now, \* the one clock + readAt, \* tick at which the current fork attempt read S (None if no attempt in progress) + delAt, \* tick at which S was deleted (None while S lives) + sdelfk, \* history: S was deleted while step = "fk" (for the witness) + ffail \* history: a fork attempt failed on its deadline (for the witness) -vars == <> +tvars == <> +vars == <> THeadFids == IF thead = NoHead THEN {} ELSE {thead[i] : i \in Idx} VRefs == {i \in Idx : thead # NoHead /\ thead[i][1] = "V"} \* roots: V's HEAD (while V lives), S (while it lives), T's HEAD, T's snapshot, \* uploaded-but-unpublished batch fids (intent roots them), S's fids while claimed SFids == {VF[i] : i \in Idx} +\* nc rule G: a deleted S stays a root for G ticks (FALSE whenever NoClaim = FALSE) +SGrace == NoClaim /\ DeletedRooted /\ ~ slive /\ delAt # None /\ now < delAt + G Roots == (IF vlive THEN SFids ELSE {}) - \cup (IF slive THEN SFids ELSE {}) + \cup (IF (slive \/ SGrace) THEN SFids ELSE {}) \cup THeadFids \cup tsnap \cup (IF NoIntent THEN {} ELSE up) \* S may be deleted by retention when nothing holds it SHeld == claim \/ (RetentionIgnoresMarker /\ thead # NoHead) +\* nc: with NoClaim the snapshot delete never looks at a fork +SDeletable == slive /\ (NoClaim \/ ~ SHeld) +\* nc rule D (TRUE whenever NoClaim = FALSE) +DeadlineOK == (~ NoClaim) \/ (~ ForkChecksDeadline) \/ (now < readAt + D) Init == /\ store = [f \in Fids |-> IF f[1] = "V" THEN "pres" ELSE "none"] /\ vlive = TRUE /\ slive = TRUE /\ claim = FALSE /\ thead = NoHead /\ step = "start" /\ up = {} /\ marker = FALSE /\ tsnap = {} /\ gclist = {} /\ localdone = FALSE /\ crashes = 0 /\ gcs = 0 + /\ now = 0 /\ readAt = None /\ delAt = None /\ sdelfk = FALSE /\ ffail = FALSE \* step 0: S is sealed (given) and claimed -Claim == step = "start" /\ slive /\ claim' = TRUE /\ step' = "c" +\* nc: the step is kept (S found, step counter) but takes no claim +Claim == step = "start" /\ slive /\ claim' = (~ NoClaim) /\ step' = "c" /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 1: fork (T HEAD names S's fids, all V-owned) \* r0.1: two steps. Between them T exists without a HEAD, so only the claim keeps S (and \* through S its fids) alive; that window is what the claim is for. +\* nc: ForkBegin reads S (requires S live) and records readAt; ForkEnd only within the deadline ForkBegin == step = "c" /\ step' = "fk" + /\ (NoClaim => slive) /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ readAt' = (IF NoClaim THEN now ELSE readAt) /\ UNCHANGED <> -ForkEnd == step = "fk" /\ thead' = VF /\ step' = "own" + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ DeadlineOK /\ thead' = VF /\ step' = "own" /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) /\ UNCHANGED <> + /\ UNCHANGED tvars +\* nc: past the deadline the fork fails cleanly: T stays without a HEAD, a retry is a new ForkBegin +ForkFail == NoClaim /\ step = "fk" /\ now >= readAt + D + /\ step' = "c" /\ readAt' = None /\ ffail' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> +\* nc: a (re)try that re-reads S and finds it gone ends with "not found" (terminal) +ForkNotFound == NoClaim /\ step = "c" /\ ~ slive /\ step' = "nf" + /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 3: one batch: upload own fids for up to Batch V-owned indexes (intent roots them) BatchSet == {B \in SUBSET VRefs : B # {} /\ Cardinality(B) <= Batch} @@ -96,6 +140,7 @@ Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] /\ up' = {TF[j] : j \in B} /\ UNCHANGED <> + /\ UNCHANGED tvars \* the batch HEAD CAS: swap exactly the uploaded indexes Cas == step = "own" /\ up # {} /\ thead' = [i \in Idx |-> IF TF[i] \in up THEN TF[i] ELSE thead[i]] @@ -103,50 +148,75 @@ Cas == step = "own" /\ up # {} /\ up' = {} /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) /\ UNCHANGED <> + /\ UNCHANGED tvars \* mutant: CAS a batch whose upload is not durable (the T fid is still "none") CasEarly(B) == CasBeforeUpload /\ step = "own" /\ up = {} /\ thead' = [i \in Idx |-> IF i \in B THEN TF[i] ELSE thead[i]] /\ UNCHANGED <> + /\ UNCHANGED tvars UploadLate == CasBeforeUpload /\ step = "own" /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" /\ store' = [store EXCEPT ![TF[i]] = "pres"] /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 4: marker after the last V ref is gone (and the final CAS is done), then drop the claim Marker == step = "own" /\ ~ marker /\ up = {} /\ (VRefs = {} \/ MarkerEarly \/ (MarkerBeforeCas /\ Cardinality(VRefs) <= Batch)) /\ marker' = TRUE /\ step' = "done" /\ localdone' = TRUE /\ UNCHANGED <> + /\ UNCHANGED tvars DropClaim == marker /\ claim /\ claim' = FALSE /\ UNCHANGED <> + /\ UNCHANGED tvars \* a snapshot of T: refused before the marker (unless the mutant allows it) SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) /\ tsnap' = THeadFids /\ UNCHANGED <> + /\ UNCHANGED tvars \* crash of the restore process; the new owner resumes from remote facts (thead, marker) +\* nc: a resume in the fork window (no HEAD) is a retry that re-reads S (back to "c", new +\* ForkBegin requires S live); mutant ~ResumeRereads: stays "fk" with a fresh deadline (readAt = now) +\* and the content read before the crash Crash == crashes < MaxCrash /\ step \in {"fk", "own", "done"} /\ up' = {} \* an unpublished batch is abandoned; its fids are collectable /\ step' = (IF ResumeLocal /\ localdone THEN "done" - ELSE IF marker THEN "done" ELSE IF thead = NoHead THEN "fk" ELSE "own") + ELSE IF marker THEN "done" + ELSE IF thead = NoHead THEN (IF (NoClaim /\ ResumeRereads) THEN "c" ELSE "fk") + ELSE "own") + /\ readAt' = (IF (NoClaim /\ thead = NoHead) THEN (IF ResumeRereads THEN None ELSE now) ELSE readAt) /\ crashes' = crashes + 1 /\ UNCHANGED <> + /\ UNCHANGED <> \* user deletes V; retention deletes S when nothing holds it DeleteV == vlive /\ vlive' = FALSE /\ UNCHANGED <> -DeleteS == slive /\ ~ SHeld /\ slive' = FALSE + /\ UNCHANGED tvars +\* nc: whenever S is live (SDeletable = slive); records delAt and whether a fork was in its window +DeleteS == SDeletable /\ slive' = FALSE + /\ delAt' = (IF NoClaim THEN now ELSE delAt) + /\ sdelfk' = (IF (NoClaim /\ step = "fk") THEN TRUE ELSE sdelfk) /\ UNCHANGED <> + /\ UNCHANGED <> \* GC (reduced machine E): deletes present fids no root reaches, and fids put on the list Gc == gcs < MaxGc /\ store' = [f \in Fids |-> IF store[f] = "pres" /\ (f \notin Roots \/ f \in gclist) THEN "del" ELSE store[f]] /\ gcs' = gcs + 1 /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* nc: time advances by one tick (never when NoClaim = FALSE) +Tick == NoClaim /\ now < MaxTick /\ now' = now + 1 + /\ UNCHANGED <> + /\ UNCHANGED <> Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + \/ ForkFail \/ ForkNotFound \/ Tick Spec == Init /\ [][Next]_vars @@ -163,11 +233,24 @@ ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim ClaimUntilHead_Inv == (step = "fk") => claim \* lifecycle independence: after the marker and the claim drop, nothing of T holds S LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* nc replacement of LifecycleFree: nothing ever holds S; S is deletable at every moment it lives +LifecycleFreeNC == NoClaim => (~ claim /\ (SDeletable = slive)) +\* nc frame check for old cfgs: with NoClaim = FALSE the new variables never move +OldFrame == (~ NoClaim) => (now = 0 /\ readAt = None /\ delAt = None /\ ~ sdelfk /\ ~ ffail) \* INV-RESTORE-STATE-REMOTE: "done" only when the remote marker exists StateRemote == step = "done" => marker -TypeOK == /\ step \in {"start", "c", "fk", "own", "done"} /\ up \subseteq Fids /\ tsnap \subseteq Fids +TypeOK == /\ step \in {"start", "c", "fk", "own", "done", "nf"} /\ up \subseteq Fids /\ tsnap \subseteq Fids + /\ now \in 0..MaxTick /\ readAt \in {None} \cup (0..MaxTick) /\ delAt \in {None} \cup (0..MaxTick) + /\ sdelfk \in BOOLEAN /\ ffail \in BOOLEAN \* witnesses (r0.1): each is an invariant expected to be VIOLATED, proving the state is reachable W_Done == ~ (marker /\ ~ claim /\ ~ slive /\ ~ vlive /\ \A i \in Idx : store[VF[i]] = "del") W_CrashResume == ~ (marker /\ crashes = MaxCrash) +\* nc witnesses: S deleted inside the fork window and the restore still completes, every block present, +\* every V fid physically gone +W_nc_DelInFork == ~ (sdelfk /\ marker /\ step = "done" /\ ~ vlive /\ ~ slive + /\ (\A i \in Idx : store[VF[i]] = "del") + /\ (\A i \in Idx : store[thead[i]] = "pres")) +\* nc witness: a fork failed on its deadline and a retry found S gone +W_nc_FailNotFound == ~ (ffail /\ step = "nf") ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg index 1ab2298c47..8102f6b6cf 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg @@ -14,12 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 0 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote - W_CrashResume diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg new file mode 100644 index 0000000000..5b319dceb8 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg new file mode 100644 index 0000000000..959c1e147f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg new file mode 100644 index 0000000000..dabec4a948 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg index 70a61b6cee..b398ea33a7 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg new file mode 100644 index 0000000000..d5a4f2f982 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg index 82592e7bc4..460f66230b 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg index 560a8c4cc7..088e125bd2 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg index 38b2ecc46a..de0c18acac 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg index b2ed698e1f..a9584e358a 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = TRUE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg index 383cbda367..a5690276cb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg index dce285726d..00961ba3fb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg new file mode 100644 index 0000000000..1d114c2163 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = FALSE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg new file mode 100644 index 0000000000..cd8b15a2c1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = FALSE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg new file mode 100644 index 0000000000..a623dd8f51 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg new file mode 100644 index 0000000000..fef3519c2c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg new file mode 100644 index 0000000000..24ee54e48a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg index bf269afeae..9b33687854 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg index 34c9db075b..c0c370f29e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg new file mode 100644 index 0000000000..79708ebd36 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_DelInFork diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg new file mode 100644 index 0000000000..74cc24ef9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_FailNotFound diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg similarity index 76% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg index 9590e854ad..ae5548a57e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,3 +29,4 @@ INVARIANTS ClaimUntilIndependent LifecycleFree StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg new file mode 100644 index 0000000000..33e1c88fdb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = TRUE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFree + StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg similarity index 78% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg index 3d9c60ac18..c4f0281674 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = TRUE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,4 +29,3 @@ INVARIANTS ClaimUntilHead_Inv LifecycleFree StateRemote - W_Done diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg similarity index 72% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg index 5dae146b29..6bd867a906 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv LifecycleFree StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg deleted file mode 100644 index 6c115a1f13..0000000000 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg +++ /dev/null @@ -1,24 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - NIdx = 3 - Batch = 1 - MaxCrash = 2 - MaxGc = 3 - DropClaimAtFork = FALSE - CasBeforeUpload = FALSE - ListForeign = FALSE - MarkerEarly = FALSE - MarkerBeforeCas = FALSE - ResumeLocal = FALSE - SnapDuringRestore = FALSE - RetentionIgnoresMarker = TRUE - ClaimUntilHead = FALSE - NoIntent = FALSE -INVARIANTS - TypeOK - NoGap - Independent - NoForeignList - ClaimUntilIndependent - LifecycleFree - StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg index 682ed72f1f..5327a664e4 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -12,13 +12,20 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv + ClaimUntilIndependent LifecycleFree StateRemote diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 02d7a1d468..25a61677d0 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -222,7 +222,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | | `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | | `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | -| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload | +| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload | | `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | | `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | | `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | @@ -275,6 +275,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | +| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). | +| `Volumes[].Chunk.Stats.COWSpillCapReason` | string | (group of `COWSpillCap`) COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). (omitted when empty) | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |