diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md index 15de39f911..bec2170b6d 100644 --- a/seaweed-block/.github/pull_request_template.md +++ b/seaweed-block/.github/pull_request_template.md @@ -1 +1,19 @@ -Machine / invariants (INV ids) / spec covered: +Feature: +Machine/INV: / +Model: +Red-first: +Simplest: + + diff --git a/seaweed-block/.github/scripts/spec-trace-check-test.sh b/seaweed-block/.github/scripts/spec-trace-check-test.sh new file mode 100644 index 0000000000..6b6128ff69 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check-test.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Self-test of the spec-trace check: PR descriptions and change lists against +# the exit code they must give. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +check=$here/spec-trace-check.sh +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +fail=0 + +# expect WANT_EXIT NAME BODY [STATUS PATH]... +expect() { + local want=$1 name=$2 body=$3 got=0 + shift 3 + printf '%s' "$body" >"$tmp/body" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} + +ok='Feature: O-SNAP-2 +Machine/INV: IMPL M5.Quiesce>Copy / INV-MAINT-ONE-OWNER +Model: docs/spec/MaintenanceOwner.tla, exhausted +Red-first: 7f542dbc TestMaintenanceHeldPass failed on base' +simplest='Simplest: one owner per volume on the existing cut path; no new machine.' + +expect 0 "all four lines, docs only" "$ok" M docs/a.md +expect 0 "FIX kind" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001}" +expect 0 "CHANGE kind" "${ok/IMPL M5.Quiesce>Copy/CHANGE M5}" +expect 0 "core change with Simplest" "$ok +$simplest" M core/storage/gc.go +expect 0 "core test only needs no Simplest" "$ok" M core/storage/gc_test.go +expect 0 "CRLF body" "$(printf '%s\n' "$ok" | sed 's/$/\r/')" +expect 0 "CHANGE of two machines" "${ok/IMPL M5.Quiesce>Copy/CHANGE M4, M6}" +expect 0 "list markers and bold keys" "$(printf '%s\n' "$ok" | sed "s/^Feature:/- **Feature:**/; s/^Model:/* Model:/")" +expect 0 "Model NONE with a reason" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: CI wiring only, no state}" + +expect 1 "empty body" "" +expect 1 "missing Red-first" "$(printf '%s\n' "$ok" | grep -v Red-first)" +expect 1 "short NONE" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: n/a}" +expect 1 "no kind" "${ok/IMPL M5.Quiesce>Copy/B,D,E}" +expect 1 "IMPL without transition" "${ok/IMPL M5.Quiesce>Copy/IMPL M5}" +expect 1 "NONE is not a kind" "${ok/IMPL M5.Quiesce>Copy \/ INV-MAINT-ONE-OWNER/NONE: tooling only, no machine}" +expect 1 "core file deleted without Simplest" "$ok" D core/storage/old.go +expect 1 "two kinds" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy FIX INV-MAINT-ONE-OWNER}" +expect 1 "second Machine/INV line with another kind" "$ok +Machine/INV: FIX INV-MAINT-ONE-OWNER" +expect 1 "second Machine/INV line in list and bold form" "$ok +- **Machine/INV:** CHANGE M5" +expect 1 "Simplest declared twice" "$ok +$simplest +$simplest" M core/storage/gc.go +expect 1 "kind token with a trailing junk" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001x}" +expect 1 "transition with a stray character" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy;x}" +expect 1 "key inside another word" "${ok/Feature: O-SNAP-2/Not-Feature: O-SNAP-2}" +expect 1 "placeholder left in Feature" "${ok/Feature: O-SNAP-2/Feature: }" +expect 1 "placeholder left in Red-first" "$(printf '%s\n' "$ok" | sed "s/^Red-first:.*/Red-first: /")" +expect 1 "placeholder left in Simplest" "$ok +Simplest: " M core/storage/gc.go +expect 1 "unfilled template" "$(cat "$here/../pull_request_template.md")" +expect 1 "core change without Simplest" "$ok" M core/storage/gc.go +expect 1 "cmd change, short Simplest" "$ok +Simplest: small" A cmd/sw-block/new.go + +# expect_raw WANT_EXIT NAME BYTES: a change list given as printf format. +expect_raw() { + local want=$1 name=$2 got=0 + printf "%s" "$ok" >"$tmp/body" + printf "$3" | bash "$check" "$tmp/body" >/dev/null 2>&1 || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +expect_raw 2 "record cut off before its NUL" "M\0core/storage/gc.go" +expect_raw 2 "status without a path" "M\0" +expect_raw 2 "status cut off before its NUL" "M\0docs/a.md\0M" +expect_raw 2 "unknown status" "R100\0core/a.go\0" +expect_raw 0 "well-formed docs change" "M\0docs/a.md\0" + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail diff --git a/seaweed-block/.github/scripts/spec-trace-check.sh b/seaweed-block/.github/scripts/spec-trace-check.sh new file mode 100644 index 0000000000..dac909ef10 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Usage: spec-trace-check.sh BODY_FILE < changes +# +# Checks the spec trace in a PR description. changes are NUL-separated +# STATUS, PATH pairs (post-merge-review-changed.sh). +# +# - Feature:, Machine/INV:, Model: and Red-first: each start a line (after +# optional indentation, a list marker or bold) and carry a value that is not +# a template placeholder; "NONE:" needs a reason of at least 10 characters. +# - Machine/INV: starts with exactly one PR kind: "IMPL .", +# "FIX " or "CHANGE ". NONE is not a kind. +# - Simplest: (20+ characters) is present when the PR adds, modifies or +# deletes non-test Go under core/ or cmd/. +# +# Prints every problem and exits 1 if there is one; exits 0 if none, 2 on a +# usage error or a malformed change list. +set -euo pipefail + +body_file=${1:?usage: spec-trace-check.sh BODY_FILE < changes} +[[ -f $body_file ]] || { echo "spec-trace: body file $body_file missing" >&2; exit 2; } +body=$(tr -d '\r' <"$body_file") + +# value KEY: the text after KEY on the first line that starts with KEY, +# trimmed. A key inside another word ("Not-Feature:") does not count. +value() { + local line + line=$(printf '%s\n' "$body" | grep -m1 -E "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$1" || true) + [[ -n $line ]] || return 0 + line=${line#*"$1"} + line=${line#\*\*} + line=${line#"${line%%[![:space:]]*}"} + printf '%s' "${line%"${line##*[![:space:]]}"}" +} + +bad=0 +problem() { echo "spec-trace: $1"; bad=1; } + +# Each trace line is declared once: a second Machine/INV line could carry a +# second kind past the check. +for key in Feature: Machine/INV: Model: Red-first: Simplest:; do + n=$(printf '%s\n' "$body" | grep -cE "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$key" || true) + ((n <= 1)) || problem "$key is declared $n times; declare it once" +done + +for key in Feature: Machine/INV: Model: Red-first:; do + v=$(value "$key") + if [[ -z $v ]]; then + problem "missing or empty $key" + elif [[ $v == '<'* ]]; then + problem "$key still holds the template placeholder" + elif [[ $v == NONE:* ]]; then + r=${v#NONE:} + r=${r#"${r%%[![:space:]]*}"} + ((${#r} >= 10)) || problem "$key NONE needs a reason of at least 10 characters" + fi +done + +# One kind token, ending at the line end, a space, a comma or a slash. +end='($|[[:space:],/])' +kind_re="^(IMPL [A-Za-z0-9_]+[.][A-Za-z0-9_>.-]+|FIX INV-[A-Z0-9]+(-[A-Z0-9]+)*|CHANGE [A-Za-z0-9_]+)$end" +mi=$(value Machine/INV:) +if [[ -n $mi && $mi != '<'* ]]; then + if [[ ! $mi =~ $kind_re ]]; then + problem "Machine/INV: must start with IMPL ., FIX or CHANGE " + elif [[ ${mi#"${BASH_REMATCH[0]}"} =~ (^|[^A-Za-z0-9_])(IMPL|FIX|CHANGE)([^A-Za-z0-9_]|$) ]]; then + problem "Machine/INV: names more than one kind; a PR is exactly one of IMPL, FIX or CHANGE" + fi +fi + +core=0 +while IFS= read -r -d '' status; do + [[ $status == [ADMT] ]] || { echo "spec-trace: malformed change list: status ${status@Q}" >&2; exit 2; } + IFS= read -r -d '' path || { echo "spec-trace: malformed change list: status $status without a path" >&2; exit 2; } + [[ -n $path ]] || { echo "spec-trace: malformed change list: empty path" >&2; exit 2; } + if [[ $path == core/*.go || $path == cmd/*.go ]] && [[ $path != *_test.go ]]; then + core=1 + fi +done +# A record cut off before its NUL is malformed, not skipped. +[[ -z ${status-} ]] || { echo "spec-trace: malformed change list: unterminated record" >&2; exit 2; } +if ((core)); then + s=$(value Simplest:) + if ((${#s} < 20)) || [[ $s == '<'* ]]; then + problem "Simplest: (20+ characters) is required when non-test Go under core/ or cmd/ changes" + fi +fi + +exit $bad diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml new file mode 100644 index 0000000000..d16c1e6978 --- /dev/null +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -0,0 +1,50 @@ +name: spec trace + +# Every PR description carries the spec trace (see the PR template); this +# check fails a PR whose description does not. +# +# pull_request_target: the workflow and the script come from the base branch, +# so a PR cannot change its own check. The PR's code is never checked out or +# run: only its commit is fetched, for the file list. The description is read +# from the event through an environment variable, never interpolated. +on: + pull_request_target: + # edited: the check reads the description and the base. + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: spec-trace-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + trace: + name: spec trace + # Same-repository PRs use the project's self-hosted runners, as the test + # workflow does; fork PRs stay on a GitHub-hosted runner, whose shared queue + # can wait for hours. No PR code runs here either way. + runs-on: ${{ github.event.pull_request.head.repo.full_name == github.repository && 'tp04-seaweed-block' || 'ubuntu-latest' }} + timeout-minutes: 5 + steps: + - name: Checkout base + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.pull_request.base.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Check spec trace + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + BODY: ${{ github.event.pull_request.body }} + run: | + set -euo pipefail + bash .github/scripts/spec-trace-check-test.sh + git fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" + printf '%s' "$BODY" >body.txt + bash .github/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin + bash .github/scripts/spec-trace-check.sh body.txt 0 && c.captureInterval < 5*time.Minute { + return errors.New("--chunk-capture-interval must be 0 or at least 5m") + } if c.captureInterval < 0 { return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) } @@ -106,14 +117,15 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. type chunkWiring struct { - remoteFor func(volumeID string) (storage.ChunkRemote, error) - catalog *chunkstore.Catalog - close func() error + remoteFor func(volumeID string) (storage.ChunkRemote, error) + catalog *chunkstore.Catalog + maintenance func(context.Context, string) error + close func() error } // newChunkWiring dials the filer and refuses unless it is the only filer of // its group (chunkstore.CheckSingleFiler). -func newChunkWiring(c chunkFlags) (chunkWiring, error) { +func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) { client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ FilerGRPC: c.filer, Collection: c.collection, @@ -133,7 +145,17 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) { _ = client.Close() return chunkWiring{}, err } + var masterAddr string + if len(master) > 0 { + masterAddr = master[0] + } + maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr) + if err != nil { + _ = client.Close() + return chunkWiring{}, err + } return chunkWiring{ + maintenance: maintenance, remoteFor: func(volumeID string) (storage.ChunkRemote, error) { root, err := chunkVolumeRoot(c.path, volumeID) if err != nil { @@ -142,7 +164,7 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) { return chunkstore.NewSWFSChunkRemote(client, root) }, catalog: cat, - close: client.Close, + close: func() error { return errors.Join(closeMaintenance(), client.Close()) }, }, nil } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 5bf1bfcdfb..c885307e7c 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -15,11 +15,11 @@ func TestWALStoreChunkFlags(t *testing.T) { return append(phase150RequiredBlockvolumeArgs(), extra...) } f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", - "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=30s")) + "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m")) if err != nil { t.Fatalf("walstore-chunk with a filer: %v", err) } - if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 30*time.Second || f.chunk.controlEndpoint { + if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint { t.Fatalf("parsed chunk flags = %+v", f.chunk) } f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", @@ -31,8 +31,8 @@ func TestWALStoreChunkFlags(t *testing.T) { if err != nil { t.Fatal(err) } - if d.chunk.captureInterval != 0 || d.chunk.dirtyThreshold != 512 { - t.Fatalf("scheduler defaults interval %s threshold %d, want timer off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold) + if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || d.chunk.dirtyThreshold != 512 { + t.Fatalf("scheduler defaults interval %s threshold %d, want capture 15m, maintenance 1h, GC off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold) } off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=0", "--chunk-dirty-threshold=0")) @@ -43,13 +43,15 @@ func TestWALStoreChunkFlags(t *testing.T) { t.Fatalf("walstore with the chunk defaults untouched: %v", err) } refused := map[string][]string{ - "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"), - "no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"), - "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), - "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), - "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), - "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), - "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), + "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"), + "no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"), + "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), + "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), + "below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"), + "negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"), + "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), + "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), + "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), "control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0", "--chunk-control-endpoint"), "control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ca2a80a683..394ef1d974 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,7 +203,9 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") - fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 15m, minimum 5m); 0 disables") + fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") + fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") @@ -658,8 +660,12 @@ func run(f flags) int { var chunkErr error var chunk chunkWiring if cfg.Impl == durable.ImplWALStoreChunk { - chunk, chunkErr = newChunkWiring(f.chunk) + chunk, chunkErr = newChunkWiring(f.chunk, f.masterAddr) cfg.ChunkCaptureInterval = f.chunk.captureInterval + cfg.ChunkCutTimeout = defaultChunkCutTimeout + cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval + cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout + cfg.ChunkMaintenance = chunk.maintenance cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency diff --git a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go index 92d2e90d13..2215732638 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go @@ -208,7 +208,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { if !first.MarkSaved || first.Reclaimed != 0 { t.Fatalf("first mark: %+v", first) } - now = now.Add(time.Hour + time.Second) + now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) preview = call(false) if preview.Reclaimed != 0 || len(preview.WouldDelete) != 1 || preview.WouldDelete[0].Key != "orphan" { t.Fatalf("mature preview: %+v", preview) @@ -278,7 +278,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { if expired.ExpiredIntents != 1 || expired.Reclaimed != 0 { t.Fatalf("fenced intent admission: %+v", expired) } - now = now.Add(time.Hour + time.Second) + now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) reclaimed := call(true) if reclaimed.Reclaimed != 1 || len(reclaimed.WouldDelete) != 1 || reclaimed.WouldDelete[0].Key != "held" { t.Fatalf("expired capture: %+v", reclaimed) diff --git a/seaweed-block/cmd/sw-block/chunk_gc_test.go b/seaweed-block/cmd/sw-block/chunk_gc_test.go index aaf158c4cf..c8d49708c0 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "errors" @@ -264,3 +265,20 @@ func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) { }) } } + +func TestOpsChunkGC_PermanentDeleteReportsFailureWithSavedCoverage(t *testing.T) { + var stdout, stderr bytes.Buffer + out := chunkstore.GCExecution{MarkOutcome: "complete", MarkSaved: true, GCResult: chunkstore.GCResult{ + Reclaimed: 1, FailedDeletes: []chunkstore.GCDeleteFailure{{GCObject: chunkstore.GCObject{Volume: "v1", Key: "bad", FID: "3,bad"}, Error: "http 400"}}, + }} + rc := chunkGCResult(out, chunkstore.ErrBlobDeleteRejected, &stdout, &stderr) + var body struct { + GC chunkstore.GCExecution `json:"gc"` + } + if err := json.Unmarshal(stdout.Bytes(), &body); err != nil { + t.Fatal(err) + } + if rc != 1 || !body.GC.MarkSaved || body.GC.MarkOutcome != "complete" || body.GC.Reclaimed != 1 || len(body.GC.FailedDeletes) != 1 || body.GC.FailedDeletes[0].FID != "3,bad" { + t.Fatalf("partial failure lost saved coverage or object identity: rc=%d body=%s", rc, stdout.String()) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 52633a9426..06f94c6ee8 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -83,7 +83,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld|workspace") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -128,6 +128,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsChunk(args[2:], stdout, stderr) case "volume-unheld": return runOpsVolumeUnheld(args[2:], stdout, stderr) + case "workspace": + return runOpsWorkspace(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2296,6 +2298,8 @@ func usage(w io.Writer) { 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 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`)") } func emptyCLI(value string) string { diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go new file mode 100644 index 0000000000..b1e7d1693f --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -0,0 +1,274 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "strings" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" +) + +// Exit codes of `sw-block ops workspace`. +const ( + wsExitOK = 0 + wsExitRefused = 1 // the master refused; nothing moved + wsExitRefusedLocally = 2 // bad usage or confirmation; no RPC was sent + wsExitUnknown = 3 // outcome unknown: rerun with the SAME --request-id + wsExitReadoutUnproven = 4 // move issued (or ranges exist) but the lost range is not proven + wsDefaultTimeout = 30 * time.Second + workspaceForceMoveName = "sw-block ops workspace force-move" + workspaceLostRangeName = "sw-block ops workspace lost-range" +) + +const workspaceUsage = `usage: + sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A + --request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s] + sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s] + +force-move FORCES an RF1 workspace volume's authority off a holder that is gone, +abandoning what it wrote after the last published HEAD. It moves AUTHORITY only: +starting the volume on the target host is the next step, done separately. The +blockmaster admits it only once the holder's lease horizon and its granted or +restart deadline, each plus the clock-skew bound, have passed; before that it is +refused and this command says when it becomes admissible. There is NO bypass +flag. Clean (detached) moves are not offered here. + +--confirm-forced must be exactly @, retyped: the epoch +is the holder's epoch the move is sent against, and the master refuses it when +that is no longer current. --dry-run asks the master for an advisory preview +(nothing is written; admission is re-checked at the move); it is never a +confirmation. The lost range is stored before the move is issued and printed +from that record; the authority store and its lost-range files stay off the +volume hosts (layout rule). + +lost-range prints the stored lost ranges of the volume's issued forced moves, in +issue order (all of them, or the one of --request-id). It never prints "no loss" +for a forced move whose record is missing or fails its checks. + +exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage +or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME +--request-id; 4 the move is issued but its lost range is not proven (or a +stored range is unreadable). +` + +// workspaceDial is swapped by tests. +var workspaceDial = wsclient.Dial + +// runOpsWorkspace is `sw-block ops workspace`. +func runOpsWorkspace(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + fmt.Fprint(stderr, workspaceUsage) + return wsExitRefusedLocally + } + switch args[0] { + case "force-move": + return runWorkspaceForceMove(args[1:], stdout, stderr) + case "lost-range": + return runWorkspaceLostRange(args[1:], stdout, stderr) + case "-h", "--help", "help": + fmt.Fprint(stdout, workspaceUsage) + return wsExitOK + default: + fmt.Fprintf(stderr, "sw-block ops workspace: unknown subcommand %q\n", args[0]) + fmt.Fprint(stderr, workspaceUsage) + return wsExitRefusedLocally + } +} + +func workspaceExit(o wsclient.Outcome) int { + switch o { + case wsclient.OutcomeOK: + return wsExitOK + case wsclient.OutcomeRefusedLocally: + return wsExitRefusedLocally + case wsclient.OutcomeRefused: + return wsExitRefused + case wsclient.OutcomeReadoutUnproven: + return wsExitReadoutUnproven + } + return wsExitUnknown +} + +func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(workspaceForceMoveName, flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) } + var m wsclient.ForcedMove + var master string + var dryRun bool + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&m.VolumeID, "volume", "", "volume id") + fs.StringVar(&m.TargetHost, "target-host", "", "target node server id") + fs.StringVar(&m.TargetDataAddr, "target-data", "", "target data address host:port") + fs.StringVar(&m.TargetCtrlAddr, "target-ctrl", "", "target control address host:port") + fs.StringVar(&m.RequestID, "request-id", "", "this move's id; a rerun with the same id returns the stored grant") + fs.StringVar(&m.Confirm, "confirm-forced", "", "exactly @") + fs.BoolVar(&dryRun, "dry-run", false, "advisory preview only; writes nothing") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPCs") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || m.VolumeID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" || m.RequestID == "" || timeout <= 0 { + fmt.Fprintf(stderr, "%s: --master, --volume, --target-host, --target-data, --target-ctrl, --request-id and --confirm-forced are required (refused locally; nothing sent)\n", workspaceForceMoveName) + return wsExitRefusedLocally + } + // Row Parse -> Refused: checked before any connection or RPC. + if _, err := wsclient.ParseConfirmation(m.Confirm, m.VolumeID); err != nil { + fmt.Fprintf(stderr, "%s: refused locally, nothing sent: %v\n", workspaceForceMoveName, err) + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if dryRun { + return workspacePreview(ctx, c, m, stdout, stderr) + } + g, err := c.ForceMove(ctx, m) + switch o := wsclient.OutcomeOf(err); o { + case wsclient.OutcomeOK: + printForcedGrant(stdout, g) + fmt.Fprintln(stdout, wsclient.Readout(m.VolumeID, g.GetLostRange())) + fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", m.VolumeID, g.GetNewHost()) + return wsExitOK + case wsclient.OutcomeReadoutUnproven: + if g != nil { + printForcedGrant(stdout, g) + } + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + fmt.Fprintf(stderr, "%s: the move IS issued; do not assume no loss. Check the master's load errors, and read the range with:\n", workspaceForceMoveName) + fmt.Fprintf(stderr, "%s%s\n", workspaceRecoveryPrefix, shellCommand("sw-block", "ops", "workspace", "lost-range", "--master", master, "--volume", m.VolumeID, "--request-id", m.RequestID)) + return wsExitReadoutUnproven + case wsclient.OutcomeRefused: + fmt.Fprintf(stderr, "%s: refused by the master (nothing moved): %v\n", workspaceForceMoveName, err) + if at, ok := c.AdmissibleAt(ctx, m); ok { + fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano())) + } + return wsExitRefused + case wsclient.OutcomeUnknown: + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID) + return wsExitUnknown + default: + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + return workspaceExit(o) + } +} + +// workspaceRecoveryPrefix starts the line that carries a recovery command. +const workspaceRecoveryPrefix = " " + +// shellCommand joins args for a POSIX shell, single-quoting any argument +// that is not plainly safe, so a printed command can be pasted as is. +func shellCommand(args ...string) string { + out := make([]string, len(args)) + for i, a := range args { + out[i] = shellQuote(a) + } + return strings.Join(out, " ") +} + +func shellQuote(a string) string { + if a != "" && strings.Trim(a, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" { + return a + } + return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'" +} + +func printForcedGrant(w io.Writer, g *control.WorkspaceGrant) { + fmt.Fprintf(w, "forced move issued: volume %s request %s: %s@%d on %s -> %s@%d on %s (kept HEAD gen %d, remote LSN %d)\n", + g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetOldHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn()) +} + +// workspacePreview is the --dry-run row: advisory, writes nothing, exit 0 +// whatever the answer (a failed preview call is reported by its outcome). +func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.ForcedMove, stdout, stderr io.Writer) int { + p, err := c.PreviewForcedMove(ctx, m) + if err != nil { + fmt.Fprintf(stderr, "%s --dry-run: %v\n", workspaceForceMoveName, err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { + fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName) + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + verdict := "not admitted" + if p.GetAdmitted() { + verdict = "admitted" + } + fmt.Fprintf(stdout, "preview (advisory): at master time %s, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.\n", wsclient.FormatTime(p.GetMasterTimeNs())) + if p.GetReason() != "" { + fmt.Fprintf(stdout, "forced move %s: %s\n", verdict, p.GetReason()) + } else { + fmt.Fprintf(stdout, "forced move %s\n", verdict) + } + if !p.GetAdmitted() && p.GetLostUntilNs() > p.GetMasterTimeNs() { + fmt.Fprintf(stdout, "admissible at %s, master clock\n", wsclient.FormatTime(p.GetLostUntilNs())) + } + if p.GetHeadRead() { + at := "unknown" + if p.GetHeadTimeKnown() { + at = wsclient.FormatTime(p.GetHeadTimeNs()) + " " + wsclient.HeadTimeClock + } + fmt.Fprintf(stdout, "HEAD now: gen %d, epoch %d, holder %s, remote LSN %d, published at %s\n", p.GetHeadGen(), p.GetHeadEpoch(), p.GetHeadHolder(), p.GetHeadRemoteLsn(), at) + if p.GetAdmitted() { + fmt.Fprintf(stdout, "if moved now: writes with LSN <= %d are kept; writes acknowledged after that and before %s, master clock, may be lost\n", p.GetHeadRemoteLsn(), wsclient.FormatTime(p.GetLostUntilNs())) + } + } else if p.GetHeadError() != "" { + fmt.Fprintf(stdout, "HEAD read failed: %s\n", p.GetHeadError()) + } + return wsExitOK +} + +func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(workspaceLostRangeName, flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) } + var master, volume, requestID string + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&volume, "volume", "", "volume id") + fs.StringVar(&requestID, "request-id", "", "only this forced move's range (default: all, in issue order)") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || volume == "" || timeout <= 0 { + fmt.Fprintf(stderr, "%s: --master and --volume are required\n", workspaceLostRangeName) + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + ranges, err := c.LostRanges(ctx, volume, requestID) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", workspaceLostRangeName, err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven { + fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName) + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + if len(ranges) == 0 { + fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume) + return wsExitOK + } + for i, r := range ranges { + fmt.Fprintf(stdout, "range %d of %d: request %s, %s@%d -> epoch %d, lost after LSN %d, until %s (master clock)\n", + i+1, len(ranges), r.GetRequestId(), r.GetOldReplicaId(), r.GetOldEpoch(), r.GetNewEpoch(), r.GetLostAfterLsn(), wsclient.FormatTime(r.GetLostUntilNs())) + fmt.Fprintf(stdout, " %s\n", wsclient.Readout(volume, r)) + } + return wsExitOK +} diff --git a/seaweed-block/cmd/sw-block/workspace_master_test.go b/seaweed-block/cmd/sw-block/workspace_master_test.go new file mode 100644 index 0000000000..d7c594913b --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_master_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// seedForcedVolume makes r1 on node-a the holder of vol-f at epoch 1 (lease +// renewed once) with a prepared target binding on node-b. +func seedForcedVolume(t *testing.T, h *master.Host) { + t.Helper() + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + for _, server := range []string{"node-a", "node-b"} { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}, + {VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(3 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); ok && line.Epoch == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("no authority line for vol-f") + } + } + if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil { + t.Fatal(err) + } +} + +// The CLI against a real master: before the horizon the move is refused +// (exit 1) with when it becomes admissible, and the dry run writes nothing; +// after it the move is issued with the readout of the stored range; a rerun +// with the same request id prints the same; lost-range prints that range; +// after a restart with the range file damaged a rerun exits 4 (issued, +// readout unproven) and lost-range exits 4. A confirmation at another epoch +// is refused by the master's state (exit 1); a malformed one never leaves +// the CLI (exit 2). +func TestWorkspaceForceMoveAgainstRealMaster(t *testing.T) { + headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + authDir := t.TempDir() + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil + }} + h, stop := startDeleteMaster(t, cfg) + stopped := false + defer func() { + if !stopped { + stop() + } + }() + seedForcedVolume(t, h) + args := func(extra ...string) []string { + return append([]string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1"}, extra...) + } + + if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1x")); code != wsExitRefusedLocally { + t.Fatalf("malformed confirmation: exit %d %s", code, errOut) + } + if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@2")); code != wsExitRefused || !strings.Contains(errOut, "no holder of volume") { + t.Fatalf("confirmation at another epoch: exit %d %s", code, errOut) + } + code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1")) + if code != wsExitRefused || !strings.Contains(errOut, "has not elapsed") || !strings.Contains(errOut, "admissible at ") { + t.Fatalf("before the horizon: exit %d %s", code, errOut) + } + code, out, _ := runCLI(args("--confirm-forced", "vol-f@1", "--dry-run")) + if code != wsExitOK || !strings.Contains(out, "forced move not admitted") || !strings.Contains(out, "admissible at ") { + t.Fatalf("dry run before the horizon: exit %d\n%s", code, out) + } + if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { + t.Fatalf("refusal or dry run wrote a journal record: %+v", st.Moves) + } + + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + code, out, errOut = runCLI(args("--confirm-forced", "vol-f@1")) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b (kept HEAD gen 9, remote LSN 42)\n") || + !strings.Contains(out, "volume vol-f restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; writes acknowledged by r1@1 after that and before ") { + t.Fatalf("forced move: exit %d stderr %s\n%s", code, errOut, out) + } + code2, out2, _ := runCLI(args("--confirm-forced", "vol-f@1")) + if code2 != wsExitOK || out2 != out { + t.Fatalf("rerun with the same request id: exit %d\n%s\nwant\n%s", code2, out2, out) + } + readout := strings.Split(out, "\n")[1] + code, lr, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", h.Addr(), "--volume", "vol-f"}) + if code != wsExitOK || !strings.HasPrefix(lr, "range 1 of 1: request force-1, r1@1 -> epoch 2, lost after LSN 42") || !strings.Contains(lr, " "+readout+"\n") { + t.Fatalf("lost-range: exit %d\n%s\nwant readout %s", code, lr, readout) + } + + stop() + stopped = true + var files []string + _ = filepath.WalkDir(authDir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") { + files = append(files, p) + } + return err + }) + if len(files) != 1 { + t.Fatalf("lost range files %v", files) + } + raw, err := os.ReadFile(files[0]) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil { + t.Fatal(err) + } + h2, stop2 := startDeleteMaster(t, cfg) + defer stop2() + args2 := func(extra ...string) []string { + a := args(extra...) + a[4] = h2.Addr() + return a + } + code, out, errOut = runCLI(args2("--confirm-forced", "vol-f@1")) + if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1") || strings.Contains(out, "restored to") || !strings.Contains(errOut, "not proven") { + t.Fatalf("rerun with a damaged range: exit %d stdout %q stderr %s", code, out, errOut) + } + if code, _, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", h2.Addr(), "--volume", "vol-f"}); code != wsExitReadoutUnproven { + t.Fatalf("lost-range with a damaged range: exit %d %s", code, errOut) + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_postissue_test.go b/seaweed-block/cmd/sw-block/workspace_postissue_test.go new file mode 100644 index 0000000000..0be23f3bdc --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_postissue_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "bytes" + "context" + "log" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" +) + +type lockedLog struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +// A failure AFTER the forced move is issued (here the binding +// reconciliation, made to fail by moving the binding store's directory away) +// is reported through the RPC, the client and the CLI as an unknown outcome +// with the same-request-id recovery, never as a refusal ("nothing moved") +// and never with a fresh request id; the master's audit log records the +// issue; a rerun with the same id then returns the stored grant. +func TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome(t *testing.T) { + logs := &lockedLog{} + lifecycleDir := t.TempDir() + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil + }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolume(t, h) + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + bindings := filepath.Join(lifecycleDir, "workspace-bindings") + if err := os.Rename(bindings, bindings+".aside"); err != nil { + t.Fatal(err) + } + args := []string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"} + code, out, errOut := runCLI(args) + if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); !ok || line.Epoch != 2 { + t.Fatalf("fixture: the forced move was not issued before the failure: %+v", line) + } + if code != wsExitUnknown || strings.Contains(errOut, "nothing moved") || strings.Contains(out, "nothing moved") || + !strings.Contains(errOut, "rerun with the SAME --request-id force-1") || strings.Contains(strings.ToLower(errOut), "new request id") { + t.Fatalf("post-issue failure: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", code, out, errOut) + } + if !strings.Contains(logs.String(), `forced move issued volume="vol-f" request="force-1"`) { + t.Fatalf("issued forced move missing from the audit log:\n%s", logs.String()) + } + if err := os.Rename(bindings+".aside", bindings); err != nil { + t.Fatal(err) + } + code, out, errOut = runCLI(args) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") { + t.Fatalf("rerun with the same id: exit %d stdout %q stderr %s", code, out, errOut) + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_test.go b/seaweed-block/cmd/sw-block/workspace_test.go new file mode 100644 index 0000000000..31b73cceb9 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_test.go @@ -0,0 +1,450 @@ +package main + +import ( + "bytes" + "context" + "net" + "strings" + "sync" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// fakeWorkspace is a workspace service with canned answers that records +// every call. +type fakeWorkspace struct { + control.UnimplementedWorkspaceServiceServer + mu sync.Mutex + calls map[string]int + moves []*control.WorkspaceMove + status *control.WorkspaceStatus + move func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) + preview *control.WorkspaceMovePreview + ranges []*control.WorkspaceLostRange + rangeErr error + lastLR *control.WorkspaceLostRangeQuery +} + +func (f *fakeWorkspace) count(m string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.calls == nil { + f.calls = map[string]int{} + } + f.calls[m]++ +} + +func (f *fakeWorkspace) n(m string) int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls[m] +} + +func (f *fakeWorkspace) total() int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, c := range f.calls { + n += c + } + return n +} + +func (f *fakeWorkspace) QueryWorkspace(context.Context, *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { + f.count("QueryWorkspace") + return f.status, nil +} + +func (f *fakeWorkspace) MoveWorkspace(_ context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + f.count("MoveWorkspace") + f.mu.Lock() + f.moves = append(f.moves, q) + f.mu.Unlock() + return f.move(q) +} + +func (f *fakeWorkspace) PreviewWorkspaceMove(context.Context, *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + f.count("PreviewWorkspaceMove") + if f.preview == nil { + return nil, status.Error(codes.Unavailable, "no preview") + } + return f.preview, nil +} + +func (f *fakeWorkspace) QueryWorkspaceLostRange(_ context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) { + f.count("QueryWorkspaceLostRange") + f.mu.Lock() + f.lastLR = q + f.mu.Unlock() + if f.rangeErr != nil { + return nil, f.rangeErr + } + return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil +} + +// startFakeWorkspace serves f; dials counts the CLI's connections. +func startFakeWorkspace(t *testing.T, f *fakeWorkspace) (addr string, dials *int) { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterWorkspaceServiceServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + n := 0 + prev := workspaceDial + workspaceDial = func(a string) (*wsclient.Client, error) { n++; return wsclient.Dial(a) } + t.Cleanup(func() { workspaceDial = prev }) + return lis.Addr().String(), &n +} + +var ( + wsHeadTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + wsLostUntil = time.Date(2026, 11, 21, 1, 5, 0, 0, time.UTC) +) + +func wsHolder() *control.WorkspaceStatus { + return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}} +} + +func wsGrant(q *control.WorkspaceMove) *control.WorkspaceGrant { + return &control.WorkspaceGrant{RequestId: q.RequestId, VolumeId: q.VolumeId, OldReplicaId: q.ExpectedReplicaId, NewReplicaId: q.TargetReplicaId, Kind: "forced", + OldEpoch: q.ExpectedEpoch, NewEpoch: q.ExpectedEpoch + 1, HeadGen: 9, RemoteLsn: 42, Issued: true, OldHost: "node-a", NewHost: q.TargetServerId, + LostRange: &control.WorkspaceLostRange{RequestId: q.RequestId, VolumeId: q.VolumeId, NewEpoch: q.ExpectedEpoch + 1, OldReplicaId: q.ExpectedReplicaId, OldEpoch: q.ExpectedEpoch, + LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true}} +} + +const wsReadout = "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00Z, master clock, may be lost; the upper bound is a time, not an LSN." + +func forceMoveArgs(addr string, extra ...string) []string { + return append([]string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol", "--target-host", "node-b", "--target-data", "10.0.0.2:3260", + "--target-ctrl", "10.0.0.2:9100", "--request-id", "req-1"}, extra...) +} + +func runCLI(args []string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(args, &out, &errOut) + return code, out.String(), errOut.String() +} + +// Row Parse -> Refused (INV-WS-FORCED-CONFIRM-001): a confirmation that is +// absent or not exactly @ exits 2 with no +// connection and no RPC. +func TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }} + addr, dials := startFakeWorkspace(t, f) + for _, extra := range [][]string{nil, {"--confirm-forced", "other@3"}, {"--confirm-forced", "vol"}, {"--confirm-forced", "vol@x"}, {"--confirm-forced", "vol@0"}, + {"--confirm-forced", "vol@3", "--force"}, {"--dry-run"}} { + code, out, errOut := runCLI(forceMoveArgs(addr, extra...)) + if code != wsExitRefusedLocally || out != "" { + t.Fatalf("%v: exit %d stdout %q; want 2 and nothing", extra, code, out) + } + if len(extra) > 0 && extra[len(extra)-1] != "--force" && !strings.Contains(errOut, "refused locally") { + t.Fatalf("%v: stderr %q", extra, errOut) + } + } + if *dials != 0 || f.total() != 0 { + t.Fatalf("refused locally after %d dials and %d RPCs", *dials, f.total()) + } +} + +// Row Parse -> Preview: --dry-run calls only the preview, writes nothing, +// labels the answer advisory, says when a refused move becomes admissible, +// and exits 0 whatever the answer. +func TestWorkspaceForceMove_Row2_DryRunPreview(t *testing.T) { + master := time.Date(2026, 11, 21, 1, 4, 0, 0, time.UTC) + f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { panic("dry run moved") }, + preview: &control.WorkspaceMovePreview{Reason: "workspace forced move lease expiry plus clock-skew margin has not elapsed", LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: master.UnixNano()}} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run")) + if code != wsExitOK || f.n("MoveWorkspace") != 0 || f.n("PreviewWorkspaceMove") != 1 { + t.Fatalf("exit %d, %v; stderr %s", code, f.calls, errOut) + } + for _, s := range []string{"preview (advisory): at master time 2026-11-21T01:04:00Z, may change; admission is re-checked at the move", "this is not a confirmation", + "forced move not admitted: workspace forced move lease expiry", "admissible at 2026-11-21T01:05:00Z, master clock"} { + if !strings.Contains(out, s) { + t.Fatalf("stdout lacks %q:\n%s", s, out) + } + } + f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano(), + HeadRead: true, HeadGen: 9, HeadEpoch: 3, HeadHolder: "node-a/r1", HeadRemoteLsn: 42, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true} + code, out, _ = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run")) + if code != wsExitOK || f.n("MoveWorkspace") != 0 || strings.Contains(out, "admissible at") || + !strings.Contains(out, "forced move admitted") || !strings.Contains(out, "HEAD now: gen 9, epoch 3, holder node-a/r1, remote LSN 42, published at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution)") { + t.Fatalf("admitted preview: exit %d\n%s", code, out) + } +} + +// Rows Parse -> Sent and Sent -> Granted: the move is sent as kind forced, +// force true, at the confirmed epoch with the request id; the grant and the +// readout from its stored range are printed, with the next step. +func TestWorkspaceForceMove_Row3and4_SentAndGranted(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitOK || errOut != "" { + t.Fatalf("exit %d stderr %s", code, errOut) + } + q := f.moves[0] + if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" || + q.VolumeId != "vol" || q.TargetServerId != "node-b" || q.TargetDataAddr != "10.0.0.2:3260" || q.TargetCtrlAddr != "10.0.0.2:9100" { + t.Fatalf("sent %+v", f.moves) + } + want := "forced move issued: volume vol request req-1: r1@3 on node-a -> r1@4 on node-b (kept HEAD gen 9, remote LSN 42)\n" + wsReadout + "\n" + + "next: start volume vol on node-b (this command moved authority only)\n" + if out != want { + t.Fatalf("stdout\n got %q\nwant %q", out, want) + } +} + +// Row Sent -> Refused: a FailedPrecondition prints the master's reason and, +// before the horizon, when the move becomes admissible; exit 1. +func TestWorkspaceForceMove_Row5_MasterRefusal(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + return nil, status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed") + }, preview: &control.WorkspaceMovePreview{LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(-time.Minute).UnixNano()}} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitRefused || out != "" || !strings.Contains(errOut, "refused by the master (nothing moved)") || !strings.Contains(errOut, "has not elapsed") || + !strings.Contains(errOut, "admissible at 2026-11-21T01:05:00Z, master clock") || !strings.Contains(errOut, "there is no bypass") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + // Past the horizon (refused for another reason) no time is promised. + f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano()} + if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitRefused || strings.Contains(errOut, "admissible at") { + t.Fatalf("exit %d stderr %s", code, errOut) + } + // A confirmation at an epoch the master never had is refused before the move. + moves := f.n("MoveWorkspace") + if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@7")); code != wsExitRefused || f.n("MoveWorkspace") != moves || !strings.Contains(errOut, "no holder of volume") { + t.Fatalf("stale epoch: exit %d stderr %s", code, errOut) + } +} + +// Row Sent -> Unknown: a transport error or the deadline leaves the outcome +// unknown; exit 3 with "rerun with the SAME --request-id". +func TestWorkspaceForceMove_Row6_OutcomeUnknown(t *testing.T) { + for name, move := range map[string]func(*control.WorkspaceMove) (*control.WorkspaceGrant, error){ + "unavailable": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + return nil, status.Error(codes.Unavailable, "connection reset") + }, + "deadline": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + time.Sleep(2 * time.Second) + return nil, status.Error(codes.Unavailable, "late") + }, + } { + t.Run(name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: move} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--timeout", "500ms")) + if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "outcome unknown: rerun with the SAME --request-id req-1") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + }) + } +} + +// Row Granted -> LostMissing: an issued forced grant without its stored +// range (or with another move's) exits 4: the move is issued, the readout is +// not proven, and "no loss" is never printed. lost-range with a missing or +// corrupt record (DataLoss) exits 4 too. +func TestWorkspaceForceMove_Row7_ReadoutUnproven(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.LostRange, g.LostRangeError = nil, "workspace lost range missing or unreadable: forced move \"req-1\" has no loaded lost range record" + return g, nil + }, rangeErr: status.Error(codes.DataLoss, "workspace lost range missing or unreadable")} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol request req-1") || strings.Contains(out, "restored to") || + !strings.Contains(errOut, "lost range is not proven") || !strings.Contains(errOut, "the move IS issued; do not assume no loss") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + code, out, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}) + if code != wsExitReadoutUnproven || out != "" || !strings.Contains(errOut, "NOT proven") { + t.Fatalf("lost-range: exit %d stdout %q stderr %s", code, out, errOut) + } +} + +// splitShellWords splits a POSIX shell line of plain words and +// single-quoted parts and backslash escapes (the forms shellCommand prints). +func splitShellWords(t *testing.T, line string) []string { + t.Helper() + var words []string + var cur strings.Builder + in, quoted, inQuote, escaped := false, false, false, false + for _, r := range line { + switch { + case escaped: + cur.WriteRune(r) + escaped, in = false, true + case inQuote && r == '\'': + inQuote = false + case inQuote: + cur.WriteRune(r) + case r == '\'': + inQuote, in, quoted = true, true, true + case r == '\\': + escaped = true + case r == ' ': + if in { + words = append(words, cur.String()) + cur.Reset() + in, quoted = false, false + } + default: + cur.WriteRune(r) + in = true + } + } + if inQuote { + t.Fatalf("unterminated quote in %q", line) + } + if in || quoted { + words = append(words, cur.String()) + } + return words +} + +// The exit-4 recovery command carries the master address and survives +// arguments that need quoting: the printed words parse back to the same +// values and run as a lost-range command against the same master. +func TestWorkspaceForceMoveRecoveryCommandRuns(t *testing.T) { + const reqID = "req 1'$x" + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.LostRange, g.LostRangeError = nil, "missing" + return g, nil + }, ranges: nil} + addr, _ := startFakeWorkspace(t, f) + args := forceMoveArgs(addr, "--confirm-forced", "vol@3") + args[len(args)-3] = reqID // --request-id value + code, _, errOut := runCLI(args) + if code != wsExitReadoutUnproven { + t.Fatalf("exit %d %s", code, errOut) + } + var line string + for _, l := range strings.Split(errOut, "\n") { + if strings.HasPrefix(l, workspaceRecoveryPrefix+"sw-block ") { + line = strings.TrimPrefix(l, workspaceRecoveryPrefix) + } + } + words := splitShellWords(t, line) + want := []string{"sw-block", "ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", reqID} + if strings.Join(words, "\x00") != strings.Join(want, "\x00") { + t.Fatalf("recovery command %q parses to %q; want %q", line, words, want) + } + f.ranges = []*control.WorkspaceLostRange{{RequestId: reqID, VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9}} + if code, out, errOut := runCLI(words[1:]); code != wsExitOK || f.lastLR.RequestId != reqID || f.lastLR.VolumeId != "vol" || !strings.Contains(out, "range 1 of 1") { + t.Fatalf("recovery command run: exit %d %+v stdout %q stderr %s", code, f.lastLR, out, errOut) + } +} + +// A successful answer that does not match the request (here the target) +// is an unknown outcome, and one whose range disagrees with the kept HEAD +// is unproven: neither prints the preservation readout. +func TestWorkspaceForceMoveRejectsAMismatchedAnswer(t *testing.T) { + for name, tc := range map[string]struct { + fault func(*control.WorkspaceGrant) + exit int + }{ + "grant target": {func(g *control.WorkspaceGrant) { g.NewHost = "node-c" }, wsExitUnknown}, + "grant epoch": {func(g *control.WorkspaceGrant) { g.OldEpoch = 2 }, wsExitUnknown}, + "range volume": {func(g *control.WorkspaceGrant) { g.LostRange.VolumeId = "vol2" }, wsExitReadoutUnproven}, + "range frontier": {func(g *control.WorkspaceGrant) { g.LostRange.LostAfterLsn = 41 }, wsExitReadoutUnproven}, + "range head gen": {func(g *control.WorkspaceGrant) { g.LostRange.HeadGen = 8 }, wsExitReadoutUnproven}, + } { + t.Run(name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + tc.fault(g) + return g, nil + }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != tc.exit || strings.Contains(out, "restored to") || strings.Contains(out, "next: start") { + t.Fatalf("exit %d (want %d) stdout %q stderr %s", code, tc.exit, out, errOut) + } + if tc.exit == wsExitUnknown && !strings.Contains(errOut, "rerun with the SAME --request-id req-1") { + t.Fatalf("no same-id recovery: %s", errOut) + } + }) + } +} + +// Row Rerun same id -> Granted: the master replays the stored grant, and +// the output is the same, from the stored range. +func TestWorkspaceForceMove_Row8_RerunSameRequestID(t *testing.T) { + stored := map[string]*control.WorkspaceGrant{} + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if g, ok := stored[q.RequestId]; ok { + return g, nil + } + stored[q.RequestId] = wsGrant(q) + return nil, status.Error(codes.Unavailable, "reply lost") + }} + addr, _ := startFakeWorkspace(t, f) + if code, _, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitUnknown { + t.Fatalf("first run: exit %d; want unknown", code) + } + code, out, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + code2, out2, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitOK || code2 != wsExitOK || out != out2 || !strings.Contains(out, wsReadout) { + t.Fatalf("reruns: exit %d/%d\n%s\n%s", code, code2, out, out2) + } + if len(f.moves) != 3 || f.moves[0].RequestId != f.moves[2].RequestId { + t.Fatalf("moves %+v", f.moves) + } +} + +// lost-range lists every stored range in issue order (or the one of +// --request-id), each with its readout; a volume without forced moves says +// so. +func TestWorkspaceLostRangeListsAllInOrder(t *testing.T) { + q := &control.WorkspaceMove{RequestId: "req-1", VolumeId: "vol", ExpectedReplicaId: "r1", TargetReplicaId: "r1", ExpectedEpoch: 3} + first := wsGrant(q).LostRange + second := &control.WorkspaceLostRange{RequestId: "req-2", VolumeId: "vol", NewEpoch: 5, OldReplicaId: "r1", OldEpoch: 4, LostAfterLsn: 42, + LostUntilNs: wsLostUntil.Add(time.Minute).UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true} + f := &fakeWorkspace{ranges: []*control.WorkspaceLostRange{first, second}} + addr, _ := startFakeWorkspace(t, f) + code, out, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}) + i1, i2 := strings.Index(out, "range 1 of 2: request req-1, r1@3 -> epoch 4"), strings.Index(out, "range 2 of 2: request req-2, r1@4 -> epoch 5") + if code != wsExitOK || i1 < 0 || i2 < i1 || !strings.Contains(out, " "+wsReadout+"\n") || !strings.Contains(out, "acknowledged by r1@4 after that and before 2026-11-21T01:06:00Z") { + t.Fatalf("exit %d\n%s", code, out) + } + if f.lastLR.RequestId != "" { + t.Fatalf("listed with request id %q", f.lastLR.RequestId) + } + f.ranges = []*control.WorkspaceLostRange{second} + if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "req-2"}); code != wsExitOK || f.lastLR.RequestId != "req-2" || !strings.Contains(out, "range 1 of 1: request req-2") { + t.Fatalf("by request id: exit %d %+v\n%s", code, f.lastLR, out) + } + f.ranges = nil + if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}); code != wsExitOK || out != "volume vol has no issued forced move\n" { + t.Fatalf("none: exit %d %q", code, out) + } + f.rangeErr = status.Error(codes.NotFound, "no issued forced move with that request id") + if code, _, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "x"}); code != wsExitRefused { + t.Fatalf("unknown request id: exit %d", code) + } +} + +// The help says authority only, the next step, and that no bypass exists. +func TestWorkspaceHelpText(t *testing.T) { + code, out, _ := runCLI([]string{"ops", "workspace", "help"}) + out = strings.Join(strings.Fields(out), " ") + for _, s := range []string{"AUTHORITY only", "starting the volume on the target host is the next step", "There is NO bypass", "never a confirmation", "@"} { + if code != wsExitOK || !strings.Contains(out, s) { + t.Fatalf("help lacks %q:\n%s", s, out) + } + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_uncertain_test.go b/seaweed-block/cmd/sw-block/workspace_uncertain_test.go new file mode 100644 index 0000000000..d4e2c96043 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_uncertain_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "errors" + "log" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" +) + +// The issuing write of a forced move reaches the authority store (renamed +// into place) but the store reports an error (directory sync): the master +// cannot know whether the move is issued, and memory stays unissued. The +// CLI must report an unknown outcome with the same-request-id recovery, +// never "nothing moved", also on a rerun before the master restarts; after a +// restart the master reloads the issued record and a rerun with the same id +// gets the grant. +func TestWorkspaceForceMoveUncertainIssueWriteIsUnknown(t *testing.T) { + logs := &lockedLog{} + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil + }} + h, stop := startDeleteMaster(t, cfg) + stopped := false + defer func() { + if !stopped { + stop() + } + }() + seedForcedVolume(t, h) + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + var faults atomic.Int32 + authority.SetPutAfterRenameFaultForTest(func(r authority.DurableRecord) error { + if r.Workspace == nil { + return nil + } + for _, m := range r.Workspace.Moves { + if m.RequestID == "force-1" && m.Issued && faults.Add(1) == 1 { + return errors.New("injected directory fsync failure after the rename") + } + } + return nil + }) + t.Cleanup(func() { authority.SetPutAfterRenameFaultForTest(nil) }) + + args := func(addr string) []string { + return []string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"} + } + for _, attempt := range []string{"first", "rerun before restart"} { + code, out, errOut := runCLI(args(h.Addr())) + if code != wsExitUnknown || strings.Contains(errOut+out, "nothing moved") || !strings.Contains(errOut, "rerun with the SAME --request-id force-1") { + t.Fatalf("%s: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", attempt, code, out, errOut) + } + } + if faults.Load() != 1 { + t.Fatalf("fixture: the issuing write failed %d times; want once", faults.Load()) + } + if line, _ := h.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 1 { + t.Fatalf("fixture: memory published the issue (epoch %d); this control needs it unpublished", line.Epoch) + } + if !strings.Contains(logs.String(), `MoveWorkspace outcome unknown volume="vol-f" request="force-1"`) || strings.Contains(logs.String(), "forced move issued") { + t.Fatalf("master log must record an unknown outcome, not an issue:\n%s", logs.String()) + } + + stop() + stopped = true + h2, stop2 := startDeleteMaster(t, cfg) + defer stop2() + if line, _ := h2.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 2 { + t.Fatalf("fixture: the reloaded store does not hold the issued move (epoch %d)", line.Epoch) + } + code, out, errOut := runCLI(args(h2.Addr())) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") || !strings.Contains(out, "restored to the last published image") { + t.Fatalf("rerun after restart: exit %d stdout %q stderr %s", code, out, errOut) + } +} diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index c6516119ec..c0fc650b39 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -469,6 +469,11 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.mu.Lock() if p.workspaceUncertain[ask.VolumeID] { p.mu.Unlock() + if grant != nil { + // An earlier workspace write may have landed (an issue among + // them): a move cannot be answered definitely until a reload. + return fmt.Errorf("authority: workspace persistence uncertain; restart required: %w", ErrWorkspaceOutcomeUncertain) + } return fmt.Errorf("authority: workspace persistence uncertain; restart required") } if p.workspace[ask.VolumeID] != nil && ask.Intent != IntentRefreshEndpoint && grant == nil { @@ -607,6 +612,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.refreshLeaseViewLocked(ask.VolumeID) } p.mu.Unlock() + if issuedWorkspace != nil { + // The store may have written the issuing record before + // failing (e.g. a directory sync after the rename): the + // move's outcome is unknown, not refused. + return fmt.Errorf("authority: durable Put of a workspace move issue failed: %w: %w", err, ErrWorkspaceOutcomeUncertain) + } return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err) } p.writeSeqByVolume[ask.VolumeID] = nextSeq diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index f14b0bc1db..e27dff65f2 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -6,8 +6,26 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" ) +// putAfterRenameFault, when set, runs in every FileAuthorityStore.Put after +// the record's rename (its bytes are in the final file) and before the +// directory sync; an error fails that Put as a failed sync would. +var putAfterRenameFault atomic.Pointer[func(DurableRecord) error] + +// SetPutAfterRenameFaultForTest installs (nil clears) that hook for every +// FileAuthorityStore in the process. Tests only: it models a durable write +// whose caller sees an error (directory sync or close failing after the +// rename). +func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) { + if hook == nil { + putAfterRenameFault.Store(nil) + return + } + putAfterRenameFault.Store(&hook) +} + // ============================================================ // P14 S5 — File-Per-Volume Authority Store // @@ -188,6 +206,11 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error { _ = os.Remove(tempPath) return fmt.Errorf("authority_store: rename temp->final: %w", err) } + if h := putAfterRenameFault.Load(); h != nil { + if err := (*h)(record); err != nil { + return fmt.Errorf("authority_store: after rename: %w", err) + } + } // Best-effort fsync the directory so the rename is durable. // On Windows, opening directories as files for fsync is not diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 5b83779332..27f50cabe1 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -2,18 +2,29 @@ package authority import ( "context" + "errors" "fmt" "time" ) // WorkspaceHead is read from the configured HEAD source, never supplied as // operator evidence. Detached means the old holder's final cut is committed. +// FilerMtimeNS is the HEAD entry's modification time as the filer reports it +// with that same read (1 s resolution; the entry's mtime is set by the cut +// that wrote it); 0 means the source gave none (unknown, never invented). type WorkspaceHead struct { Gen, Epoch, RemoteLSN uint64 Holder string Detached bool + FilerMtimeNS int64 } +// ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its +// issuing write failed after it may have reached the store, or the volume's +// workspace persistence is already uncertain. Memory shows it unissued, but +// a reload may find it issued; a definite refusal must not be reported. +var ErrWorkspaceOutcomeUncertain = errors.New("workspace move outcome unknown: an authority write may have landed") + type WorkspaceLease struct { ReplicaID string Epoch uint64 @@ -350,19 +361,32 @@ func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, req // forcedMoveAdmissionLocked returns the audit bound of the lost range when a // forced move is admitted. Caller holds p.mu. func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) { - now := p.workspaceNow() + lostUntil, _, err := p.forcedMoveBarrierLocked(volume, lease) + if err != nil { + return 0, err + } + return lostUntil, nil +} + +// forcedMoveBarrierLocked evaluates forced admission at master time now. It +// returns the barrier (the audit bound of the lost range, wall time: the +// later of lease expiry and the granted or restart deadline, each plus +// skew) whether or not it has passed, and an error while it has not. +// Caller holds p.mu. +func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) { + now = p.workspaceNow() skew := p.workspaceSkew(lease) deadline := p.leaseDeadlineLocked(volume) - if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { - return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") - } - // The audit bound only, in wall time: the admission above keeps both + // The audit bound only, in wall time: the admission below keeps both // predicates (the deadline's monotonic reading included). - lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() + lostUntil = time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() if d := deadline.Add(skew).UnixNano(); d > lostUntil { lostUntil = d } - return lostUntil, nil + if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + return lostUntil, now, nil } // issueWorkspaceMove marks the move issued and starts the new holder's lease @@ -414,16 +438,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return s, r.NewEpoch, now, nil } } - owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID - if !owned && q.Kind == "forced" { - // Admitted (the expected holder's lease has expired) and HEAD read - // after that: a HEAD at an older epoch means the expected holder - // never claimed it, or an earlier holder's late claim landed. The - // lost range starts at this HEAD's RemoteLSN. A HEAD at the expected - // or a higher epoch that is not the expected holder's stays refused. - owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch - } - if !owned { + if !workspaceHeadAdmits(q, h) { return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") } if q.Kind == "clean" { @@ -443,7 +458,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} if q.Kind == "forced" { - lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} + lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil, HeadTimeNS: h.FilerMtimeNS} if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { return nil, 0, time.Time{}, err } @@ -456,3 +471,81 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra p.issueWorkspaceMove(s, len(s.Moves)-1, now) return s, r.NewEpoch, now, nil } + +// workspaceHeadAdmits is the HEAD rule of a move: HEAD is the expected +// holder's at the expected epoch, or, for a forced move only, any published +// HEAD at an older epoch. Admitted (the expected holder's lease has expired) +// and HEAD read after that: a HEAD at an older epoch means the expected +// holder never claimed it, or an earlier holder's late claim landed. The +// lost range starts at this HEAD's RemoteLSN. A HEAD at the expected or a +// higher epoch that is not the expected holder's stays refused. +func workspaceHeadAdmits(q WorkspaceMoveRequest, h WorkspaceHead) bool { + owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID + if !owned && q.Kind == "forced" { + owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch + } + return owned +} + +// WorkspaceForcedMovePreview is a forced move's admission as the publisher +// would judge it now. It is advisory: MoveWorkspace checks again. +type WorkspaceForcedMovePreview struct { + Admitted bool + Reason string // why not admitted, or a note on an admitted replay + // LostUntilNS is the forced barrier (master wall time): the move is + // admissible from then on, and it bounds the lost range. 0 when there + // is no lease of the expected holder to judge. + LostUntilNS int64 + NowNS int64 // the master time of this judgement + Replay bool // the request id is an issued move: a move replays it +} + +// PreviewWorkspaceForcedMove runs the forced admission of req (request +// validation, journal replay, the expected line and lease, the barrier) +// without reserving, writing or minting anything. The HEAD rule is +// WorkspaceMoveHeadAdmits, applied by the caller to a HEAD read after an +// admitted preview, as for the move itself. +func (p *Publisher) PreviewWorkspaceForcedMove(req WorkspaceMoveRequest) WorkspaceForcedMovePreview { + p.mu.Lock() + defer p.mu.Unlock() + out := WorkspaceForcedMovePreview{NowNS: p.workspaceNow().UnixNano()} + if req.Kind != "forced" { + out.Reason = "workspace move preview: forced moves only" + return out + } + if err := validateWorkspaceMoveRequest(req); err != nil { + out.Reason = err.Error() + return out + } + if _, replay, err := p.issuedWorkspaceReplayLocked(req); err != nil { + out.Reason = err.Error() + return out + } else if replay { + out.Admitted, out.Replay = true, true + out.Reason = "request id already issued: a move with it returns the stored grant" + if lr, ok := p.lostRangeForRequestLocked(req.VolumeID, req.RequestID); ok { + out.LostUntilNS = lr.LostUntilNS + } + return out + } + _, line, ok := p.workspaceLineLocked(req.VolumeID) + s := p.workspace[req.VolumeID] + if !ok || line.info.Epoch != req.ExpectedEpoch || line.info.ReplicaID != req.ExpectedReplicaID || s == nil || s.Lease == nil { + out.Reason = "workspace move: missing or changed authority/lease" + return out + } + lostUntil, now, err := p.forcedMoveBarrierLocked(req.VolumeID, s.Lease) + out.LostUntilNS, out.NowNS = lostUntil, now.UnixNano() + if err != nil { + out.Reason = err.Error() + return out + } + out.Admitted = true + return out +} + +// WorkspaceMoveHeadAdmits reports whether head passes the HEAD rule of req +// (the same predicate a move applies). +func WorkspaceMoveHeadAdmits(req WorkspaceMoveRequest, head WorkspaceHead) bool { + return workspaceHeadAdmits(req, head) +} diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go index 40d26cd5ae..74198aa17a 100644 --- a/seaweed-block/core/authority/workspace_lost_range.go +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -16,6 +16,11 @@ import ( // none of them was acknowledged later than LostUntilNS (master time: the // forced barrier, the lease horizon or restart deadline plus skew). The // lease carries no write frontier, so the upper bound is a time. +// +// HeadTimeNS is the kept HEAD entry's filer mtime, read with that HEAD at the +// move; 0 means unknown (the filer gave none, or the record predates the +// field). It is stored apart from the checksummed v1 range body (see +// lostRangeEnvelope) so the encoding of the ranges themselves is unchanged. type WorkspaceLostRange struct { RequestID string NewEpoch uint64 @@ -23,17 +28,82 @@ type WorkspaceLostRange struct { OldEpoch uint64 LostAfterLSN uint64 LostUntilNS int64 + HeadTimeNS int64 `json:"-"` } // lostRangeFileExtension does not end in storeFileExtension: authority // loaders, old and new, never read these files. const lostRangeFileExtension = ".lostrange.json" +// lostRangeEnvelope: Checksum covers VolumeID and Ranges exactly as before +// HEAD times existed, so a binary that predates them still verifies and +// loads the file (it ignores the two fields after it). HeadTimes carries the +// non-zero HEAD times; HeadTimesChecksum covers VolumeID, Ranges and +// HeadTimes together, and a file with HeadTimes but without a matching +// HeadTimesChecksum fails its checks. type lostRangeEnvelope struct { - Version int `json:"v"` - VolumeID string `json:"volume"` - Ranges []WorkspaceLostRange `json:"ranges"` - Checksum string `json:"checksum"` + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []WorkspaceLostRange `json:"ranges"` + Checksum string `json:"checksum"` + HeadTimes []lostRangeHeadTime `json:"head_times,omitempty"` + HeadTimesChecksum string `json:"head_times_checksum,omitempty"` +} + +type lostRangeHeadTime struct { + RequestID string + NewEpoch uint64 + HeadTimeNS int64 +} + +func lostRangeHeadTimesChecksum(volumeID string, ranges []WorkspaceLostRange, times []lostRangeHeadTime) string { + body, err := json.Marshal(struct { + VolumeID string + Ranges []WorkspaceLostRange + HeadTimes []lostRangeHeadTime + }{volumeID, ranges, times}) + if err != nil { + return "" + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]) +} + +func encodeLostRangeEnvelope(volumeID string, ranges []WorkspaceLostRange) lostRangeEnvelope { + env := lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)} + for _, r := range ranges { + if r.HeadTimeNS != 0 { + env.HeadTimes = append(env.HeadTimes, lostRangeHeadTime{RequestID: r.RequestID, NewEpoch: r.NewEpoch, HeadTimeNS: r.HeadTimeNS}) + } + } + if len(env.HeadTimes) > 0 { + env.HeadTimesChecksum = lostRangeHeadTimesChecksum(volumeID, ranges, env.HeadTimes) + } + return env +} + +// decodeLostRangeHeadTimes checks env's HEAD times and copies them onto its +// ranges. +func decodeLostRangeHeadTimes(env *lostRangeEnvelope) error { + if len(env.HeadTimes) == 0 && env.HeadTimesChecksum == "" { + return nil + } + if env.HeadTimesChecksum != lostRangeHeadTimesChecksum(env.VolumeID, env.Ranges, env.HeadTimes) { + return errors.New("head times checksum mismatch") + } + for _, t := range env.HeadTimes { + found := false + for i := range env.Ranges { + if env.Ranges[i].RequestID == t.RequestID && env.Ranges[i].NewEpoch == t.NewEpoch { + env.Ranges[i].HeadTimeNS = t.HeadTimeNS + found = true + } + } + if !found { + return fmt.Errorf("head time for unknown range %s/%d", t.RequestID, t.NewEpoch) + } + } + return nil } func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string { @@ -54,7 +124,7 @@ func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []Wo if volumeID == "" { return fmt.Errorf("authority_store: lost range with empty VolumeID") } - payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)}) + payload, err := json.Marshal(encodeLostRangeEnvelope(volumeID, ranges)) if err != nil { return fmt.Errorf("authority_store: encode lost range: %w", err) } @@ -136,6 +206,8 @@ func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLo err = errors.New("checksum mismatch") case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name: err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID) + default: + err = decodeLostRangeHeadTimes(&env) } if err != nil { skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err)) @@ -189,6 +261,51 @@ func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) e return nil } +// ErrWorkspaceLostRangeMissing: an issued forced move has no readable lost +// range (never written, or its file failed its checks at load and was +// skipped). The readout is unproven; it must never be reported as no loss. +var ErrWorkspaceLostRangeMissing = errors.New("workspace lost range missing or unreadable") + +// ErrWorkspaceNoForcedMove: the request id names no issued forced move. +var ErrWorkspaceNoForcedMove = errors.New("workspace: no issued forced move with that request id") + +// WorkspaceLostRangeReadout is one stored lost range with the stored move +// record it belongs to (the HEAD generation the move kept, and the hosts). +type WorkspaceLostRangeReadout struct { + WorkspaceLostRange + VolumeID string + HeadGen uint64 + OldHost, NewHost string +} + +// WorkspaceLostRangeReadouts returns the stored lost range of every issued +// forced move of volume, in journal (issue) order, or only requestID's when +// it is not empty. Nothing is recomputed. Any issued forced move in scope +// whose range is not loaded fails the whole read with +// ErrWorkspaceLostRangeMissing; an empty result means the volume has no +// issued forced move. +func (p *Publisher) WorkspaceLostRangeReadouts(volume, requestID string) ([]WorkspaceLostRangeReadout, error) { + p.mu.Lock() + defer p.mu.Unlock() + var out []WorkspaceLostRangeReadout + if s := p.workspace[volume]; s != nil { + for _, m := range s.Moves { + if !m.Issued || m.Kind != "forced" || (requestID != "" && m.RequestID != requestID) { + continue + } + r, ok := p.lostRangeLocked(volume, m.RequestID, m.NewEpoch) + if !ok { + return nil, fmt.Errorf("%w: forced move %q (epoch %d -> %d) of volume %q has no loaded lost range record", ErrWorkspaceLostRangeMissing, m.RequestID, m.OldEpoch, m.NewEpoch, volume) + } + out = append(out, WorkspaceLostRangeReadout{WorkspaceLostRange: r, VolumeID: volume, HeadGen: m.HeadGen, OldHost: m.OldHost, NewHost: m.NewHost}) + } + } + if requestID != "" && len(out) == 0 { + return nil, fmt.Errorf("%w: %q on volume %q", ErrWorkspaceNoForcedMove, requestID, volume) + } + return out, nil +} + // WorkspaceLostRanges returns the lost ranges of volume's issued forced // moves (an entry with no matching issued move is ignored). func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { @@ -209,3 +326,16 @@ func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { } return out } + +// lostRangeForRequestLocked returns the recorded range of requestID's +// journal record, if any. Called under p.mu. +func (p *Publisher) lostRangeForRequestLocked(volume, requestID string) (WorkspaceLostRange, bool) { + if s := p.workspace[volume]; s != nil { + for _, m := range s.Moves { + if m.RequestID == requestID { + return p.lostRangeLocked(volume, requestID, m.NewEpoch) + } + } + } + return WorkspaceLostRange{}, false +} diff --git a/seaweed-block/core/authority/workspace_lost_range_readout_test.go b/seaweed-block/core/authority/workspace_lost_range_readout_test.go new file mode 100644 index 0000000000..7dc5e6d5cb --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range_readout_test.go @@ -0,0 +1,339 @@ +package authority + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +// The HEAD time a forced move kept, as the filer reported it with HEAD. +var headFilerTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + +// pastBarrier moves now past the forced barrier of v's current lease. +func pastBarrier(t *testing.T, p *Publisher, now *time.Time) { + t.Helper() + st := p.WorkspaceState("v") + if st == nil || st.Lease == nil { + t.Fatal("no lease") + } + barrier := time.Unix(0, st.Lease.ExpiresAtNS) + if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { + barrier = d + } + *now = barrier.Add(p.workspaceSkew(st.Lease)).Add(time.Second) +} + +// INV-WS-LOST-RANGE-READOUT-001: a forced move stores the kept HEAD's filer +// time with its range; the readout returns it, with the move record's HEAD +// generation, also after a reload. A range with a HEAD time keeps the v1 +// checksum over the ranges, so a binary that predates HEAD times still +// verifies the file; a range without one is written exactly as before. +func TestWorkspaceForcedMoveStoresHeadFilerTime(t *testing.T) { + for _, known := range []bool{true, false} { + t.Run(map[bool]string{true: "filer time known", false: "filer time unknown"}[known], func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + head := forcedLostRangeHead + if known { + head.FilerMtimeNS = headFilerTime.UnixNano() + } + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head) + if err != nil { + t.Fatal(err) + } + want := WorkspaceLostRangeReadout{WorkspaceLostRange: WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano(), HeadTimeNS: head.FilerMtimeNS}, + VolumeID: "v", HeadGen: 7, OldHost: "old-node", NewHost: "new-node"} + for name, q := range map[string]*Publisher{"running": p, "reloaded": NewPublisher(nil, WithStore(disk))} { + got, err := q.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(got) != 1 || got[0] != want { + t.Fatalf("%s: readout %+v %v; want [%+v]", name, got, err, want) + } + } + raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "head_times") != known { + t.Fatalf("head times present=%v in %s", !known, raw) + } + // What a binary that predates HEAD times reads and checks. + type oldRange struct { + RequestID string + NewEpoch uint64 + OldReplicaID string + OldEpoch uint64 + LostAfterLSN uint64 + LostUntilNS int64 + } + var old struct { + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []oldRange `json:"ranges"` + Checksum string `json:"checksum"` + } + if err := json.Unmarshal(raw, &old); err != nil { + t.Fatal(err) + } + body, _ := json.Marshal(struct { + VolumeID string + Ranges []oldRange + }{old.VolumeID, old.Ranges}) + sum := sha256.Sum256(body) + if old.Version != 1 || old.Checksum != hex.EncodeToString(sum[:]) || len(old.Ranges) != 1 || old.Ranges[0].LostAfterLSN != 42 { + t.Fatalf("an older binary would not verify the file: %s", raw) + } + }) + } +} + +// A HEAD time changed on disk without its checksum fails the file's checks: +// the readout then fails, never "no loss" and never a wrong time. +func TestWorkspaceLostRangeHeadTimeTamperFailsClosed(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + head := forcedLostRangeHead + head.FilerMtimeNS = headFilerTime.UnixNano() + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "v"+lostRangeFileExtension) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var env map[string]any + if err := json.Unmarshal(raw, &env); err != nil { + t.Fatal(err) + } + env["head_times"].([]any)[0].(map[string]any)["HeadTimeNS"] = float64(headFilerTime.Add(time.Hour).UnixNano()) + tampered, _ := json.Marshal(env) + if err := os.WriteFile(path, tampered, 0o644); err != nil { + t.Fatal(err) + } + reloaded := NewPublisher(nil, WithStore(disk)) + if _, err := reloaded.WorkspaceLostRangeReadouts("v", ""); !errors.Is(err, ErrWorkspaceLostRangeMissing) { + t.Fatalf("tampered head time: %v; want ErrWorkspaceLostRangeMissing", err) + } + if !loadErrorsMention(reloaded, "head times checksum mismatch") { + t.Fatalf("load errors %v do not name the failed check", reloaded.LoadErrors()) + } +} + +func loadErrorsMention(p *Publisher, s string) bool { + for _, e := range p.LoadErrors() { + if strings.Contains(e.Error(), s) { + return true + } + } + return false +} + +// Accumulation: a second forced move with no cut between (HEAD unchanged, +// still at the first holder's epoch) keeps the same LostAfterLSN with a +// later LostUntil; a forced move after a new cut starts at the new HEAD. The +// readout lists every range in issue order, or one by request id; replays +// return the stored ranges, never recomputed ones. +func TestWorkspaceLostRangeAccumulatesInIssueOrder(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + h1 := forcedLostRangeHead + h1.FilerMtimeNS = headFilerTime.UnixNano() + f1, err := p.MoveWorkspace(ctx, forcedLostRangeReq, h1) // old-node -> new-node, epoch 1 -> 2 + if err != nil { + t.Fatal(err) + } + pastBarrier(t, p, now) + f2req := WorkspaceMoveRequest{RequestID: "f2", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "new-node", TargetHost: "third-node", + ExpectedEpoch: f1.NewEpoch, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + f2, err := p.MoveWorkspace(ctx, f2req, h1) // the grantee never cut: HEAD unchanged + if err != nil { + t.Fatal(err) + } + pastBarrier(t, p, now) + h3 := WorkspaceHead{Gen: 8, Epoch: f2.NewEpoch, Holder: "third-node/old", RemoteLSN: 50, FilerMtimeNS: headFilerTime.Add(time.Minute).UnixNano()} + f3req := WorkspaceMoveRequest{RequestID: "f3", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "third-node", TargetHost: "old-node", + ExpectedEpoch: f2.NewEpoch, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + if _, err := p.MoveWorkspace(ctx, f3req, h3); err != nil { + t.Fatal(err) + } + got, err := p.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(got) != 3 { + t.Fatalf("readout %+v %v; want three ranges", got, err) + } + if got[0].RequestID != "f" || got[1].RequestID != "f2" || got[2].RequestID != "f3" { + t.Fatalf("not in issue order: %+v", got) + } + if got[1].LostAfterLSN != got[0].LostAfterLSN || got[1].LostUntilNS <= got[0].LostUntilNS || got[1].HeadGen != 7 || got[1].HeadTimeNS != h1.FilerMtimeNS { + t.Fatalf("no cut between: want the same LostAfterLSN, a later LostUntil and the same HEAD: %+v then %+v", got[0], got[1]) + } + if got[2].LostAfterLSN != 50 || got[2].HeadGen != 8 || got[2].HeadTimeNS != h3.FilerMtimeNS || got[2].LostUntilNS <= got[1].LostUntilNS { + t.Fatalf("after a cut: want a range from the new HEAD: %+v", got[2]) + } + one, err := p.WorkspaceLostRangeReadouts("v", "f2") + if err != nil || len(one) != 1 || one[0] != got[1] { + t.Fatalf("by request id: %+v %v; want [%+v]", one, err, got[1]) + } + if _, err := p.WorkspaceLostRangeReadouts("v", "nope"); !errors.Is(err, ErrWorkspaceNoForcedMove) { + t.Fatalf("unknown request id: %v", err) + } + // A replay much later, after a reload, returns the stored grant and the + // stored range: nothing is recomputed from the replay's clock or HEAD. + *now = now.Add(time.Hour) + q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now })) + r2, err := q.MoveWorkspace(ctx, f2req, WorkspaceHead{Gen: 99, Epoch: 9, Holder: "x/y", RemoteLSN: 999, FilerMtimeNS: 1}) + if err != nil || r2 != f2 { + t.Fatalf("replay %+v %v; want the stored grant %+v", r2, err, f2) + } + again, err := q.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(again) != 3 || again[0] != got[0] || again[1] != got[1] || again[2] != got[2] { + t.Fatalf("after reload and replay: %+v %v; want %+v", again, err, got) + } +} + +// Fail closed: an issued forced move whose range file is missing, or fails +// its checksum, makes the readout fail (all ranges, or its own); it never +// returns an empty "no loss". +func TestWorkspaceLostRangeReadoutFailsClosed(t *testing.T) { + for _, damage := range []string{"missing", "checksum"} { + t.Run(damage, func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "v"+lostRangeFileExtension) + if damage == "missing" { + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + } else { + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":43`, 1)), 0o644); err != nil { + t.Fatal(err) + } + } + reloaded := NewPublisher(nil, WithStore(disk)) + for _, id := range []string{"", "f"} { + got, err := reloaded.WorkspaceLostRangeReadouts("v", id) + if !errors.Is(err, ErrWorkspaceLostRangeMissing) || got != nil { + t.Fatalf("request %q: %+v %v; want ErrWorkspaceLostRangeMissing", id, got, err) + } + } + if damage == "checksum" && !loadErrorsMention(reloaded, "checksum mismatch") { + t.Fatalf("load errors %v", reloaded.LoadErrors()) + } + }) + } +} + +// skipRangeStore drops the lost range write but reports success: the +// mutant "grant issued, range write skipped". +type skipRangeStore struct{ *FileAuthorityStore } + +func (skipRangeStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil } + +// The mutant "grant issued, range write skipped" is detected: the move +// issues (the store claimed the range durable), but the readout of a master +// that reloads from disk fails closed instead of reporting no loss. (The +// order itself, range before issue, is TestWorkspaceForcedMoveLostRangeOrdering.) +func TestWorkspaceLostRangeSkippedWriteIsDetected(t *testing.T) { + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, skipRangeStore{disk}, false) + *now = barrier.Add(time.Second) + if r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil || !r.Issued { + t.Fatalf("fixture: %+v %v", r, err) + } + if _, err := NewPublisher(nil, WithStore(disk)).WorkspaceLostRangeReadouts("v", "f"); !errors.Is(err, ErrWorkspaceLostRangeMissing) { + t.Fatalf("skipped range write not detected: %v", err) + } +} + +// countWritesStore counts every durable write, authority and lost range. +type countWritesStore struct { + *FileAuthorityStore + writes atomic.Int64 +} + +func (s *countWritesStore) Put(r DurableRecord) error { + s.writes.Add(1) + return s.FileAuthorityStore.Put(r) +} + +func (s *countWritesStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error { + s.writes.Add(1) + return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs) +} + +// The preview runs the forced admission and writes nothing: before the +// barrier it is refused and names the barrier (when it becomes admissible); +// after it, it is admitted, and the move then records exactly that barrier +// as LostUntil. A replay previews as admitted with the stored bound. +func TestWorkspaceForcedMovePreviewWritesNothing(t *testing.T) { + disk, dir := newTempStore(t) + store := &countWritesStore{FileAuthorityStore: disk} + p, now, barrier := forcedLostRangeFixture(t, store, false) + before, state := store.writes.Load(), p.WorkspaceState("v") + *now = barrier.Add(-time.Nanosecond) + pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq) + if pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.NowNS != now.UnixNano() || !strings.Contains(pv.Reason, "has not elapsed") { + t.Fatalf("preview before the barrier: %+v", pv) + } + *now = barrier.Add(time.Second) + pv = p.PreviewWorkspaceForcedMove(forcedLostRangeReq) + if !pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.Replay { + t.Fatalf("preview after the barrier: %+v", pv) + } + bad := forcedLostRangeReq + bad.ExpectedEpoch = 5 + if pv := p.PreviewWorkspaceForcedMove(bad); pv.Admitted || !strings.Contains(pv.Reason, "missing or changed authority/lease") { + t.Fatalf("preview at a stale epoch: %+v", pv) + } + clean := forcedLostRangeReq + clean.Kind, clean.Force = "clean", false + if pv := p.PreviewWorkspaceForcedMove(clean); pv.Admitted { + t.Fatalf("preview of a clean move: %+v", pv) + } + if !WorkspaceMoveHeadAdmits(forcedLostRangeReq, forcedLostRangeHead) || WorkspaceMoveHeadAdmits(forcedLostRangeReq, WorkspaceHead{Gen: 9, Epoch: 1, Holder: "other/old"}) { + t.Fatal("the preview's HEAD rule differs from the move's") + } + if got := store.writes.Load(); got != before { + t.Fatalf("preview wrote %d times", got-before) + } + if after := p.WorkspaceState("v"); len(after.Moves) != len(state.Moves) || *after.Lease != *state.Lease { + t.Fatalf("preview changed state: %+v -> %+v", state, after) + } + if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 { + t.Fatalf("preview wrote a lost range file: %v", m) + } + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal(err) + } + if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0].LostUntilNS != pv.LostUntilNS { + t.Fatalf("move recorded %+v; the preview named %d", got, pv.LostUntilNS) + } + writes := store.writes.Load() + *now = now.Add(time.Hour) + if pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq); !pv.Admitted || !pv.Replay || pv.LostUntilNS != barrier.UnixNano() { + t.Fatalf("preview of the issued request %+v (grant %+v)", pv, r) + } + if store.writes.Load() != writes { + t.Fatal("replay preview wrote") + } +} diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go new file mode 100644 index 0000000000..aab5f3ec8e --- /dev/null +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -0,0 +1,69 @@ +package authority + +import ( + "context" + "errors" + "testing" + "time" +) + +// An issuing write that lands in the store but reports an error (the +// directory sync after the rename) leaves the move's outcome unknown: +// MoveWorkspace fails with ErrWorkspaceOutcomeUncertain while memory shows +// it unissued, a retry before a reload fails the same way, and a reload finds +// it issued and replays it. Ordinary refusals (admission before the barrier, +// a failed lost-range write before the issue) are not marked uncertain. +func TestWorkspaceUncertainIssueWriteIsTyped(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + req := forcedLostRangeReq + req.RequestID = "uncertain-1" + + *now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("admission refusal before the barrier: %v; want a plain refusal", err) + } + *now = barrier.Add(time.Second) + testLostRangeFaultHook = func(string) error { return errInjected } + t.Cleanup(func() { testLostRangeFaultHook = nil }) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, errInjected) || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("lost-range write failure before the issue: %v; want a plain refusal", err) + } + testLostRangeFaultHook = nil + + faults := 0 + SetPutAfterRenameFaultForTest(func(r DurableRecord) error { + if r.Workspace != nil { + for _, m := range r.Workspace.Moves { + if m.RequestID == req.RequestID && m.Issued { + faults++ + return errInjected + } + } + } + return nil + }) + t.Cleanup(func() { SetPutAfterRenameFaultForTest(nil) }) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("issuing write landed then failed: %v; want ErrWorkspaceOutcomeUncertain", err) + } + SetPutAfterRenameFaultForTest(nil) + if faults != 1 || p.IssuedWorkspaceMove(req) { + t.Fatalf("fixture: faults=%d issued in memory=%v; want one fault and memory unissued", faults, p.IssuedWorkspaceMove(req)) + } + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("retry before a reload: %v; want ErrWorkspaceOutcomeUncertain", err) + } + reloaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now })) + if !reloaded.IssuedWorkspaceMove(req) { + t.Fatal("the reloaded store does not hold the issued move") + } + r, err := reloaded.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || !r.Issued || r.RequestID != req.RequestID { + t.Fatalf("replay after reload: %+v %v", r, err) + } + if got, err := reloaded.WorkspaceLostRangeReadouts("v", req.RequestID); err != nil || len(got) != 1 || got[0].LostAfterLSN != 42 { + t.Fatalf("readout after reload: %+v %v", got, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index eb6fd6f4eb..2fff8ee9ef 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -70,9 +70,12 @@ const ( // SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there. SnapAbsent = "absent" - // OriginCreate and OriginFork are a volume's origins. - OriginCreate = "create" - OriginFork = "fork" + // OriginCreate, OriginFork and OriginRestore are a volume's origins. A + // restore is a fork whose volume later becomes independent of its source + // (own chunks, restoreIndependentName written); until then it is a fork. + OriginCreate = "create" + OriginFork = "fork" + OriginRestore = "restore" // DefaultOpDeadline bounds a snapshot or fork from reading its source to // its final write (spec §2.3). @@ -395,10 +398,10 @@ func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) { if v.Format != volumeFormat { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: format %d not supported", p, v.Format) } - if v.Origin != OriginCreate && v.Origin != OriginFork { + if v.Origin != OriginCreate && v.Origin != OriginFork && v.Origin != OriginRestore { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: origin %q", p, v.Origin) } - if v.Origin == OriginFork && (v.Fork == nil || v.Fork.RequestID == "") { + if isForked(v.Origin) && (v.Fork == nil || v.Fork.RequestID == "") { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: a fork without its fork record", p) } v.State = string(e.Extended[extVolState]) @@ -527,8 +530,10 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } } - if v.Origin == OriginFork { + if isForked(v.Origin) { // One read of HEAD decides both: absent and aborted never attach. + // A restore reads only its own HEAD here, never its source: a source + // deleted meanwhile is a normal state, not a mismatch. h, has, err := c.ReadHead(ctx, vol) switch { case err != nil: @@ -748,11 +753,18 @@ func (c *Catalog) AbortSnapshot(ctx context.Context, vol, name, attempt string) // is confirmed or can never apply. It never touches another attempt's // intent, even under the same operation: an earlier attempt's create may // still be held by the server and land later (W5 rule). A failed delete -// leaves the intent, which only over-protects. +// leaves the intent, which only over-protects. The delete outlives the +// caller's cancellation (cleanup after a refused or cancelled request) but is +// bounded by dropIntentTimeout, so it can never hang on an unresponsive filer. func (c *Catalog) dropIntent(ctx context.Context, root, id string) { - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dropIntentTimeout) + defer cancel() + _ = c.f.DeleteEntry(dctx, path.Join(root, intentsDir), id, nil) } +// dropIntentTimeout bounds one intent delete (a var so tests can shorten it). +var dropIntentTimeout = 30 * time.Second + type createOutcome int const ( @@ -859,6 +871,23 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if !ok { return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) } + if v.Origin == OriginRestore { + // A restore is independent only once its marker exists: a snapshot + // taken before would keep naming the source's chunks for its whole + // retention, so it is refused until then. + if _, independent, err := c.ReadIndependence(ctx, vol); err != nil { + return SnapshotInfo{}, err + } else if !independent { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) + } + // The supplied image need not be the current HEAD: a cut taken before + // the marker may still name the source's chunks. Check the image itself. + if q, err := c.foreignRefsOf(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } else if q > 0 { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) + } + } // Take the name: this request's record, or an earlier attempt's of it. attempt, err := c.claimName(ctx, vol, root, req, head.Gen) @@ -1169,6 +1198,24 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // unsettled keeps its own intent (that create may still land); no attempt // or replay deletes another attempt's intent. func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginFork) +} + +// Restore starts an independent restore of req.Source's snapshot into +// req.Target: the same steps as Fork (claim, qualified refs, HEAD), recorded +// with Origin restore. The target serves at once (lazy fill); the restore +// driver then hydrates every chunk, re-uploads the qualified ones under the +// target's own keys in bounded batch cuts, and MarkIndependent records the +// end of the lineage once HEAD holds no ref to another volume. +func (c *Catalog) Restore(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginRestore) +} + +// isForked reports whether origin made the volume from another volume's +// snapshot (a fork record exists and HEAD may hold qualified refs). +func isForked(origin string) bool { return origin == OriginFork || origin == OriginRestore } + +func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (ForkResult, error) { if _, err := c.volRoot(req.Source); err != nil { return ForkResult{}, err } @@ -1199,7 +1246,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, refuseDeleted(req.Target, "fork to a new volume id") } if ok { - if err := c.checkForkRecord(existing, req); err != nil { + if err := c.checkForkRecord(existing, req, origin); err != nil { return ForkResult{}, err } h, has, err := c.ReadHead(ctx, req.Target) @@ -1271,7 +1318,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen) } } else { - vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: OriginFork, CreatedNs: c.now().UnixNano(), + vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(), Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record} ve, err := volumeEntry(vol, req.RequestID) if err != nil { @@ -1285,7 +1332,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) } v, err := decodeVolume(path.Join(dstRoot, volumeName), got) - if err != nil || c.checkForkRecord(v, req) != nil || v.Fork.HeadSHA256 != digest { + if err != nil || c.checkForkRecord(v, req, origin) != nil || v.Fork.HeadSHA256 != digest { return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) } } @@ -1477,7 +1524,10 @@ func (c *Catalog) AbortFork(ctx context.Context, target string) (claimed bool, e } // checkForkRecord refuses a target VOLUME that is not this fork request's. -func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest) error { +func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest, origin string) error { + if v.Origin != origin { + return catErr(CodeTargetExists, false, nil, "volume %s exists (origin %s, not %s)", req.Target, v.Origin, origin) + } if v.Fork == nil || v.Fork.RequestID != req.RequestID { return catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) } diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 7e8bf522f5..678e243df2 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -19,6 +19,15 @@ import ( const extGCDeleted = "swb.gc.deleted" +// ErrBlobDeleteRejected identifies a definite per-object refusal (HTTP400). +// It never proves the needle absent; GC retains its tombstone and reports it. +var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected") + +// DefaultGCClockSkew is the allowed pairwise difference between timestamp +// writers and collectors. Deployments with a larger bound must raise ClockSkew; +// no finite time-based grace can be safe with unbounded clock differences. +const DefaultGCClockSkew = time.Minute + // BlobDeleter deletes one immutable needle. Missing needles are success. // Implementations must not reuse a deleted fid. type BlobDeleter interface { @@ -30,8 +39,11 @@ type BlobDeleter interface { // lease expiry or a cached guess. Unknown authority retains the intent. type GCConfig struct { Grace, IntentTTL time.Duration - IssuedEpoch func(context.Context, string) (uint64, error) - Now func() time.Time + // ClockSkew bounds pairwise wall-clock differences. Zero uses the default. + // Binding creation timestamps additionally lose up to one second of precision. + ClockSkew time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time } type GCRoot struct { @@ -47,10 +59,16 @@ type GCObject struct { Key string `json:"key"` FID string `json:"fid"` } +type GCDeleteFailure struct { + GCObject + Error string `json:"error"` +} + type GCResult struct { - Roots []GCRoot `json:"roots"` - WouldDelete []GCObject `json:"would_delete"` - WouldExpireIntents []string `json:"would_expire_intents"` + FailedDeletes []GCDeleteFailure `json:"failed_deletes"` + Roots []GCRoot `json:"roots"` + WouldDelete []GCObject `json:"would_delete"` + WouldExpireIntents []string `json:"would_expire_intents"` Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int // Pre-binding needles cannot be enumerated by this API. They are retained; // UnknownUnbound is true rather than inventing a report-only count. @@ -77,6 +95,7 @@ type gcIntent struct { // Different collectors may duplicate idempotent blob deletes but cannot // shorten either collector's independent two-mark grace requirement. type Collector struct { + scope string // empty traces and reclaims the entire namespace cat *Catalog blobs BlobDeleter cfg GCConfig @@ -89,6 +108,12 @@ func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, er if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority") } + if cfg.ClockSkew == 0 { + cfg.ClockSkew = DefaultGCClockSkew + } + if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second { + return nil, errors.New("chunkstore: invalid GC clock skew bound") + } if cfg.Now == nil { cfg.Now = time.Now } @@ -112,6 +137,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e result.Roots = []GCRoot{} result.WouldDelete = []GCObject{} result.WouldExpireIntents = []string{} + result.FailedDeletes = []GCDeleteFailure{} defer func() { if err != nil && apply { g.candidates = map[string]gcCandidate{} @@ -119,7 +145,13 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e }() start := g.cfg.Now() if !g.last.IsZero() && start.Before(g.last) { - return result, errors.New("chunkstore: GC clock moved backwards") + // Discard coverage across a backward clock step; a fresh complete mark + // can still make progress without borrowing time from the future. + if apply { + g.candidates = map[string]gcCandidate{} + } + // Preview must also ignore the old coverage without mutating it. + // Candidate lookup below is guarded by this same condition. } roots := map[string]bool{} var bindings []gcBinding @@ -207,18 +239,18 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } for _, in := range intents { result.Intents++ - if in.CreatedNs <= 0 || in.CreatedNs > start.UnixNano() { + if in.CreatedNs <= 0 { return result, errors.New("chunkstore: invalid intent creation time") } expire := false - if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL { + if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && g.oldEnough(start, time.Unix(0, in.CreatedNs), g.cfg.IntentTTL, 0) { issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol) // Catalog copy intents are retained: their exclusive creates // are not epoch-fenced. For a capture, both the authority // and the actual CAS domain must have // advanced. Mere lease loss, or issuance without takeover, // cannot authorize expiry of a paused publisher's intent. - expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued + expire = (g.scope == "" || g.scope == vol) && authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued } if expire { expired = append(expired, gcIntent{r, in}) @@ -256,6 +288,10 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } } } + // INV-MAINT-SCOPE: roots above remain catalog-wide; candidates are local. + if g.scope != "" && g.scope != vol { + continue + } pageAfter := "" for { page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage) @@ -312,15 +348,18 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e continue } created := time.Unix(b.entry.Attributes.Crtime, 0) - if !start.After(created.Add(g.cfg.Grace)) { + if !g.oldEnough(start, created, g.cfg.Grace, time.Second) { continue } candidate, seen := g.candidates[p] + if !g.last.IsZero() && start.Before(g.last) { + seen = false + } if !seen || candidate.digest != b.digest { candidate = gcCandidate{start, b.digest} } result.Candidates++ - if start.Sub(candidate.since) < g.cfg.Grace { + if !g.oldEnough(start, candidate.since, g.cfg.Grace, 0) { nextCandidates[p] = candidate continue } @@ -343,7 +382,20 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } } if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { - return result, err + if ctx.Err() != nil { + return result, ctx.Err() + } + if !errors.Is(err, ErrBlobDeleteRejected) { + return result, err + } + // 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. + result.FailedDeletes = append(result.FailedDeletes, GCDeleteFailure{ + GCObject: GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])}, Error: err.Error(), + }) + nextCandidates[p] = candidate + continue } e := proto.Clone(b.entry).(*filerpb.Entry) e.Extended[extGCDeleted] = []byte("done") @@ -388,3 +440,11 @@ func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { } return reader.Get(ctx, fid) } + +// 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. +func (g *Collector) oldEnough(now, stamp time.Time, grace, resolution time.Duration) bool { + age := now.Sub(stamp) + return age > grace && age-grace > g.cfg.ClockSkew+resolution +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go b/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go new file mode 100644 index 0000000000..427d0596cc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go @@ -0,0 +1,308 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" + "path" + "strings" + "testing" + "time" +) + +// Exercise the default one-minute pairwise budget independently of the +// implementation constant. Wider clock differences require a larger config. +const testedGCSkew = time.Minute + +func TestGCSkewSnapshotDeleteGraceBothDirections(t *testing.T) { + for _, offset := range []time.Duration{-testedGCSkew, testedGCSkew} { + t.Run(offset.String(), func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + realDelete := *now + c.SetClock(func() time.Time { return realDelete.Add(offset) }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) + snapshotDir(t, f, "v1", "s1") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + if offset < 0 { + *now = realDelete.Add(g.cfg.Grace - testedGCSkew/2) + } else { + *now = realDelete + } + roots, err := g.snapshotAttemptHeads(ctx, "v1", *now) + if err != nil || len(roots) != 1 { + t.Fatalf("skew shortened delete grace or blocked mark: roots=%d err=%v", len(roots), err) + } + *now = realDelete.Add(g.cfg.Grace + 2*testedGCSkew + time.Nanosecond) + roots, err = g.snapshotAttemptHeads(ctx, "v1", *now) + if err != nil || len(roots) != 0 { + t.Fatalf("old deleting attempt did not release: roots=%d err=%v", len(roots), err) + } + }) + } +} +func TestGCSkewIntentExpiryUsesConservativeAge(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old"}) + if err != nil { + t.Fatal(err) + } + ins, _ := r.ListIntents(ctx) + created := time.Unix(0, ins[0].CreatedNs) + head, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } + *now = created.Add(g.cfg.IntentTTL + testedGCSkew/2) + result, err := g.Run(ctx) + if err != nil || result.ExpiredIntents != 0 { + t.Fatalf("intent expired inside skew allowance: %+v %v", result, err) + } + *now = created.Add(g.cfg.IntentTTL + testedGCSkew + time.Nanosecond) + result, err = g.Run(ctx) + if err != nil || result.ExpiredIntents != 1 { + t.Fatalf("eligible intent %s retained: %+v %v", id, result, err) + } +} +func TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for _, key := range []string{"rooted", "orphan"} { + if err := r.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}) + if err != nil { + t.Fatal(err) + } + dir := path.Join(catBase, "v1", intentsDir) + entry, err := f.LookupEntry(ctx, dir, id) + if err != nil { + t.Fatal(err) + } + var doc intentDoc + if err = json.Unmarshal(entry.Content, &doc); err != nil { + t.Fatal(err) + } + doc.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() + entry.Content, _ = json.Marshal(doc) + if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + out, err := g.Run(ctx) + if err != nil { + t.Fatalf("future intent blocked unrelated progress: %v", err) + } + if i == 1 && out.Reclaimed != 1 { + t.Fatalf("unrelated orphan did not progress: %+v", out) + } + *now = now.Add(2 * time.Hour) + } + if _, err = r.Get(ctx, "rooted"); err != nil { + t.Fatal("future root lost", err) + } +} +func TestGCSkewPersistedCoverageAcrossHosts(t *testing.T) { + for _, future := range []bool{false, true} { + t.Run(map[bool]string{false: "fast-reader", true: "future-writer"}[future], func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + first := *now + if future { + *now = first.Add(testedGCSkew) + } + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + if future { + *now = first + } else { + *now = first.Add(g.cfg.Grace + testedGCSkew/2) + } + out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || out.Reclaimed != 0 { + t.Fatalf("cross-host coverage shortened grace or blocked pass: %+v %v", out, err) + } + *now = now.Add(g.cfg.Grace + testedGCSkew + time.Nanosecond) + out, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || out.Reclaimed != 1 { + t.Fatalf("fresh safe coverage did not reclaim: %+v %v", out, err) + } + }) + } +} +func TestGCSkewBindingAgeIncludesSecondResolution(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + born := time.Unix(now.Unix(), 900000000) + *now = born.Add(g.cfg.Grace) + dir := path.Join(catBase, "v1", keysDir) + entry, err := f.LookupEntry(ctx, dir, "orphan") + if err != nil { + t.Fatal(err) + } + entry.Attributes.Crtime = born.Add(-testedGCSkew).Unix() + if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + out, err := g.Run(ctx) + if err != nil || out.Candidates != 0 { + t.Fatalf("binding age lost skew/second resolution: %+v %v", out, err) + } +} + +func TestGCSkewConfigAndMarkCoverage(t *testing.T) { + for _, skew := range []time.Duration{0, 2 * time.Minute} { + t.Run(skew.String(), func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + cfg := g.cfg + cfg.ClockSkew = skew + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true); err != nil { + t.Fatal(err) + } + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName) + if err != nil { + t.Fatal(err) + } + var mark savedGCMark + if err = json.Unmarshal(entry.Content, &mark); err != nil { + t.Fatal(err) + } + if mark.ClockSkewNs <= 0 { + t.Fatal("normalized clock policy absent from mark") + } + // A legacy mark, or one from another skew policy, cannot authorize deletion. + mark.ClockSkewNs = 0 + entry.Content, _ = json.Marshal(mark) + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), entry, nil); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + out, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) + if err != nil || out.Reclaimed != 0 { + t.Fatalf("legacy coverage borrowed: %+v %v", out, err) + } + *now = now.Add(2 * time.Hour) + out, err = c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) + if err != nil || out.Reclaimed != 1 { + t.Fatalf("matching normalized policy lost coverage: %+v %v", out, err) + } + }) + } + _, b, c, g, _ := gcFixture(t) + for _, bad := range []time.Duration{-1, time.Duration(1<<63 - 1)} { + cfg := g.cfg + cfg.ClockSkew = bad + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatalf("bad skew %s accepted", bad) + } + } +} + +func TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + first := g.last + *now = now.Add(-time.Second) + if out, err := g.Preview(ctx); err != nil || out.Reclaimed != 0 { + t.Fatalf("backward preview: %+v %v", out, err) + } + if !g.last.Equal(first) || len(g.candidates) != 1 { + t.Fatal("preview changed coverage") + } + if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 { + t.Fatalf("backward mark: %+v %v", out, err) + } + *now = now.Add(g.cfg.Grace + g.cfg.ClockSkew + time.Nanosecond) + if out, err := g.Run(ctx); err != nil || out.Reclaimed != 1 { + t.Fatalf("fresh coverage made no progress: %+v %v", out, err) + } +} + +func TestGCSkewFutureCopyDoesNotBlockOtherSettlement(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x55)}) + for _, name := range []string{"future", "expired"} { + snapshotDir(t, f, "v1", name) + holdFirst(f, path.Join(catBase, "v1", snapsDir, name)+"/") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, h); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("held copy: %v", err) + } + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + ins, err := r.ListIntents(ctx) + if err != nil || len(ins) != 2 { + t.Fatalf("intents: %+v %v", ins, err) + } + *now = now.Add(DefaultOpDeadline + time.Second) + futureID := "" + for _, in := range ins { + if !strings.Contains(in.Holder, "/future/") { + continue + } + futureID = in.ID + dir := path.Join(catBase, "v1", intentsDir) + e, err := f.LookupEntry(ctx, dir, in.ID) + if err != nil { + t.Fatal(err) + } + var d intentDoc + if err = json.Unmarshal(e.Content, &d); err != nil { + t.Fatal(err) + } + d.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() + e.Content, _ = json.Marshal(d) + if err = f.UpdateEntry(ctx, dir, e, nil); err != nil { + t.Fatal(err) + } + } + if futureID == "" { + t.Fatal("future copy fixture not found") + } + if count, err := g.SweepCopies(ctx); err != nil || count != 1 { + t.Fatalf("unrelated settlement blocked: %d %v", count, err) + } + left, err := r.ListIntents(ctx) + if err != nil || len(left) != 1 || left[0].ID != futureID { + t.Fatalf("future protection lost: %+v %v", left, err) + } + if out, err := g.Run(ctx); err != nil || len(out.Roots) == 0 { + t.Fatalf("future copy not rooted: %+v %v", out, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 2da07b132e..9d5e515dc5 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -31,6 +31,9 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { } var pending []copyAttempt for _, vol := range vols { + if g.scope != "" && g.scope != vol { + continue + } r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) if e != nil { return 0, e @@ -43,10 +46,13 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") { continue } - if in.CreatedNs <= 0 || in.CreatedNs > now.UnixNano() { + if in.CreatedNs <= 0 { return 0, errors.New("chunkstore: invalid copy intent creation time") } - if in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { + // A future creation stamp retains protection, without preventing + // unrelated copy attempts from settling. Deadline alone never + // releases roots: the permanent target claim below is still required. + if in.CreatedNs > now.UnixNano() || in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { continue } pending = append(pending, copyAttempt{vol, r, in}) @@ -86,7 +92,7 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if readErr != nil { return settled, readErr } - if !ok || v.Origin != OriginFork || v.Fork == nil || v.Fork.RequestID != parts[1] { + if !ok || !isForked(v.Origin) || v.Fork == nil || v.Fork.RequestID != parts[1] { return settled, errors.New("chunkstore: fork intent has no matching target VOLUME") } if _, err = g.cat.AbortFork(ctx, a.vol); err != nil { @@ -171,10 +177,10 @@ func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now ti } if info.State == SnapDeleting { ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64) - if err != nil || ns <= 0 || ns > now.UnixNano() { + if err != nil || ns <= 0 { return nil, errors.New("chunkstore: invalid deleted snapshot timestamp") } - if now.Sub(time.Unix(0, ns)) > g.cfg.Grace { + if g.oldEnough(now, time.Unix(0, ns), g.cfg.Grace, 0) { continue } } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 00789d6bf4..16e1994efa 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -163,7 +163,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { t.Fatalf("first unrooted mark: %+v %v", result, e) } - *now = now.Add(time.Hour) + *now = now.Add(time.Hour + g.cfg.ClockSkew + time.Nanosecond) if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go b/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go new file mode 100644 index 0000000000..0874adcddd --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go @@ -0,0 +1,97 @@ +package chunkstore + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestGCPermanentDeleteDoesNotStarveLaterBindings(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for _, key := range []string{"a_bad", "b_later", "rooted"} { + if err := r.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + if _, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}); err != nil { + t.Fatal(err) + } + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") + if err != nil { + t.Fatal(err) + } + badFID := string(entry.Extended[extFid]) + calls := map[string]int{} + var callsMu sync.Mutex + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + fid := strings.TrimPrefix(req.URL.Path, "/") + callsMu.Lock() + calls[fid]++ + callsMu.Unlock() + if fid == badFID { + http.Error(w, "cookie mismatch", http.StatusBadRequest) + return + } + if err := b.DeleteBlob(req.Context(), fid); err != nil { + t.Error(err) + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + deleter := &SWFS{http: server.Client(), vidCache: map[string][]string{"3": {strings.TrimPrefix(server.URL, "http://")}}} + if _, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + out, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) + if out.Reclaimed != 1 { + t.Fatalf("permanent DELETE starved later binding: %+v err=%v", out, err) + } + if len(out.FailedDeletes) != 1 || out.FailedDeletes[0].FID != badFID || out.FailedDeletes[0].Key != "a_bad" || out.FailedDeletes[0].Volume != "v1" || !strings.Contains(out.FailedDeletes[0].Error, "http 400") { + t.Fatalf("object refusal missing from result: %+v", out) + } + if !errors.Is(err, ErrBlobDeleteRejected) || !out.MarkSaved { + t.Fatalf("partial deletion must retain complete mark coverage: %+v %v", out, err) + } + badEntry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") + if err != nil || string(badEntry.Extended[extGCDeleted]) != "1" { + t.Fatalf("failed DELETE declared done: %+v %v", badEntry, err) + } + if _, err := r.Get(ctx, "rooted"); err != nil { + t.Fatal("protected root lost", err) + } + // A repeatedly rejected older object must not erase a younger object's + // first mark, including when each pass is a new collector process. + if err := r.Put(ctx, "c_new", []byte("c_new")); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + *now = now.Add(2 * time.Hour) + out, err = c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) + if (err != nil && !errors.Is(err, ErrBlobDeleteRejected)) || !out.MarkSaved || ((len(out.FailedDeletes) > 0) != errors.Is(err, ErrBlobDeleteRejected)) { + t.Fatalf("repeated rejection stalled coverage: %+v %v", out, err) + } + if i == 1 && out.Reclaimed != 1 { + t.Fatalf("younger binding lost coverage: %+v", out) + } + } + callsMu.Lock() + badCalls := calls[badFID] + callsMu.Unlock() + if badCalls < 2 { + t.Fatal("failed binding was silently abandoned") + } + if err := r.Put(ctx, "a_bad", []byte("rebind")); err == nil { + t.Fatal("failed deletion permitted rebinding") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution.go b/seaweed-block/core/frontend/chunkstore/gc_execution.go index 5d4b5ab560..98188a765c 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_execution.go +++ b/seaweed-block/core/frontend/chunkstore/gc_execution.go @@ -25,9 +25,11 @@ type savedGCCandidate struct { Digest string `json:"digest"` } type savedGCMark struct { + Scope string `json:"scope,omitempty"` Format int `json:"format"` Base string `json:"base"` GraceNs int64 `json:"grace_ns"` + ClockSkewNs int64 `json:"clock_skew_ns"` TTLNs int64 `json:"ttl_ns"` OpDeadlineNs int64 `json:"op_deadline_ns"` Ready bool `json:"ready"` @@ -53,6 +55,19 @@ type GCExecution struct { // and identify uncertain stages, rather than asserting remote absence. // The catalog namespace is the scope; permanent tombstones are untouched. func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) { + return c.executeGC(ctx, blobs, cfg, apply, "") +} + +// ExecuteVolumeGC reclaims only volumeID's objects while tracing every volume's +// roots. Its persisted two-mark coverage never aliases namespace-wide coverage. +func (c *Catalog) ExecuteVolumeGC(ctx context.Context, volumeID string, blobs BlobDeleter, cfg GCConfig, apply bool) (GCExecution, error) { + if err := CheckVolumeID(volumeID); err != nil { + return GCExecution{GCResult: GCResult{UnknownUnbound: true}}, err + } + return c.executeGC(ctx, blobs, cfg, apply, volumeID) +} + +func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool, scope string) (out GCExecution, err error) { // Pre-binding needles remain unenumerable even if admission/readback fails. out.UnknownUnbound = true out.DryRun = !apply @@ -62,11 +77,12 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig if err != nil { return out, err } + g.scope = scope mark, previous, err := g.readMark(ctx) if err != nil { return out, err } - if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(cfg.IntentTTL) && mark.OpDeadlineNs == int64(c.deadline()) { + if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(g.cfg.IntentTTL) && mark.ClockSkewNs == int64(g.cfg.ClockSkew) && mark.OpDeadlineNs == int64(c.deadline()) { for p, candidate := range mark.Candidates { raw, _ := hex.DecodeString(candidate.Digest) var digest [32]byte @@ -105,11 +121,17 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig } out.MarkOutcome = "complete" out.MarkSaved = true + if len(out.FailedDeletes) != 0 { + // The mark completed and is reusable even though these tombstoned + // objects remain. Report partial failure after persisting coverage, + // so CLI/maintenance callers cannot mistake it for full reclamation. + return out, fmt.Errorf("%w: %d objects retained; complete GC mark saved", ErrBlobDeleteRejected, len(out.FailedDeletes)) + } return out, nil } func (g *Collector) mark(ready bool) savedGCMark { - m := savedGCMark{Format: 1, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}} + m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), ClockSkewNs: int64(g.cfg.ClockSkew), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}} if ready { m.LastNs = g.last.UnixNano() for p, c := range g.candidates { @@ -119,8 +141,15 @@ func (g *Collector) mark(ready bool) savedGCMark { return m } +func (g *Collector) markDir() string { + if g.scope != "" { + return path.Join(g.cat.base, g.scope) + } + return g.cat.base +} + func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) { - e, err := g.cat.f.LookupEntry(ctx, g.cat.base, gcMarkName) + e, err := g.cat.f.LookupEntry(ctx, g.markDir(), gcMarkName) if errors.Is(err, ErrNotFound) { return nil, "", nil } @@ -141,20 +170,25 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) if err = d.Decode(&trailing); err != io.EOF { return nil, "", errors.New("chunkstore: trailing GC mark content") } - if m.Format != 1 || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 { + if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 || m.ClockSkewNs < 0 { return nil, "", errors.New("chunkstore: incompatible GC mark") } if m.Ready { now := g.cfg.Now().UnixNano() - if m.LastNs <= 0 || m.LastNs > now { - return nil, "", errors.New("chunkstore: invalid/future GC mark time") + if m.LastNs <= 0 { + return nil, "", errors.New("chunkstore: invalid GC mark time") } for p, c := range m.Candidates { digest, err := hex.DecodeString(c.Digest) - if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.cat.base+"/") || !strings.Contains(p, "/"+keysDir+"/") { + if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.markDir()+"/") || !strings.Contains(p, "/"+keysDir+"/") { return nil, "", errors.New("chunkstore: invalid GC candidate state") } } + if m.LastNs > now { + // A valid mark from a faster clock cannot supply elapsed coverage. + // Keep its token for the conditional replacement, but start afresh. + m.Ready, m.LastNs, m.Candidates = false, 0, nil + } } else if m.LastNs != 0 || len(m.Candidates) != 0 { return nil, "", errors.New("chunkstore: incomplete GC mark carries coverage") } @@ -176,9 +210,9 @@ func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected strin now := g.cfg.Now().Unix() e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}} if expected == "" { - err = g.cat.f.CreateEntry(ctx, g.cat.base, e, true) + err = g.cat.f.CreateEntry(ctx, g.markDir(), e, true) } else { - err = g.cat.f.UpdateEntry(ctx, g.cat.base, e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)}) + err = g.cat.f.UpdateEntry(ctx, g.markDir(), e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)}) } if err != nil { return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err) diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go b/seaweed-block/core/frontend/chunkstore/gc_execution_test.go index 94da6e0517..84b089e9c9 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_execution_test.go @@ -31,7 +31,7 @@ func TestGCExecution_PreviewAndIndependentApplyMarks(t *testing.T) { if e != nil || len(early.WouldDelete) != 0 { t.Fatalf("early independent preview: %+v %v", early, e) } - *now = now.Add(2 * time.Second) + *now = now.Add(2*time.Second + g.cfg.ClockSkew) before, _ := f.LookupEntry(ctx, catBase, gcMarkName) mature, e := c.ExecuteGC(ctx, b, g.cfg, false) if e != nil || len(mature.WouldDelete) != 1 || mature.Reclaimed != 0 { diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 498a7f667f..70ff2d2eab 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -142,7 +142,7 @@ func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) { if _, e := r.Get(ctx, "orphan"); e != nil { t.Fatal("orphan deleted before grace", e) } - *now = now.Add(2 * time.Second) + *now = now.Add(2*time.Second + g.cfg.ClockSkew) result, e := g.Run(ctx) if e != nil || result.Reclaimed != 1 { t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e) @@ -181,7 +181,7 @@ func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { {"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false}, {"unknown-authority", 2, 2, 2 * time.Hour, true, false}, {"TTL-not-exceeded", 2, 2, time.Hour, false, false}, - {"higher-issued-and-fenced", 2, 2, time.Hour + time.Nanosecond, false, true}, + {"higher-issued-and-fenced", 2, 2, time.Hour + DefaultGCClockSkew + time.Nanosecond, false, true}, } { t.Run(tc.name, func(t *testing.T) { f, b, _, g, now := gcFixture(t) @@ -339,7 +339,7 @@ func TestGC_CopyIntentSurvivesTakeover(t *testing.T) { } func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { - for _, status := range []int{200, 202, 204, 404, 401, 500} { + for _, status := range []int{200, 202, 204, 404, 400, 401, 500} { t.Run(http.StatusText(status), func(t *testing.T) { calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -355,6 +355,9 @@ func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { if (e == nil) != (status == 200 || status == 202 || status == 204 || status == 404) { t.Fatalf("status %d: %v", status, e) } + if errors.Is(e, ErrBlobDeleteRejected) != (status == 400) { + t.Fatalf("wrong per-object refusal classification: status=%d err=%v", status, e) + } if calls != 1 { t.Fatalf("calls %d", calls) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go new file mode 100644 index 0000000000..f45bd190a4 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -0,0 +1,239 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "reflect" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + v1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + v2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + for _, key := range []string{"rooted-only-from-v2", "local-orphan"} { + if err := v1.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + if err := v2.Put(ctx, "foreign-orphan", []byte("foreign")); err != nil { + t.Fatal(err) + } + if _, err := v2.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "snapshot:v2/s1/req", Keys: []string{"@v1/rooted-only-from-v2"}}); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + } + if _, err := v1.Get(ctx, "local-orphan"); err == nil { + t.Error("local orphan not reclaimed") + } + if _, err := v1.Get(ctx, "rooted-only-from-v2"); err != nil { + t.Errorf("foreign root lost: %v", err) + } + if _, err := v2.Get(ctx, "foreign-orphan"); err != nil { + t.Errorf("scoped pass reclaimed foreign candidate: %v", err) + } +} + +func TestGC_GraceConstructorRejectsCopyDeadline(t *testing.T) { + _, b, c, g, _ := gcFixture(t) + for _, grace := range []time.Duration{0, c.deadline() - time.Nanosecond, c.deadline()} { + cfg := g.cfg + cfg.Grace = grace + if _, err := NewCollector(c, b, cfg); err == nil { + t.Errorf("accepted grace %s <= copy deadline", grace) + } + } + cfg := g.cfg + cfg.Grace = c.deadline() + time.Nanosecond + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatal(err) + } +} + +func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { + t.Fatal(err) + } + if _, err := c.ExecuteGC(ctx, b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + // A separate scope must take its own first mark, even with mature global coverage. + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 0 { + t.Fatalf("scope imported namespace coverage: %+v %v", result, err) + } + if _, err = f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName); errors.Is(err, ErrNotFound) { + t.Fatal("scoped watermark absent") + } +} + +func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) { + for _, mode := range []string{"incomplete", "config"} { + t.Run(mode, func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { + t.Fatal(err) + } + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + if mode == "incomplete" { + g.scope = "v1" + _, token, err := g.readMark(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = g.writeMark(ctx, g.mark(false), token); err != nil { + t.Fatal(err) + } + } else { + g.cfg.IntentTTL += time.Second + } + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 0 { + t.Fatalf("stale coverage used: %+v %v", result, err) + } + *now = now.Add(2 * time.Hour) + result, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 1 { + t.Fatalf("fresh coverage did not progress: %+v %v", result, err) + } + }) + } +} + +func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x22)}) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil || out.Reclaimed != 0 { + t.Fatalf("foreign-only fork root reclaimed: %+v %v", out, err) + } + *now = now.Add(2 * time.Hour) + } + for _, ref := range h.Chunks { + if _, err := r.Get(ctx, ref.Key); err != nil { + t.Fatal("fork bytes reclaimed", err) + } + } +} + +func TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + remotes := map[string]*ChunkRemote{} + for _, vol := range []string{"v1", "v2"} { + remote, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) + remotes[vol] = remote + if err := remote.Put(ctx, "capture", []byte("protected")); err != nil { + t.Fatal(err) + } + if _, err := remote.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old", Keys: []string{"capture"}}); err != nil { + t.Fatal(err) + } + cur, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } + *now = time.Now().Add(3 * time.Hour) + foreign, _ := remotes["v2"].ListIntents(ctx) + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + local, _ := remotes["v1"].ListIntents(ctx) + after, _ := remotes["v2"].ListIntents(ctx) + if err != nil || result.ExpiredIntents != 1 || len(local) != 0 || !reflect.DeepEqual(foreign, after) { + t.Fatalf("capture scope mutated foreign intent: %+v %v before=%+v after=%+v", result, err, foreign, after) + } + if _, err := remotes["v2"].Get(ctx, "capture"); err != nil { + t.Fatal("foreign protection lost", err) + } + result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) + if err != nil || result.ExpiredIntents != 1 { + t.Fatalf("foreign positive eligibility not witnessed: %+v %v", result, err) + } +} +func TestVolumeGC_ForeignEligibleCopyIsNotSettled(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + h := publishSource(t, f, b.fakeBlobs, vol, map[uint64][]byte{0: chunkBytes(0x55)}) + snapshotDir(t, f, vol, "held") + holdFirst(f, path.Join(catBase, vol, snapsDir, "held")+"/") + if _, err := c.CreateSnapshot(ctx, vol, SnapshotRequest{Name: "held", RequestID: "dead"}, h); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("copy not held: %v", err) + } + } + before := intentsOf(t, f, "v2") + foreignPath := snapPath(t, f, "v2", "held") + *now = now.Add(DefaultOpDeadline + time.Second) + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + after := intentsOf(t, f, "v2") + if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v1")) != 0 || !reflect.DeepEqual(before, after) { + t.Fatalf("copy scope changed foreign attempt: %+v %v", result, err) + } + if _, err := f.LookupEntry(ctx, path.Dir(foreignPath), path.Base(foreignPath)); !errors.Is(err, ErrNotFound) { + t.Fatalf("foreign pending copy claimed: %v", err) + } + result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) + if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v2")) != 0 { + t.Fatalf("foreign positive settlement not witnessed: %+v %v", result, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go new file mode 100644 index 0000000000..22a12d1f83 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore.go @@ -0,0 +1,163 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "errors" + "path" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreIndependentName is the write-once entry that ends a restore's +// lineage: written only when the restored volume's HEAD holds no qualified +// ref, so from then on nothing of the volume reaches its source's chunks. +const ( + restoreIndependentName = "RESTORE-INDEPENDENT" + kindRestoreIndependent = "chunkrestoreindependent" +) + +// Restore error codes. +const ( + // CodeNotRestore: the volume was not made by Restore. + CodeNotRestore = "not_restore" + // CodeRestoreIncomplete: HEAD still holds qualified refs (or no HEAD). + CodeRestoreIncomplete = "restore_incomplete" +) + +// RestoreIndependence is the content of restoreIndependentName. +type RestoreIndependence struct { + Format int `json:"format"` + VolumeID string `json:"volume_id"` + HeadGen uint64 `json:"head_gen"` + MarkedNs int64 `json:"marked_ns"` +} + +// ForeignRefs counts the refs of vol's HEAD h that name ANOTHER volume's +// chunks or segments: a "@/" key whose owner is not vol. A resolved +// HEAD writes every chunk key in owner-qualified form, vol's own included, +// so a bare "@" prefix does not make a ref foreign; an unqualified key is +// always vol's own. +func ForeignRefs(h storage.ChunkHead, vol string) int { + foreign := func(key string) bool { + if !strings.HasPrefix(key, "@") { + return false + } + owner, _, ok := strings.Cut(key[1:], "/") + return !ok || owner != vol + } + n := 0 + for _, ref := range h.Chunks { + if foreign(ref.Key) { + n++ + } + } + for _, seg := range h.Segments { + if foreign(seg.Key) { + n++ + } + } + return n +} + +// MarkIndependent records that restored volume vol no longer depends on its +// source: refused unless vol was made by Restore and its current HEAD holds +// no qualified ref. Write-once: an existing marker is a replay (ok). +func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndependence, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, err + } + if m, ok, err := c.ReadIndependence(ctx, vol); err != nil || ok { + return m, err + } + v, ok, err := c.ReadVolume(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !ok || v.Origin != OriginRestore { + return RestoreIndependence{}, catErr(CodeNotRestore, false, nil, "volume %s was not made by restore", vol) + } + h, has, err := c.ReadHead(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) + } + q, err := c.foreignRefsOf(ctx, vol, h) + if err != nil { + return RestoreIndependence{}, err + } + if q > 0 { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) + } + m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} + body, err := json.Marshal(m) + if err != nil { + return RestoreIndependence{}, err + } + now := time.Now().Unix() + e := &filerpb.Entry{ + Name: restoreIndependentName, + Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, + Extended: map[string][]byte{extKind: []byte(kindRestoreIndependent)}, + Content: body, + } + if err := c.f.CreateEntry(ctx, root, e, true); err != nil { + if !errors.Is(err, ErrExists) { + return RestoreIndependence{}, remoteErr(err, "create %s of %s", restoreIndependentName, vol) + } + m, ok, err := c.ReadIndependence(ctx, vol) + if err == nil && !ok { + err = remoteErr(nil, "re-read %s of %s", restoreIndependentName, vol) + } + return m, err + } + return m, nil +} + +// ReadIndependence returns vol's independence marker; ok is false when the +// restore has not ended (or vol is not a restore). +func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreIndependence, bool, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, false, err + } + e, err := c.f.LookupEntry(ctx, root, restoreIndependentName) + if errors.Is(err, ErrNotFound) { + return RestoreIndependence{}, false, nil + } + if err != nil { + return RestoreIndependence{}, false, remoteErr(err, "read %s of %s", restoreIndependentName, vol) + } + if k := string(e.Extended[extKind]); k != kindRestoreIndependent { + return RestoreIndependence{}, false, remoteErr(nil, "%s of %s: kind %q", restoreIndependentName, vol, k) + } + var m RestoreIndependence + if err := json.Unmarshal(e.GetContent(), &m); err != nil || m.VolumeID != vol { + return RestoreIndependence{}, false, remoteErr(err, "decode %s of %s", restoreIndependentName, vol) + } + return m, true, nil +} + +// foreignRefsOf counts the refs to other volumes in image h of vol, resolved: +// the manifest segments name chunk refs too, so every segment key and every +// chunk ref inside is checked, as GC and usage resolve it. +func (c *Catalog) foreignRefsOf(ctx context.Context, vol string, h storage.ChunkHead) (int, error) { + if c.blobs == nil { + return 0, errors.New("chunkstore: restore independence needs the segment reader") + } + r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + if err != nil { + return 0, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return 0, remoteErr(err, "resolve gen %d of %s", h.Gen, vol) + } + return ForeignRefs(resolved, vol), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go new file mode 100644 index 0000000000..25588987c4 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -0,0 +1,437 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreFixture: v1 with snapshot s1, restored into v2. +func restoreFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { + t.Helper() + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil { + t.Fatal(err) + } + return f, b, c, h +} + +// ownAll re-uploads every qualified chunk of vol under vol's own keys and +// publishes a HEAD with no qualified ref (what the restore's batch cuts do). +func ownAll(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(f, b, catBase+"/"+vol) + if err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + // The batch cut's result in one step: every chunk under a fresh own key + // (chunks/e2/...), a new manifest, one HEAD CAS, intents dropped. + next := storage.ChunkHead{Epoch: 1, Holder: "h2", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + key := fmt.Sprintf("chunks/e2/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, intents, err := r.PrepareManifest(ctx, h, next, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return got +} + +// allQualified reports whether every chunk ref and segment key of h names another volume. +func allQualified(h storage.ChunkHead) bool { + for _, ref := range h.Chunks { + if !strings.HasPrefix(ref.Key, "@") { + return false + } + } + for _, seg := range h.Segments { + if !strings.HasPrefix(seg.Key, "@") { + return false + } + } + return len(h.Chunks) > 0 +} + +func TestRestore_RecordsOriginForkRecordAndQualifiedHead(t *testing.T) { + f, b, c, h := restoreFixture(t) + ctx := context.Background() + v, ok, err := c.ReadVolume(ctx, "v2") + if err != nil || !ok || v.Origin != OriginRestore || v.Fork == nil || v.Fork.Source != "v1" || v.Parent == nil { + t.Fatalf("restored VOLUME %+v ok=%v err=%v: want Origin restore with a fork record and Parent", v, ok, err) + } + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if !allQualified(h2) || len(h2.Chunks) != len(h.Chunks) { + t.Fatalf("restored HEAD %v: want all %d chunk refs (and segments) qualified", h2.Chunks, len(h.Chunks)) + } + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("a restored volume attaches like a fork: %v", err) + } +} + +func TestRestore_ReplayAndOriginMismatchRefused(t *testing.T) { + _, _, c, _ := restoreFixture(t) + ctx := context.Background() + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("restore replay: %+v %v", r, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a fork onto a restored volume with the same request id must be refused: %v", err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a restore onto a fork volume with the same request id must be refused: %v", err) + } +} + +func TestRestore_MarkIndependentOnlyWithoutQualifiedRefs(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + if _, err := c.MarkIndependent(ctx, "v2"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker while HEAD holds qualified refs: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || ok { + t.Fatalf("no marker may exist after a refused mark: ok=%v err=%v", ok, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.MarkIndependent(ctx, "v3"); CodeOf(err) != CodeNotRestore { + t.Fatalf("marker on a fork: %v, want %s", err, CodeNotRestore) + } + h := ownAll(t, f, b, "v2") + if ForeignRefs(h, "v2") != 0 { + t.Fatalf("fixture: %d foreign refs left", ForeignRefs(h, "v2")) + } + m, err := c.MarkIndependent(ctx, "v2") + if err != nil || m.HeadGen != h.Gen || m.VolumeID != "v2" { + t.Fatalf("marker: %+v %v (HEAD gen %d)", m, err, h.Gen) + } + if again, err := c.MarkIndependent(ctx, "v2"); err != nil || again != m { + t.Fatalf("marker is write-once (a replay returns it): %+v %v", again, err) + } + if got, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || !ok || got != m { + t.Fatalf("read marker: %+v %v %v", got, ok, err) + } +} + +// Deleting the source mid-restore is a normal state for every reader of T's fork record. +func TestRestore_SourceGoneIsNormal(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + before := map[uint64][]byte{} + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + before[idx] = data + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatalf("after T has its HEAD the source snapshot may go: %v", err) + } + detachHead(t, f, b, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + v, _, _ := c.ReadVolume(ctx, "v2") + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("attach of a restore whose source is gone must be normal: %v", err) + } + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("replay of a restore whose source is gone: %+v %v", r, err) + } + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil || sha256.Sum256(data) != sha256.Sum256(before[idx]) || sha256.Sum256(data) != ref.SHA256 { + t.Fatalf("chunk %d unreadable or changed after the source was deleted: %v", idx, err) + } + } + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatalf("the restore finishes with its source gone: %v (HEAD gen %d)", err, h.Gen) + } +} + +// Load-bearing (the claim ends at the first HEAD): after the restore's HEAD exists, the +// source snapshot and the source volume may both go; GC must keep every chunk T's HEAD names (qualified +// refs resolve to the owner's bindings) until T's own batch cuts replace them. +func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)}) + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { + t.Fatal(e) + } + if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + if _, e := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); e != nil { + t.Fatal(e) + } + if _, e := c.DeleteSnapshot(ctx, "v1", "s1"); e != nil { + t.Fatalf("retention/delete may retire S once T has a HEAD: %v", e) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, e := c.DeleteVolume(ctx, "v1", nil); e != nil { + t.Fatalf("delete the source volume: %v", e) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, e := r2.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + for i := 0; i < 3; i++ { + if _, e := g.Run(ctx); e != nil { + t.Fatalf("gc: %v", e) + } + *now = now.Add(2 * time.Hour) + } + want := map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)} + for idx, ref := range h2.Chunks { + got, e := r2.Get(ctx, ref.Key) + if e != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("restored chunk %d lost after S and V were deleted and GC ran: %v", idx, e) + } + } +} + +// A restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. +func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { + f, _, c, _ := catalogFixture(t) + ctx := context.Background() + v := VolumeInfo{Format: volumeFormat, VolumeID: "v9", Geometry: catGeo, Origin: OriginRestore, CreatedNs: 1, + Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: 1}, Fork: &ForkRecord{RequestID: "rq", Source: "v1", Snapshot: "s1"}} + e, err := volumeEntry(v, "rq") + if err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase+"/v9", e, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore without a HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.AbortFork(ctx, "v9"); err != nil { + t.Fatalf("abort the unpublished restore (sweep): %v", err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore with an aborted HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v9"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker on an aborted restore: %v, want %s", err, CodeRestoreIncomplete) + } +} + +// Snapshots of a restore are refused until it is independent. +func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}, h2); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("snapshot of a restore in progress: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + h := ownAll(t, f, b, "v2") + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("own chunks but no marker yet: %v, want %s", err, CodeRestoreIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + s, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h) + if err != nil { + t.Fatalf("snapshot after the marker: %v", err) + } + if ForeignRefs(s.Head(), "v2") != 0 { + t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) + } +} + +// hangingDeleteFiler blocks DeleteEntry until its ctx ends (or the test +// releases it). It reports whether that ctx carried a deadline and was live on +// entry, then how it ended. +type hangingDeleteFiler struct { + Filer + entered chan deleteEntry + ended chan error + release chan struct{} +} + +type deleteEntry struct { + hadDeadline bool + errAtEntry error +} + +func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + _, ok := ctx.Deadline() + h.entered <- deleteEntry{hadDeadline: ok, errAtEntry: ctx.Err()} + select { + case <-ctx.Done(): + h.ended <- ctx.Err() + return ctx.Err() + case <-h.release: + return errors.New("released by the test") + } +} + +// dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. +func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { + old := dropIntentTimeout + dropIntentTimeout = 50 * time.Millisecond + t.Cleanup(func() { dropIntentTimeout = old }) + h := hangingDeleteFiler{Filer: newFakeFiler(), entered: make(chan deleteEntry, 1), ended: make(chan error, 1), release: make(chan struct{})} + c := &Catalog{f: h} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan struct{}) + t.Cleanup(func() { // an unbounded delete (the failing case) is released and joined + close(h.release) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("cleanup: dropIntent did not return") + } + }) + go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() + select { + case e := <-h.entered: + if e.errAtEntry != nil { + t.Fatalf("the intent delete inherited the caller's cancellation: %v", e.errAtEntry) + } + if !e.hadDeadline { + t.Fatal("the intent delete ran without any deadline") + } + case <-time.After(5 * time.Second): + t.Fatal("dropIntent never reached the filer") + } + select { + case err := <-h.ended: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the intent delete ended with %v, want its own deadline (context.DeadlineExceeded)", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the intent delete never ended: it is unbounded") + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("dropIntent did not return: the delete is unbounded") + } +} + +// A cut image saved before the marker still names the source's chunks: the +// marker must not let it become a snapshot. +func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + stale, _ := r2.GetHead(ctx) + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + req := SnapshotRequest{Name: "stale", RequestID: "s"} + if _, err := c.CreateSnapshot(ctx, "v2", req, stale); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("stale foreign image after the marker: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", req); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + if list, _, err := c.ListSnapshots(ctx, "v2", ListOptions{}); err != nil || len(list) != 0 { + t.Fatalf("snapshots after the refusal: %v %v", list, err) + } + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "own", RequestID: "o"}, h); err != nil { + t.Fatalf("the own image must still be accepted: %v", err) + } +} + +// Retention disposition with an aborted first HEAD on a restore target: the +// fork claim alone no longer holds the parent (liveClaims counts any HEAD, +// aborted included), but the fork-record scan does (forkParentsNeeded treats +// an aborted HEAD as no HEAD), so the parent snapshot is kept as fork_parent +// until the aborted target is deleted. That conservative hold is the rule. +func TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted(t *testing.T) { + f, c, _, _ := retentionFixture(t, 1) + ctx := context.Background() + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s00", Target: "v2", RequestID: "rs"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("restore with a held HEAD create: %v", err) + } + if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { + t.Fatalf("abort the unpublished restore: claimed=%v %v", claimed, err) + } + if live, err := c.liveClaims(ctx, "v1", "s00", []string{forkClaim("v2", "rs")}); err != nil || len(live) != 0 { + t.Fatalf("claim on an aborted target: live=%v %v, want not live (any HEAD ends the claim)", live, err) + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if k := kept(res.Decisions); len(k) != 1 || k["s00"] == nil || k["s00"][0] != keepForkParent || len(res.Deleted) != 0 { + t.Fatalf("aborted restore: kept %v deleted %v; want s00 kept as fork_parent", k, res.Deleted) + } + if s, err := c.allSnapshots(ctx, "v1"); err != nil || len(s) != 1 { + t.Fatalf("parent after retention: %v %v", s, err) + } + if _, err := c.DeleteVolume(ctx, "v2", nil); err != nil { + t.Fatalf("delete the aborted restore: %v", err) + } + res, err = c.Retain(ctx, "v1", false) + if err != nil || len(res.Deleted) != 1 || res.Deleted[0] != "s00" { + t.Fatalf("after the target is gone: deleted %v (%v), want s00", res.Deleted, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index 3c2102b004..a126d1a998 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -317,6 +317,9 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { return err } resp.Body.Close() + if resp.StatusCode == http.StatusBadRequest { + return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode) + } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound { return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode) } diff --git a/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go b/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go new file mode 100644 index 0000000000..88f6dfbb2b --- /dev/null +++ b/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go @@ -0,0 +1,22 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestFrozenValidationPrecedesAnyProviderAccess(t *testing.T) { + // Deliberately poisoned receiver: validation must return before touching + // even the provider mutex/volume map, much less StopIO, capture or HEAD. + var p *DurableProvider + for _, at := range []time.Time{{}, time.Unix(0, -1), time.Now().Add(time.Hour)} { + result, last, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: at}) + if !errors.Is(err, storage.ErrInvalidFreezeBudget) || result.Head.Gen != 0 || last != 0 { + t.Fatalf("invalid input accessed provider or returned an applied point: %+v %d %v", result, last, err) + } + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go new file mode 100644 index 0000000000..d6020247f2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -0,0 +1,92 @@ +package durable + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +type maintenanceStubLayer struct{ storage.ChunkLayer } + +func (maintenanceStubLayer) Fenced() bool { return false } +func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) { + for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} { + t.Run(field, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + lin := chunkLineage{"v1", "r1", 3, 1} + layer := &maintenanceStubLayer{} + h := &volHandle{chunk: layer} + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}} + if !p.maintenanceCurrent("v1", h, layer, lin) { + t.Fatal("healthy same attachment refused") + } + switch field { + case "epoch": + id.Epoch++ + case "replica": + id.ReplicaID = "r2" + case "endpoint": + id.EndpointVersion++ + case "handle": + p.volumes["v1"] = &volHandle{chunk: layer} + case "layer": + h.chunk = &maintenanceStubLayer{} + } + p.view = precopyQueueView{id} + p.cfg.ChunkMaintenanceInterval = time.Nanosecond + calls := 0 + p.cfg.ChunkMaintenance = func(context.Context, string) error { calls++; return nil } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }) + if calls != 0 { + t.Fatalf("foreign attachment admitted %d passes", calls) + } + }) + } +} +func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + layer := &maintenanceStubLayer{} + h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}} + entered := make(chan struct{}, 2) + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, cfg: ProviderConfig{ChunkMaintenanceInterval: time.Nanosecond, ChunkMaintenance: func(ctx context.Context, _ string) error { entered <- struct{}{}; <-ctx.Done(); return ctx.Err() }}} + var stopperDone chan struct{} + t.Cleanup(func() { + p.mu.Lock() + stop, ownerDone := h.chunkStop, h.chunkDone + p.mu.Unlock() + if stop != nil { + stop() + } + for _, done := range []<-chan struct{}{stopperDone, ownerDone} { + if done != nil { + select { + case <-done: + case <-time.After(time.Second): + t.Error("cleanup did not join outstanding maintenance stopper/owner") + } + } + } + }) + for i := 0; i < 2; i++ { + p.mu.Lock() + p.startChunkLoop("v1", h, layer) + p.mu.Unlock() + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("same handle did not arm") + } + done := make(chan struct{}) + stopperDone = done + go func() { p.stopChunkLoop(h); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("stopped owner did not join") + } + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_policy_test.go b/seaweed-block/core/frontend/durable/maintenance_policy_test.go new file mode 100644 index 0000000000..734e5b89e6 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_policy_test.go @@ -0,0 +1,60 @@ +package durable + +import ( + "context" + "fmt" + "sync" + "testing" + "testing/synctest" + "time" +) + +func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) { + interval := 15 * time.Minute + seen := map[time.Duration]bool{} + for i := 0; i < 200; i++ { + s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true) + offset := s.firstDue.Sub(t0) + if offset <= 0 || offset >= interval { + t.Fatalf("phase outside interval: %s", offset) + } + seen[offset] = true + if _, due := testPolicy().due(s, s.firstDue.Add(-time.Nanosecond), false); due { + t.Fatal("published before own phase") + } + } + if len(seen) < 190 { + t.Fatalf("200 volumes collapsed into %d phases", len(seen)) + } +} + +// Virtual quiescence observes the join boundary directly, so a slow storage +// Close cannot accidentally make an omitted scheduler join look correct. +func TestMaintenanceStopJoinsBeforeRelease(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done, release, cancelled := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + defer finish() + p := &DurableProvider{} + h := &volHandle{chunkStop: cancel, chunkDone: done} + go func() { <-ctx.Done(); close(cancelled); <-release; close(done) }() + returned1, returned2 := make(chan struct{}), make(chan struct{}) + go func() { p.stopChunkLoop(h); close(returned1) }() + <-cancelled + go func() { p.stopChunkLoop(h); close(returned2) }() + synctest.Wait() + for _, returned := range []chan struct{}{returned1, returned2} { + select { + case <-returned: + t.Error("stop released before worker join") + default: + } + } + finish() + <-returned1 + <-returned2 + }) +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index c394aed3d5..55eb72554b 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -172,6 +172,13 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration + // ChunkCutTimeout bounds a cut as a whole; zero uses five minutes. + ChunkCutTimeout time.Duration + // Maintenance runs serially for an attached healthy volume. Zero interval disables + // it. Callback ownership ends only after cancellation and worker settlement. + ChunkMaintenanceInterval time.Duration + ChunkMaintenanceTimeout time.Duration + ChunkMaintenance func(context.Context, string) error // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest // I/O stopped before it resumes or settles: the drain and final cut get // three quarters of it, the settlement of a failed cut the rest (the @@ -266,9 +273,10 @@ type volHandle struct { // wait, 0 if none: a recovered volume whose layer waits for master // authority. A wait only acts while its generation is still the // latest recovery's. - recoverGen uint64 - waitGen uint64 - chunk storage.ChunkLayer // after RecoverVolume + recoverGen uint64 + waitGen uint64 + chunk storage.ChunkLayer // after RecoverVolume + chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. chunkPending storage.ChunkLayer // chunkDetach is set (under attachMu) when DetachVolume starts and @@ -336,6 +344,12 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil { return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk) } + if cfg.ChunkCaptureInterval < 0 || cfg.ChunkCutTimeout < 0 || cfg.ChunkMaintenanceInterval < 0 || cfg.ChunkMaintenanceTimeout < 0 { + return nil, fmt.Errorf("durable: chunk schedule durations must not be negative") + } + if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil { + return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback") + } if cfg.ChunkBlocks == 0 { cfg.ChunkBlocks = defaultChunkBlocks } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c74773a1c..2bc76b8324 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -320,12 +320,14 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v // startChunkLoop starts the periodic cuts of an attached layer, if configured // and not already running. The caller holds h.attachMu and p.mu. func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { - if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil { + if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil { return } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) + lin := h.chunkLineage + current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -466,7 +468,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} } - return storage.AttachChunkLayer(ws, remote, cfg) + layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg) + if attachErr == nil { + h.chunkLineage = lin + } + return layer, attachErr } // closeBoundRemote ends every remote call when the provider closes, so a @@ -635,7 +641,7 @@ const ( // cutPolicy decides when an automatic cut is due. The remote holds // snapshots, not live data: cuts are published at Snapshot, Detach/stop -// and explicit Cut, and automatically only by the operator's timer: +// and explicit Cut, and automatically by the configured timer: // - the timer fires once interval has passed since the last successful // cut of any kind (explicit Cut, Snapshot and Detach included); zero // disables it, and with it every automatic cut; @@ -760,6 +766,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer if !ok { continue } + cutCtx, cancel := p.chunkCutContext(ctx) trace := p.testChunkLoopTrace if trace != nil { trace("due", ls.LastCutNs, false) @@ -769,19 +776,21 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // A cut that completed after this decision (an explicit one // running meanwhile) restarted the timer: no cut now. var skipped bool - _, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs) + _, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs) if trace != nil { trace("cut", ls.LastCutNs, skipped) } if skipped { + cancel() continue } } else { - _, err = layer.Cut(ctx) + _, err = layer.Cut(cutCtx) if trace != nil { trace("cut", ls.LastCutNs, false) } } + cancel() s = pol.after(s, start, time.Now(), err) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff) @@ -789,15 +798,122 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } +// chunkBackground owns both workers and their cancellation. A fence is observed +// even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: +// done closes only after every admitted worker has returned. +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) { + defer close(done) + defer cancel() + var workers sync.WaitGroup + if p.cfg.ChunkCaptureInterval > 0 { + workers.Add(1) + go func() { + defer workers.Done() + cutDone := make(chan struct{}) + p.chunkLoop(ctx, volumeID, layer, cutDone) + }() + } + if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { + workers.Add(1) + go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }() + } + timer := time.NewTicker(chunkSchedulePoll) + defer timer.Stop() + for ctx.Err() == nil { + select { + case <-ctx.Done(): + case <-timer.C: + if layer.Fenced() { + cancel() + } + } + } + workers.Wait() +} + +// maintenanceCurrent binds the pass to the attached handle AND its lineage. +// The projection can remain healthy while a different owner replaces it. +func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, layer storage.ChunkLayer, lin chunkLineage) bool { + p.mu.Lock() + active := !p.closed && p.volumes[volumeID] == h && h.chunk == layer + p.mu.Unlock() + cur := p.view.Projection() + return active && chunkAuthority(cur, volumeID) && cur.VolumeID == lin.volumeID && cur.ReplicaID == lin.replicaID && cur.Epoch == lin.epoch && cur.EndpointVersion == lin.endpoint +} + +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool) { + interval := p.cfg.ChunkMaintenanceInterval + due := time.Now().Add(interval) + if p.cfg.ChunkStagger { + due = time.Now().Add(hostlimit.Phase(volumeID+":maintenance", interval)) + } + timer := time.NewTimer(time.Until(due)) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if ctx.Err() != nil || layer.Fenced() { + return + } + if !current() { + return + } + timeout := p.cfg.ChunkMaintenanceTimeout + if timeout <= 0 { + timeout = time.Minute + } + passCtx, cancel := context.WithTimeout(ctx, timeout) + // The projection has no change channel. One bounded watcher belongs to + // this pass, never to an individual tick; cancellation is joined below. + watchDone := make(chan struct{}) + go func() { + defer close(watchDone) + tick := time.NewTicker(chunkSchedulePoll) + defer tick.Stop() + for { + select { + case <-passCtx.Done(): + return + case <-tick.C: + if layer.Fenced() || !current() { + cancel() + return + } + } + } + }() + err := p.cfg.ChunkMaintenance(passCtx, volumeID) + cancel() + <-watchDone + if err != nil && ctx.Err() == nil { + log.Printf("durable: maintenance volume=%s: %v", volumeID, err) + } + // Completion-relative reset coalesces all elapsed ticks; no catch-up queue. + timer.Reset(interval) + } +} + func (p *DurableProvider) stopChunkLoop(h *volHandle) { p.mu.Lock() stop, done := h.chunkStop, h.chunkDone - h.chunkStop = nil p.mu.Unlock() if stop != nil { stop() + } + // Every concurrent stopper joins the same lifetime; none can clear ownership + // while an earlier stopper is still waiting for an admitted remote call. + if done != nil { <-done } + p.mu.Lock() + if h.chunkDone == done { + h.chunkStop = nil + h.chunkDone = nil + } + p.mu.Unlock() } func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) { @@ -831,6 +947,8 @@ func (p *DurableProvider) chunkHandle(volumeID string) (*volHandle, storage.Chun // CaptureVolume takes one quiesced cut of volumeID and publishes it to the // remote. It returns the cut's LSN. func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (uint64, error) { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() layer, err := p.chunkLayer(volumeID) if err != nil { return 0, err @@ -841,6 +959,8 @@ func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (u // MakeVolumeRemoteDurable returns nil only once volumeID's writes up to lsn // are published in the remote HEAD (snapshot, detach, migrate). func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID string, lsn uint64) error { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() layer, err := p.chunkLayer(volumeID) if err != nil { return err @@ -863,7 +983,17 @@ func chunkFenced(volumeID string, h *volHandle) error { // and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is // MakeRemoteDurable(minLSN) returning the cut: an LSN never written is // refused before anything is published, and the cut must reach minLSN. +func (p *DurableProvider) chunkCutContext(ctx context.Context) (context.Context, context.CancelFunc) { + timeout := p.cfg.ChunkCutTimeout + if timeout <= 0 { + timeout = 5 * time.Minute + } + return context.WithTimeout(ctx, timeout) +} + func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() h, layer, err := p.chunkHandle(volumeID) if err != nil { return storage.ChunkCutResult{}, err diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go new file mode 100644 index 0000000000..68f60a64c6 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -0,0 +1,360 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { + entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + remote := storage.NewMemChunkRemote() + 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 }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, vol string) error { + close(entered) + <-ctx.Done() + close(cancelled) + <-release + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { finish(); _ = p.Close() }) + s := openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("maintenance did not start with cut timer off") + } + writeDone := make(chan error, 1) + writerSettled := make(chan struct{}) + go func() { defer close(writerSettled); _, err := s.Write(1, block(0x51)); writeDone <- err }() + t.Cleanup(func() { + finish() + _ = p.Close() + select { + case <-writerSettled: + case <-time.After(5 * time.Second): + t.Error("writer cleanup did not settle") + } + }) + select { + case err := <-writeDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("maintenance held a guest lock") + } + closed := make(chan error, 1) + closeSettled := make(chan struct{}) + go func() { defer close(closeSettled); closed <- p.Close() }() + t.Cleanup(func() { + finish() + select { + case <-closeSettled: + case <-time.After(5 * time.Second): + t.Error("Close cleanup did not settle") + } + }) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("Close did not cancel maintenance") + } + select { + case err := <-closed: + t.Fatalf("Close released resources before worker join: %v", err) + default: + } + finish() + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("Close did not join") + } +} + +func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) { + view := v1View() + entered, cancelled := make(chan struct{}), make(chan struct{}) + 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 storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + close(entered) + <-ctx.Done() + close(cancelled) + return ctx.Err() + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no pass") + } + view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("lost authority did not cancel held pass") + } +} + +func TestMaintenancePassHasOneDeadline(t *testing.T) { + entered := make(chan error, 1) + three := make(chan struct{}) + var completed atomic.Int32 + 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 storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenanceTimeout: 10 * time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + <-ctx.Done() + select { + case entered <- ctx.Err(): + default: + } + if completed.Add(1) == 3 { + close(three) + } + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + done := make(chan struct{}) + go func() { _ = p.Close(); close(done) }() + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + for { + select { + case <-done: + return + case <-entered: + case <-timer.C: + t.Error("deadline callback cleanup failed to join") + return + } + } + }) + openRecovered(t, p) + // Deliberately leave the one-slot observation full across recurring passes. + select { + case <-three: + case <-time.After(5 * time.Second): + t.Fatal("recurring callback blocked with delayed receiver") + } + select { + case err := <-entered: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatal(err) + } + default: + t.Fatal("no deadline observation") + } +} + +type pendingMaintenancePut struct{ *storage.MemChunkRemote } + +func (r pendingMaintenancePut) Put(ctx context.Context, _ string, _ []byte) error { + <-ctx.Done() + return ctx.Err() +} +func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) { + remote := pendingMaintenancePut{storage.NewMemChunkRemote()} + 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 }, ChunkCutTimeout: 10 * time.Millisecond, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s := openRecovered(t, p) + if _, err = s.Write(1, block(0x48)); err != nil { + t.Fatal(err) + } + _, err = p.CaptureVolume(context.Background(), "v1") + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("whole cut did not expire: %v", err) + } + h, err := remote.GetHead(context.Background()) + if err != nil || h.Gen != 0 { + t.Fatalf("expired upload published: %+v %v", h, err) + } +} + +func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + var calls atomic.Int32 + 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 storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + if calls.Add(1) == 1 { + close(entered) + } + select { + case <-release: + case <-ctx.Done(): + } + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { finish(); _ = p.Close() }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no pass") + } + time.Sleep(30 * time.Millisecond) + if got := calls.Load(); got != 1 { + t.Fatalf("held pass started %d workers", got) + } + // Close cancels the held pass before release; there is no queued retry to drain. + if err := p.Close(); err != nil { + t.Fatal(err) + } + if got := calls.Load(); got != 1 { + t.Fatalf("Close dispatched %d elapsed ticks", got) + } + finish() +} + +func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := schedProvider(t, remote, time.Millisecond, 0) + s := openRecovered(t, p) + lsn, err := s.Write(1, block(0x91)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var first storage.ChunkHead + for { + first, err = remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if first.RemoteLSN >= lsn { + break + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-time.After(time.Millisecond): + } + } + var before int64 + for before == 0 { + before = p.DurableStatuses()[0].Chunk.Stats.LastCutNs + select { + case <-ctx.Done(): + t.Fatal("first cut did not settle", ctx.Err()) + case <-time.After(time.Millisecond): + } + } + for { + status := p.DurableStatuses()[0] + if status.Chunk.Stats.LastCutNs > before { + break + } + select { + case <-ctx.Done(): + t.Fatal("no periodic noop", ctx.Err()) + case <-time.After(time.Millisecond): + } + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != first.Gen { + t.Fatalf("noop churned HEAD: before=%d after=%d err=%v", first.Gen, after.Gen, err) + } +} + +func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) { + for _, field := range []string{"epoch", "replica", "endpoint"} { + t.Run(field, func(t *testing.T) { + view := v1View() + entered, cancelled := make(chan struct{}), make(chan struct{}) + var enterOnce, cancelOnce sync.Once + 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 storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + enterOnce.Do(func() { close(entered) }) + <-ctx.Done() + cancelOnce.Do(func() { close(cancelled) }) + return ctx.Err() + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + done := make(chan struct{}) + go func() { _ = p.Close(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("lineage cleanup did not join") + } + }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no held pass") + } + cur := view.Projection() + switch field { + case "epoch": + cur.Epoch++ + case "replica": + cur.ReplicaID = "r2" + case "endpoint": + cur.EndpointVersion++ + } + view.set(cur) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("healthy foreign lineage did not cancel pass") + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index 0c5dd7f544..5c471123e2 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -14,9 +14,25 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) +// headFilerMtimeNS is the HEAD entry's mtime from the filer's Last-Modified +// header of the same response as the content (1 s resolution), or 0 +// (unknown) when the header is absent, unparseable or not after the epoch. +func headFilerMtimeNS(h http.Header) int64 { + v := h.Get("Last-Modified") + if v == "" { + return 0 + } + t, err := http.ParseTime(v) + if err != nil || t.UnixNano() <= 0 { + return 0 + } + return t.UnixNano() +} + // NewWorkspaceHEADReader reads inline HEAD content from the configured filer // HTTP directory. It never follows redirects or accepts operator-supplied HEAD -// evidence. W2's detached state is part of the committed HEAD document. +// evidence. W2's detached state is part of the committed HEAD document. The +// HEAD's filer mtime comes from the same response (headFilerMtimeNS). func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authority.WorkspaceHead, error), error) { u, err := url.Parse(base) if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" { @@ -79,6 +95,6 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori } else if doc.DetachedBy != nil { return authority.WorkspaceHead{}, fmt.Errorf("active HEAD retains detachedBy proof") } - return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached"}, nil + return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached", FilerMtimeNS: headFilerMtimeNS(res.Header)}, nil }, nil } diff --git a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go new file mode 100644 index 0000000000..c13969c27d --- /dev/null +++ b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go @@ -0,0 +1,255 @@ +package master + +import ( + "context" + "io/fs" + "log" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// lostRangeFiles lists the lost range side files under dir. +func lostRangeFiles(t *testing.T, dir string) []string { + t.Helper() + var out []string + err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") { + out = append(out, p) + } + return err + }) + if err != nil { + t.Fatal(err) + } + return out +} + +// startStoppableMaster starts a master and registers its close as cleanup +// immediately; the returned stop closes it at most once (an explicit stop +// before a restart, then the cleanup, never closes twice). +func startStoppableMaster(t *testing.T, cfg Config) (*Host, func()) { + t.Helper() + h, err := New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + var once sync.Once + stop := func() { once.Do(func() { closeTestMaster(t, h) }) } + t.Cleanup(stop) + return h, stop +} + +// forcedMoveHost starts a master whose volume vol-f is held by r1 on node-a +// (epoch 1, lease renewed once) with a prepared target binding on node-b. +// The returned stop closes it once; it is also registered as cleanup as soon +// as the master starts, so a failing setup step never leaks it. +func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceServiceClient, *control.WorkspaceMove) { + t.Helper() + h, stop := startStoppableMaster(t, cfg) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := control.NewWorkspaceServiceClient(conn) + for _, server := range []string{"node-a", "node-b"} { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + target := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + for _, b := range []*control.WorkspaceBinding{src, target} { + if _, err := client.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "vol-f") + if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil { + t.Fatal(err) + } + return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "forced", Force: true} +} + +// INV-WS-LOST-RANGE-READOUT-001 over the real master: the preview writes +// nothing and says when the move becomes admissible; the issued forced +// grant carries the stored range (with the HEAD's filer time read with HEAD) +// and is logged; a replay returns the same grant; the lost range RPC returns +// the same stored range; after a restart with the range file damaged, a +// replay still returns the issued grant but without a range and with the +// reason, and the lost range RPC fails with DataLoss, never "no loss". +func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { + logs := &syncBuffer{} + headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + authDir := t.TempDir() + cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil + }} + h, stop, client, move := forcedMoveHost(t, cfg) + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + + pv, err := client.PreviewWorkspaceMove(ctx, move) + if err != nil { + t.Fatal(err) + } + if pv.Admitted || pv.LostUntilNs <= pv.MasterTimeNs || pv.HeadRead || !strings.Contains(pv.Reason, "has not elapsed") { + t.Fatalf("preview before the horizon: %+v", pv) + } + if _, err := client.MoveWorkspace(ctx, move); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move before the horizon: %v; want FailedPrecondition", err) + } + select { + case <-time.After(time.Until(time.Unix(0, pv.LostUntilNs)) + 50*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + pv2, err := client.PreviewWorkspaceMove(ctx, move) + if err != nil { + t.Fatal(err) + } + if !pv2.Admitted || !pv2.HeadRead || pv2.HeadGen != 9 || pv2.HeadRemoteLsn != 42 || !pv2.HeadTimeKnown || pv2.HeadTimeNs != headTime.UnixNano() || pv2.LostUntilNs != pv.LostUntilNs { + t.Fatalf("preview after the horizon: %+v", pv2) + } + if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { + t.Fatalf("preview wrote a journal record: %+v", st.Moves) + } + if files := lostRangeFiles(t, authDir); len(files) != 0 { + t.Fatalf("preview wrote a lost range: %v", files) + } + + g, err := client.MoveWorkspace(ctx, move) + if err != nil { + t.Fatal(err) + } + want := &control.WorkspaceLostRange{RequestId: "force-1", VolumeId: "vol-f", NewEpoch: g.NewEpoch, OldReplicaId: "r1", OldEpoch: move.ExpectedEpoch, + LostAfterLsn: 42, LostUntilNs: pv.LostUntilNs, HeadGen: 9, HeadTimeNs: headTime.UnixNano(), HeadTimeKnown: true} + if !g.Issued || g.LostRangeError != "" || !proto.Equal(g.LostRange, want) { + t.Fatalf("forced grant %+v; want lost range %+v", g, want) + } + for _, s := range []string{`forced move issued volume="vol-f" request="force-1"`, "old=node-a/r1@1", "new=node-b/r1@2", "replay=false", "lost_after_lsn=42", "head_gen=9", "head_filer_time=2026-11-21T01:02:03Z"} { + if !strings.Contains(logs.String(), s) { + t.Fatalf("master log lacks %q:\n%s", s, logs.String()) + } + } + g2, err := client.MoveWorkspace(ctx, move) + if err != nil || !proto.Equal(g, g2) { + t.Fatalf("replay %+v %v; want the stored grant %+v", g2, err, g) + } + if !strings.Contains(logs.String(), "replay=true") { + t.Fatalf("replayed forced grant not logged:\n%s", logs.String()) + } + for _, id := range []string{"", "force-1"} { + lr, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: id}) + if err != nil || len(lr.Ranges) != 1 || !proto.Equal(lr.Ranges[0], want) { + t.Fatalf("lost range query %q: %+v %v", id, lr, err) + } + } + if _, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: "nope"}); status.Code(err) != codes.NotFound { + t.Fatalf("unknown request id: %v; want NotFound", err) + } + if st, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"}); err != nil || len(st.Moves) != 1 || !proto.Equal(st.Moves[0].LostRange, want) { + t.Fatalf("QueryWorkspace moves %+v %v", st.GetMoves(), err) + } + if pv3, err := client.PreviewWorkspaceMove(ctx, move); err != nil || !pv3.Admitted || pv3.HeadRead || pv3.LostUntilNs != pv.LostUntilNs { + t.Fatalf("preview of the issued request: %+v %v", pv3, err) + } + + stop() + files := lostRangeFiles(t, authDir) + if len(files) != 1 { + t.Fatalf("lost range files %v", files) + } + raw, err := os.ReadFile(files[0]) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil { + t.Fatal(err) + } + h2, _ := startStoppableMaster(t, cfg) + conn, err := grpc.NewClient(h2.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + c2 := control.NewWorkspaceServiceClient(conn) + g3, err := c2.MoveWorkspace(ctx, move) + if err != nil || !g3.Issued || g3.NewEpoch != g.NewEpoch || g3.LostRange != nil || !strings.Contains(g3.LostRangeError, "missing or unreadable") { + t.Fatalf("replay with a damaged range: %+v %v; want the issued grant without a range, with the reason", g3, err) + } + if !strings.Contains(logs.String(), "lost_range=UNPROVEN") { + t.Fatalf("unproven range not logged:\n%s", logs.String()) + } + if _, err := c2.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f"}); status.Code(err) != codes.DataLoss { + t.Fatalf("lost range query with a damaged record: %v; want DataLoss", err) + } +} + +// The HEAD reader takes the HEAD entry's mtime from the filer's +// Last-Modified header of the same response; without a usable header the +// time is unknown (0), never invented. +func TestWorkspaceHEADReadsFilerMtime(t *testing.T) { + mtime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + for _, tc := range []struct { + name, header string + want int64 + }{ + {"last-modified", mtime.Format(http.TimeFormat), mtime.UnixNano()}, + {"absent", "", 0}, + {"unparseable", "yesterday", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if tc.header != "" { + w.Header().Set("Last-Modified", tc.header) + } + _, _ = w.Write([]byte(`{"format":1,"gen":9,"epoch":3,"holder":"old","remote_lsn":42}`)) + })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + h, err := read(context.Background(), "v") + if err != nil || h.FilerMtimeNS != tc.want || h.Gen != 9 || h.RemoteLSN != 42 { + t.Fatalf("HEAD %+v %v; want filer mtime %d", h, err, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 3e53da6ab8..60507669ef 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,7 @@ package master import ( "context" + "errors" "fmt" "strings" "time" @@ -132,6 +133,53 @@ func grantFact(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { OldEpoch: r.OldEpoch, NewEpoch: r.NewEpoch, HeadGen: r.HeadGen, RemoteLsn: r.RemoteLSN, Issued: r.Issued, OldHost: r.OldHost, NewHost: r.NewHost} } +// lostRangeFact is the wire form of a stored lost range. +func lostRangeFact(r authority.WorkspaceLostRangeReadout) *control.WorkspaceLostRange { + return &control.WorkspaceLostRange{RequestId: r.RequestID, VolumeId: r.VolumeID, NewEpoch: r.NewEpoch, OldReplicaId: r.OldReplicaID, OldEpoch: r.OldEpoch, + LostAfterLsn: r.LostAfterLSN, LostUntilNs: r.LostUntilNS, HeadGen: r.HeadGen, HeadTimeNs: r.HeadTimeNS, HeadTimeKnown: r.HeadTimeNS != 0} +} + +// grantWithLostRange is grantFact plus, for an issued forced grant, its +// stored lost range; a range that cannot be read leaves lost_range unset and +// says why in lost_range_error (the readout is then unproven, not empty). +func (s *services) grantWithLostRange(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { + g := grantFact(r) + if !r.Issued || r.Kind != "forced" { + return g + } + ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(r.VolumeID, r.RequestID) + switch { + case err != nil: + g.LostRangeError = err.Error() + case len(ranges) != 1: + g.LostRangeError = fmt.Sprintf("%v: %d ranges for request %q", authority.ErrWorkspaceLostRangeMissing, len(ranges), r.RequestID) + default: + g.LostRange = lostRangeFact(ranges[0]) + } + return g +} + +// logForcedGrant records an issued forced move (also a replay of one). +func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIssue error) { + if g == nil || !g.GetIssued() || g.GetKind() != "forced" { + return + } + lost := "lost_range=UNPROVEN (" + g.GetLostRangeError() + ")" + if l := g.GetLostRange(); l != nil { + head := "unknown" + if l.GetHeadTimeKnown() { + head = time.Unix(0, l.GetHeadTimeNs()).UTC().Format(time.RFC3339Nano) + } + lost = fmt.Sprintf("lost_after_lsn=%d lost_until_ns=%d lost_until=%s head_gen=%d head_filer_time=%s", + l.GetLostAfterLsn(), l.GetLostUntilNs(), time.Unix(0, l.GetLostUntilNs()).UTC().Format(time.RFC3339Nano), l.GetHeadGen(), head) + } + if postIssue != nil { + lost += fmt.Sprintf(" answer_failed_after_issue=%q", postIssue.Error()) + } + s.host.log.Printf("blockmaster: MoveWorkspace forced move issued volume=%q request=%q old=%s/%s@%d new=%s/%s@%d replay=%t %s", + g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost) +} + func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err @@ -157,11 +205,19 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) // local precondition below; Publisher checks the expected epoch atomically. // A refusal is logged after the lock is released (deferred first, so it // runs last): a slow log writer never holds workspaceMu. + // An issued forced grant is logged the same way, also after the unlock. var refusal string + var issued *control.WorkspaceGrant + var replay bool + var postIssue, unknown error defer func() { if refusal != "" { s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) } + s.logForcedGrant(issued, replay, postIssue) + if unknown != nil { + s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown) + } }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() @@ -171,11 +227,72 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } + req, target, replay, why, err := s.workspaceMoveCheckLocked(q) + if err != nil { + return nil, workspaceError(err) + } + if refusal = why; refusal != "" { + return nil, status.Error(codes.FailedPrecondition, refusal) + } + if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { + return nil, workspaceError(err) + } + r, err := s.host.Publisher().MoveWorkspace(ctx, req, head) + if err != nil { + // A move that is issued in spite of the error (it failed after the + // issue) is never a refusal: the caller recovers its grant with the + // same request id. + if s.host.Publisher().IssuedWorkspaceMove(req) { + issued, postIssue = s.issuedRecord(req), err + return nil, postIssueError(q, err) + } + if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) { + unknown = err + return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", + q.GetRequestId(), q.GetVolumeId(), err) + } + return nil, workspaceError(err) + } + // The move is issued from here on: record it for the audit log before + // anything else can fail. + issued = s.grantWithLostRange(r) + if err = s.host.reconcileWorkspaceBindings(); err != nil { + postIssue = err + return nil, postIssueError(q, err) + } + return issued, nil +} + +// postIssueError reports a failure after q's move was issued: never +// FailedPrecondition (a definite refusal); Internal, which clients treat as +// an unknown outcome, with the same-request-id recovery. +func postIssueError(q *control.WorkspaceMove, err error) error { + return status.Errorf(codes.Internal, "workspace move %q of volume %q is ISSUED, but a step after the issue failed: %v; rerun with the same request id to get its grant", + q.GetRequestId(), q.GetVolumeId(), err) +} + +// issuedRecord is the answer for req's issued journal record, if any. +func (s *services) issuedRecord(req authority.WorkspaceMoveRequest) *control.WorkspaceGrant { + if st := s.host.Publisher().WorkspaceState(req.VolumeID); st != nil { + for _, m := range st.Moves { + if m.RequestID == req.RequestID && m.Issued { + return s.grantWithLostRange(m) + } + } + } + return nil +} + +// workspaceMoveCheckLocked builds the authority request of q and the +// blockmaster's own refusal of it ("" when none): endpoints, source host, +// target node and binding. It reads and writes nothing else; MoveWorkspace +// and PreviewWorkspaceMove share it. Caller holds workspaceMu. +func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req authority.WorkspaceMoveRequest, target lifecycle.NodeRegistration, replay bool, refusal string, err error) { oldHost := s.host.workspaceSourceHost(q.GetVolumeId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()) target, ok := s.host.lifecycle.Nodes.GetNode(q.GetTargetServerId()) bindings, explicit, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) if err != nil { - return nil, workspaceError(err) + return authority.WorkspaceMoveRequest{}, lifecycle.NodeRegistration{}, false, "", err } // A volume without per-volume bindings may move to any port on the // target node's registered hosts (a host runs several slots): the host @@ -189,12 +306,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) matched = true } } - req := authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID, + req = authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID, ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()} // Strict journal isolation refuses new work only: an exact replay of an // issued move (its reply lost, the target found co-located since) gets // its durable grant back from MoveWorkspace, never a definite refusal. - replay := ok && s.host.Publisher().IssuedWorkspaceMove(req) + replay = ok && s.host.Publisher().IssuedWorkspaceMove(req) switch { case endpointErr != nil: refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) @@ -209,20 +326,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) case !matched: refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) } - if refusal != "" { - return nil, status.Error(codes.FailedPrecondition, refusal) - } - if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { - return nil, workspaceError(err) - } - r, err := s.host.Publisher().MoveWorkspace(ctx, req, head) - if err != nil { - return nil, workspaceError(err) - } - if err = s.host.reconcileWorkspaceBindings(); err != nil { - return nil, workspaceError(err) - } - return grantFact(r), nil + return req, target, replay, refusal, nil } // sameHost reports whether two host:port addresses name the same host: @@ -276,7 +380,103 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen} } for _, r := range state.Moves { - out.Moves = append(out.Moves, grantFact(r)) + out.Moves = append(out.Moves, s.grantWithLostRange(r)) + } + return out, nil +} + +// QueryWorkspaceLostRange returns the stored lost ranges of the volume's +// issued forced moves in issue order, or the one of request_id. A forced +// move whose range is missing or failed its checks fails the call with +// DataLoss: the readout is unproven, never "no loss". +func (s *services) QueryWorkspaceLostRange(ctx context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) { + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + return nil, err + } + ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(q.GetVolumeId(), q.GetRequestId()) + switch { + case errors.Is(err, authority.ErrWorkspaceLostRangeMissing): + return nil, status.Error(codes.DataLoss, err.Error()) + case errors.Is(err, authority.ErrWorkspaceNoForcedMove): + return nil, status.Error(codes.NotFound, err.Error()) + case err != nil: + return nil, workspaceError(err) + } + out := &control.WorkspaceLostRanges{} + for _, r := range ranges { + out.Ranges = append(out.Ranges, lostRangeFact(r)) + } + return out, nil +} + +// PreviewWorkspaceMove answers what MoveWorkspace would do with a forced +// move now, writing nothing: the blockmaster's own checks, the publisher's +// forced admission (with the barrier, i.e. when it becomes admissible) and, +// only once admitted, the HEAD read and HEAD rule, as the move does. A +// refusal is an answer (admitted false, reason), not an RPC error. +func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + out := &control.WorkspaceMovePreview{} + if !s.host.cfg.WorkspaceRPC { + return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled") + } + if q.GetKind() != "forced" || !q.GetForce() { + out.Reason = "workspace move preview: forced moves only (kind forced, force true)" + out.MasterTimeNs = time.Now().UnixNano() + return out, nil + } + var req authority.WorkspaceMoveRequest + var replay bool + if err := func() error { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + out.Reason = status.Convert(err).Message() + return nil + } + r, target, _, why, err := s.workspaceMoveCheckLocked(q) + if err != nil { + return err + } + req = r + pv := s.host.Publisher().PreviewWorkspaceForcedMove(req) + out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS + switch { + case why != "": + out.Admitted, out.Reason = false, why + case !pv.Admitted: + out.Reason = pv.Reason + case pv.Replay: + replay, out.Reason = true, pv.Reason + default: + if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { + out.Admitted, out.Reason = false, err.Error() + } + } + return nil + }(); err != nil { + return nil, workspaceError(err) + } + if out.MasterTimeNs == 0 { + out.MasterTimeNs = time.Now().UnixNano() + } + if !out.Admitted || replay { // a replay never reads a new HEAD + return out, nil + } + // As for the move: HEAD is read only after admission, outside the lock, + // bounded even when the caller set no deadline. + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId()) + if err != nil { + out.Admitted, out.HeadError = false, err.Error() + out.Reason = "workspace move: HEAD read failed: " + err.Error() + return out, nil + } + out.HeadRead = true + out.HeadGen, out.HeadEpoch, out.HeadHolder, out.HeadRemoteLsn = head.Gen, head.Epoch, head.Holder, head.RemoteLSN + out.HeadTimeNs, out.HeadTimeKnown = head.FilerMtimeNS, head.FilerMtimeNS != 0 + if !authority.WorkspaceMoveHeadAdmits(req, head) { + out.Admitted, out.Reason = false, "workspace move: HEAD not owned by expected holder" } return out, nil } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c3ad60dd8b..c1e4029609 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -198,9 +198,11 @@ const ( codeLSNBehind = "lsn_behind" codeInternal = "internal" codeBadRequest = "bad_request" - codeMethodNotAllowed = "method_not_allowed" - codeForbidden = "forbidden" - codeNotFound = "not_found" + // Only freeze-option validation before provider admission emits this code. + codeInvalidFreezeBudget = "invalid_freeze_budget" + codeMethodNotAllowed = "method_not_allowed" + codeForbidden = "forbidden" + codeNotFound = "not_found" ) const chunkBodyLimit = 64 << 10 @@ -308,7 +310,7 @@ func chunkErrorCode(err error) (int, string, bool) { case errors.Is(err, errFrozenDetachUnsupported): return http.StatusConflict, "frozen_detach_unsupported", false case errors.Is(err, storage.ErrInvalidFreezeBudget): - return http.StatusBadRequest, "bad_request", false + return http.StatusBadRequest, codeInvalidFreezeBudget, false case errors.Is(err, storage.ErrFrozenTailTooLarge): return http.StatusConflict, "frozen_tail_too_large", true // A local window abort cancels its uploads; that cancellation is not @@ -532,7 +534,7 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) return } if (req.Frozen && (req.Plain || req.FreezeStartedAtNs <= 0 || time.Unix(0, req.FreezeStartedAtNs).After(time.Now()))) || (!req.Frozen && (req.FreezeStartedAtNs != 0 || req.AllowOverBudget)) { - writeChunkErr(w, http.StatusBadRequest, "bad_request", false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") + writeChunkErr(w, http.StatusBadRequest, codeInvalidFreezeBudget, false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") return } ctl := s.chunkTarget(w, req.VolumeID) diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go index 58534c3fee..7c9064aadb 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -64,3 +64,44 @@ func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { t.Fatalf("cut response lost tail: %d %s %v", w.Code, w.Body, err) } } + +func TestChunkFrozenValidationHasDistinctPreMutationCode(t *testing.T) { + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}} + s := chunkServer(t, NewChunkControl(p, nil), true) + past := time.Now().Add(-time.Second).UnixNano() + for _, body := range []string{ + `{"volumeID":"v1","frozen":true}`, + fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), + fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, past), + `{"volumeID":"v1","allowOverBudget":true}`, + } { + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + var got chunkErrorBody + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if w.Code != 400 || got.Code != "invalid_freeze_budget" || got.Retryable || p.calls != 0 { + t.Errorf("freeze validation lacked pre-mutation classification: status=%d body=%s calls=%d", w.Code, w.Body, p.calls) + } + } + // A malformed/generic400 is not evidence of a typed clean refusal. + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":`, "") + var got chunkErrorBody + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if w.Code != 400 || got.Code != "bad_request" || p.calls != 0 { + t.Errorf("generic400 relabelled: %d %s calls=%d", w.Code, w.Body, p.calls) + } + status, code, retry := chunkErrorCode(storage.ErrInvalidFreezeBudget) + if status != 400 || code != "invalid_freeze_budget" || retry { + t.Errorf("storage validation lost classification: %d %s %t", status, code, retry) + } + for _, terminal := range []error{storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced} { + wantStatus, wantCode, wantRetry := chunkErrorCode(terminal) + status, code, retry = chunkErrorCode(errors.Join(terminal, storage.ErrInvalidFreezeBudget)) + if status != wantStatus || code != wantCode || retry != wantRetry { + t.Errorf("validation hid terminal/unknown cause: %d %s %t", status, code, retry) + } + } +} diff --git a/seaweed-block/core/recovery/receiver_install_format_v3_test.go b/seaweed-block/core/recovery/receiver_install_format_v3_test.go index 907aaf6fbd..2a838cfd6a 100644 --- a/seaweed-block/core/recovery/receiver_install_format_v3_test.go +++ b/seaweed-block/core/recovery/receiver_install_format_v3_test.go @@ -15,13 +15,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Plan row 9b controls (DESIGN r17.3.1 section 8.7): the dual-lane Receiver -// on a dark v3 store. Every BASE block and WAL entry goes through the -// session's install handle; both admission schedules run through the real -// receiver (WriteBase through frameBaseBlock, ApplyInstallEntry through -// RebuildSession.ApplyWALEntry from frameWALEntry). Owner: claude03. -// Mutants are the row 9a store mutants (shared-begin, no-id-check, -// premature-check) plus the row 9b caller mutants named per control. +// Controls for the dual-lane Receiver on a dark v3 store. Every BASE block +// and WAL entry goes through the session's install handle; both admission +// schedules run through the real receiver (WriteBase through frameBaseBlock, +// ApplyInstallEntry through RebuildSession.ApplyWALEntry from frameWALEntry). +// Mutants are the store mutants (shared-begin, no-id-check, premature-check) +// plus the caller mutants named per control. const v3RecvBlock = 4096 @@ -182,7 +181,7 @@ func TestReceiverV3InstallThroughTheHandle(t *testing.T) { } } -// Drain setup through the receiver (codex01 r12 P2): A's admitted BASE +// Drain setup through the receiver: A's admitted BASE // write is held; B's SessionStart begin waits for it; B writes the target // block and stays installing; a further A frame fails A's session with // ErrInstallSuperseded and B's block is byte-identical. @@ -248,7 +247,7 @@ func TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession(t *testing.T) { } } -// Premature-check setup through the receiver (codex03 r11): A's frame parks +// Premature-check setup through the receiver: A's frame parks // before acquiring installMu; B supersedes, writes the target block and // stays installing; A resumes and its session fails with // ErrInstallSuperseded, B's block byte-identical. WriteBase runs through @@ -311,7 +310,7 @@ func TestReceiverV3SupersededBaseDoneFailsWithoutAnAck(t *testing.T) { } } -// codex01 row 9b P1: the real Sender sends BaseDone from its base lane while +// The real Sender sends BaseDone from its base lane while // its WAL lane is still sending (sender.go base goroutine). A WAL entry of // the same session after BaseDone must still apply, and the barrier then // completes with both lanes' bytes. Mutant: admitting install-lane WAL diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index af8db26e4b..29fd611ef7 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -414,21 +414,26 @@ func (x *WorkspaceMove) GetTargetServerId() string { } type WorkspaceGrant struct { - state protoimpl.MessageState `protogen:"open.v1"` - RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` - OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` - NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"` - Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"` - OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` - NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` - HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` - RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"` - Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"` - OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"` - NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` + NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"` + Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"` + OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` + NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` + HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"` + Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"` + OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"` + NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"` + // Forced grants only: the lost range stored before the issue (also on a + // replay). Absent on a forced grant means the readout is not proven, and + // lost_range_error says why; it never means "no loss". + LostRange *WorkspaceLostRange `protobuf:"bytes,13,opt,name=lost_range,json=lostRange,proto3" json:"lost_range,omitempty"` + LostRangeError string `protobuf:"bytes,14,opt,name=lost_range_error,json=lostRangeError,proto3" json:"lost_range_error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkspaceGrant) Reset() { @@ -545,6 +550,370 @@ func (x *WorkspaceGrant) GetNewHost() string { return "" } +func (x *WorkspaceGrant) GetLostRange() *WorkspaceLostRange { + if x != nil { + return x.LostRange + } + return nil +} + +func (x *WorkspaceGrant) GetLostRangeError() string { + if x != nil { + return x.LostRangeError + } + return "" +} + +// What a forced move abandoned. head_gen 0: no published HEAD (everything the +// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read +// with HEAD at the move (1 s resolution), valid only when head_time_known. +// lost_until_ns is master time; the upper bound is a time, not an LSN. +type WorkspaceLostRange struct { + state protoimpl.MessageState `protogen:"open.v1"` + RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + NewEpoch uint64 `protobuf:"varint,3,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` + OldReplicaId string `protobuf:"bytes,4,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` + OldEpoch uint64 `protobuf:"varint,5,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` + LostAfterLsn uint64 `protobuf:"varint,6,opt,name=lost_after_lsn,json=lostAfterLsn,proto3" json:"lost_after_lsn,omitempty"` + LostUntilNs int64 `protobuf:"varint,7,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"` + HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + HeadTimeNs int64 `protobuf:"varint,9,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` + HeadTimeKnown bool `protobuf:"varint,10,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRange) Reset() { + *x = WorkspaceLostRange{} + mi := &file_workspace_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRange) ProtoMessage() {} + +func (x *WorkspaceLostRange) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRange.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRange) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{7} +} + +func (x *WorkspaceLostRange) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +func (x *WorkspaceLostRange) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspaceLostRange) GetNewEpoch() uint64 { + if x != nil { + return x.NewEpoch + } + return 0 +} + +func (x *WorkspaceLostRange) GetOldReplicaId() string { + if x != nil { + return x.OldReplicaId + } + return "" +} + +func (x *WorkspaceLostRange) GetOldEpoch() uint64 { + if x != nil { + return x.OldEpoch + } + return 0 +} + +func (x *WorkspaceLostRange) GetLostAfterLsn() uint64 { + if x != nil { + return x.LostAfterLsn + } + return 0 +} + +func (x *WorkspaceLostRange) GetLostUntilNs() int64 { + if x != nil { + return x.LostUntilNs + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadGen() uint64 { + if x != nil { + return x.HeadGen + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadTimeNs() int64 { + if x != nil { + return x.HeadTimeNs + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadTimeKnown() bool { + if x != nil { + return x.HeadTimeKnown + } + return false +} + +type WorkspaceLostRangeQuery struct { + state protoimpl.MessageState `protogen:"open.v1"` + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + RequestId string `protobuf:"bytes,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRangeQuery) Reset() { + *x = WorkspaceLostRangeQuery{} + mi := &file_workspace_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRangeQuery) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRangeQuery) ProtoMessage() {} + +func (x *WorkspaceLostRangeQuery) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRangeQuery.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRangeQuery) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{8} +} + +func (x *WorkspaceLostRangeQuery) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspaceLostRangeQuery) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +type WorkspaceLostRanges struct { + state protoimpl.MessageState `protogen:"open.v1"` + Ranges []*WorkspaceLostRange `protobuf:"bytes,1,rep,name=ranges,proto3" json:"ranges,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRanges) Reset() { + *x = WorkspaceLostRanges{} + mi := &file_workspace_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRanges) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRanges) ProtoMessage() {} + +func (x *WorkspaceLostRanges) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRanges.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRanges) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{9} +} + +func (x *WorkspaceLostRanges) GetRanges() []*WorkspaceLostRange { + if x != nil { + return x.Ranges + } + return nil +} + +// lost_until_ns is when a forced move becomes admissible (0 if the master has +// no lease to judge). HEAD is read only when admitted, as for the move. +type WorkspaceMovePreview struct { + state protoimpl.MessageState `protogen:"open.v1"` + Admitted bool `protobuf:"varint,1,opt,name=admitted,proto3" json:"admitted,omitempty"` + Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` + LostUntilNs int64 `protobuf:"varint,3,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"` + MasterTimeNs int64 `protobuf:"varint,4,opt,name=master_time_ns,json=masterTimeNs,proto3" json:"master_time_ns,omitempty"` + HeadRead bool `protobuf:"varint,5,opt,name=head_read,json=headRead,proto3" json:"head_read,omitempty"` + HeadError string `protobuf:"bytes,6,opt,name=head_error,json=headError,proto3" json:"head_error,omitempty"` + HeadGen uint64 `protobuf:"varint,7,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + HeadEpoch uint64 `protobuf:"varint,8,opt,name=head_epoch,json=headEpoch,proto3" json:"head_epoch,omitempty"` + HeadHolder string `protobuf:"bytes,9,opt,name=head_holder,json=headHolder,proto3" json:"head_holder,omitempty"` + HeadRemoteLsn uint64 `protobuf:"varint,10,opt,name=head_remote_lsn,json=headRemoteLsn,proto3" json:"head_remote_lsn,omitempty"` + HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` + HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceMovePreview) Reset() { + *x = WorkspaceMovePreview{} + mi := &file_workspace_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceMovePreview) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceMovePreview) ProtoMessage() {} + +func (x *WorkspaceMovePreview) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceMovePreview.ProtoReflect.Descriptor instead. +func (*WorkspaceMovePreview) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{10} +} + +func (x *WorkspaceMovePreview) GetAdmitted() bool { + if x != nil { + return x.Admitted + } + return false +} + +func (x *WorkspaceMovePreview) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *WorkspaceMovePreview) GetLostUntilNs() int64 { + if x != nil { + return x.LostUntilNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetMasterTimeNs() int64 { + if x != nil { + return x.MasterTimeNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadRead() bool { + if x != nil { + return x.HeadRead + } + return false +} + +func (x *WorkspaceMovePreview) GetHeadError() string { + if x != nil { + return x.HeadError + } + return "" +} + +func (x *WorkspaceMovePreview) GetHeadGen() uint64 { + if x != nil { + return x.HeadGen + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadEpoch() uint64 { + if x != nil { + return x.HeadEpoch + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadHolder() string { + if x != nil { + return x.HeadHolder + } + return "" +} + +func (x *WorkspaceMovePreview) GetHeadRemoteLsn() uint64 { + if x != nil { + return x.HeadRemoteLsn + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadTimeNs() int64 { + if x != nil { + return x.HeadTimeNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadTimeKnown() bool { + if x != nil { + return x.HeadTimeKnown + } + return false +} + type WorkspaceStatus struct { state protoimpl.MessageState `protogen:"open.v1"` Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"` @@ -557,7 +926,7 @@ type WorkspaceStatus struct { func (x *WorkspaceStatus) Reset() { *x = WorkspaceStatus{} - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -569,7 +938,7 @@ func (x *WorkspaceStatus) String() string { func (*WorkspaceStatus) ProtoMessage() {} func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -582,7 +951,7 @@ func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceStatus.ProtoReflect.Descriptor instead. func (*WorkspaceStatus) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{7} + return file_workspace_proto_rawDescGZIP(), []int{11} } func (x *WorkspaceStatus) GetLease() *WorkspaceLeaseFact { @@ -626,7 +995,7 @@ type WorkspaceBinding struct { func (x *WorkspaceBinding) Reset() { *x = WorkspaceBinding{} - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -638,7 +1007,7 @@ func (x *WorkspaceBinding) String() string { func (*WorkspaceBinding) ProtoMessage() {} func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -651,7 +1020,7 @@ func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceBinding.ProtoReflect.Descriptor instead. func (*WorkspaceBinding) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{8} + return file_workspace_proto_rawDescGZIP(), []int{12} } func (x *WorkspaceBinding) GetVolumeId() string { @@ -700,7 +1069,7 @@ type WorkspacePlacement struct { func (x *WorkspacePlacement) Reset() { *x = WorkspacePlacement{} - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -712,7 +1081,7 @@ func (x *WorkspacePlacement) String() string { func (*WorkspacePlacement) ProtoMessage() {} func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -725,7 +1094,7 @@ func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspacePlacement.ProtoReflect.Descriptor instead. func (*WorkspacePlacement) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{9} + return file_workspace_proto_rawDescGZIP(), []int{13} } func (x *WorkspacePlacement) GetVolumeId() string { @@ -786,7 +1155,7 @@ const file_workspace_proto_rawDesc = "" + "\x04kind\x18\b \x01(\tR\x04kind\x12\x14\n" + "\x05force\x18\t \x01(\bR\x05force\x12(\n" + "\x10target_server_id\x18\n" + - " \x01(\tR\x0etargetServerId\"\xee\x02\n" + + " \x01(\tR\x0etargetServerId\"\xe4\x03\n" + "\x0eWorkspaceGrant\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" + @@ -802,7 +1171,48 @@ const file_workspace_proto_rawDesc = "" + "\x06issued\x18\n" + " \x01(\bR\x06issued\x12\x19\n" + "\bold_host\x18\v \x01(\tR\aoldHost\x12\x19\n" + - "\bnew_host\x18\f \x01(\tR\anewHost\"\xb2\x02\n" + + "\bnew_host\x18\f \x01(\tR\anewHost\x12J\n" + + "\n" + + "lost_range\x18\r \x01(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\tlostRange\x12(\n" + + "\x10lost_range_error\x18\x0e \x01(\tR\x0elostRangeError\"\xdf\x02\n" + + "\x12WorkspaceLostRange\x12\x1d\n" + + "\n" + + "request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" + + "\tvolume_id\x18\x02 \x01(\tR\bvolumeId\x12\x1b\n" + + "\tnew_epoch\x18\x03 \x01(\x04R\bnewEpoch\x12$\n" + + "\x0eold_replica_id\x18\x04 \x01(\tR\foldReplicaId\x12\x1b\n" + + "\told_epoch\x18\x05 \x01(\x04R\boldEpoch\x12$\n" + + "\x0elost_after_lsn\x18\x06 \x01(\x04R\flostAfterLsn\x12\"\n" + + "\rlost_until_ns\x18\a \x01(\x03R\vlostUntilNs\x12\x19\n" + + "\bhead_gen\x18\b \x01(\x04R\aheadGen\x12 \n" + + "\fhead_time_ns\x18\t \x01(\x03R\n" + + "headTimeNs\x12&\n" + + "\x0fhead_time_known\x18\n" + + " \x01(\bR\rheadTimeKnown\"U\n" + + "\x17WorkspaceLostRangeQuery\x12\x1b\n" + + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1d\n" + + "\n" + + "request_id\x18\x02 \x01(\tR\trequestId\"Z\n" + + "\x13WorkspaceLostRanges\x12C\n" + + "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\x9d\x03\n" + + "\x14WorkspaceMovePreview\x12\x1a\n" + + "\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" + + "\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" + + "\rlost_until_ns\x18\x03 \x01(\x03R\vlostUntilNs\x12$\n" + + "\x0emaster_time_ns\x18\x04 \x01(\x03R\fmasterTimeNs\x12\x1b\n" + + "\thead_read\x18\x05 \x01(\bR\bheadRead\x12\x1d\n" + + "\n" + + "head_error\x18\x06 \x01(\tR\theadError\x12\x19\n" + + "\bhead_gen\x18\a \x01(\x04R\aheadGen\x12\x1d\n" + + "\n" + + "head_epoch\x18\b \x01(\x04R\theadEpoch\x12\x1f\n" + + "\vhead_holder\x18\t \x01(\tR\n" + + "headHolder\x12&\n" + + "\x0fhead_remote_lsn\x18\n" + + " \x01(\x04R\rheadRemoteLsn\x12 \n" + + "\fhead_time_ns\x18\v \x01(\x03R\n" + + "headTimeNs\x12&\n" + + "\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\"\xb2\x02\n" + "\x0fWorkspaceStatus\x12A\n" + "\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" + "\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" + @@ -818,7 +1228,7 @@ const file_workspace_proto_rawDesc = "" + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1b\n" + "\tserver_id\x18\x02 \x01(\tR\bserverId\x12\x1d\n" + "\n" + - "replica_id\x18\x03 \x01(\tR\treplicaId2\x81\x06\n" + + "replica_id\x18\x03 \x01(\tR\treplicaId2\xeb\a\n" + "\x10WorkspaceService\x12p\n" + "\x18RegisterWorkspaceBinding\x12).seaweedfs.block.control.WorkspaceBinding\x1a).seaweedfs.block.control.WorkspaceBinding\x12f\n" + "\x0ePlaceWorkspace\x12+.seaweedfs.block.control.WorkspacePlacement\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12n\n" + @@ -826,7 +1236,9 @@ const file_workspace_proto_rawDesc = "" + "\x0fRevokeWorkspace\x12*.seaweedfs.block.control.WorkspaceIdentity\x1a+.seaweedfs.block.control.WorkspaceLeaseFact\x12o\n" + "\x13AckWorkspaceRevoked\x12/.seaweedfs.block.control.WorkspaceRevocationAck\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12`\n" + "\rMoveWorkspace\x12&.seaweedfs.block.control.WorkspaceMove\x1a'.seaweedfs.block.control.WorkspaceGrant\x12d\n" + - "\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatusB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3" + "\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatus\x12y\n" + + "\x17QueryWorkspaceLostRange\x120.seaweedfs.block.control.WorkspaceLostRangeQuery\x1a,.seaweedfs.block.control.WorkspaceLostRanges\x12m\n" + + "\x14PreviewWorkspaceMove\x12&.seaweedfs.block.control.WorkspaceMove\x1a-.seaweedfs.block.control.WorkspaceMovePreviewB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3" var ( file_workspace_proto_rawDescOnce sync.Once @@ -840,44 +1252,54 @@ func file_workspace_proto_rawDescGZIP() []byte { return file_workspace_proto_rawDescData } -var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 10) +var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 14) var file_workspace_proto_goTypes = []any{ - (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity - (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume - (*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty - (*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact - (*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck - (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove - (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant - (*WorkspaceStatus)(nil), // 7: seaweedfs.block.control.WorkspaceStatus - (*WorkspaceBinding)(nil), // 8: seaweedfs.block.control.WorkspaceBinding - (*WorkspacePlacement)(nil), // 9: seaweedfs.block.control.WorkspacePlacement + (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity + (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume + (*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty + (*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact + (*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck + (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove + (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant + (*WorkspaceLostRange)(nil), // 7: seaweedfs.block.control.WorkspaceLostRange + (*WorkspaceLostRangeQuery)(nil), // 8: seaweedfs.block.control.WorkspaceLostRangeQuery + (*WorkspaceLostRanges)(nil), // 9: seaweedfs.block.control.WorkspaceLostRanges + (*WorkspaceMovePreview)(nil), // 10: seaweedfs.block.control.WorkspaceMovePreview + (*WorkspaceStatus)(nil), // 11: seaweedfs.block.control.WorkspaceStatus + (*WorkspaceBinding)(nil), // 12: seaweedfs.block.control.WorkspaceBinding + (*WorkspacePlacement)(nil), // 13: seaweedfs.block.control.WorkspacePlacement } var file_workspace_proto_depIdxs = []int32{ 0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity - 3, // 1: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact - 4, // 2: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck - 6, // 3: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant - 8, // 4: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding - 8, // 5: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding - 9, // 6: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement - 0, // 7: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity - 0, // 8: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity - 4, // 9: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck - 5, // 10: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove - 1, // 11: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume - 8, // 12: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding - 2, // 13: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty - 3, // 14: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 3, // 15: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 2, // 16: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty - 6, // 17: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant - 7, // 18: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus - 12, // [12:19] is the sub-list for method output_type - 5, // [5:12] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name + 7, // 1: seaweedfs.block.control.WorkspaceGrant.lost_range:type_name -> seaweedfs.block.control.WorkspaceLostRange + 7, // 2: seaweedfs.block.control.WorkspaceLostRanges.ranges:type_name -> seaweedfs.block.control.WorkspaceLostRange + 3, // 3: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact + 4, // 4: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck + 6, // 5: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant + 12, // 6: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding + 12, // 7: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding + 13, // 8: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement + 0, // 9: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity + 0, // 10: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity + 4, // 11: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck + 5, // 12: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove + 1, // 13: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume + 8, // 14: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:input_type -> seaweedfs.block.control.WorkspaceLostRangeQuery + 5, // 15: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:input_type -> seaweedfs.block.control.WorkspaceMove + 12, // 16: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding + 2, // 17: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty + 3, // 18: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 3, // 19: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 2, // 20: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty + 6, // 21: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant + 11, // 22: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus + 9, // 23: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:output_type -> seaweedfs.block.control.WorkspaceLostRanges + 10, // 24: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:output_type -> seaweedfs.block.control.WorkspaceMovePreview + 16, // [16:25] is the sub-list for method output_type + 7, // [7:16] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_workspace_proto_init() } @@ -891,7 +1313,7 @@ func file_workspace_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_proto_rawDesc), len(file_workspace_proto_rawDesc)), NumEnums: 0, - NumMessages: 10, + NumMessages: 14, NumExtensions: 0, NumServices: 1, }, diff --git a/seaweed-block/core/rpc/control/workspace_grpc.pb.go b/seaweed-block/core/rpc/control/workspace_grpc.pb.go index 25e43e9512..dd8830b5b7 100644 --- a/seaweed-block/core/rpc/control/workspace_grpc.pb.go +++ b/seaweed-block/core/rpc/control/workspace_grpc.pb.go @@ -26,6 +26,8 @@ const ( WorkspaceService_AckWorkspaceRevoked_FullMethodName = "/seaweedfs.block.control.WorkspaceService/AckWorkspaceRevoked" WorkspaceService_MoveWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/MoveWorkspace" WorkspaceService_QueryWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspace" + WorkspaceService_QueryWorkspaceLostRange_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspaceLostRange" + WorkspaceService_PreviewWorkspaceMove_FullMethodName = "/seaweedfs.block.control.WorkspaceService/PreviewWorkspaceMove" ) // WorkspaceServiceClient is the client API for WorkspaceService service. @@ -43,6 +45,13 @@ type WorkspaceServiceClient interface { AckWorkspaceRevoked(ctx context.Context, in *WorkspaceRevocationAck, opts ...grpc.CallOption) (*WorkspaceEmpty, error) MoveWorkspace(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceGrant, error) QueryWorkspace(ctx context.Context, in *WorkspaceVolume, opts ...grpc.CallOption) (*WorkspaceStatus, error) + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error) + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error) } type workspaceServiceClient struct { @@ -123,6 +132,26 @@ func (c *workspaceServiceClient) QueryWorkspace(ctx context.Context, in *Workspa return out, nil } +func (c *workspaceServiceClient) QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceLostRanges) + err := c.cc.Invoke(ctx, WorkspaceService_QueryWorkspaceLostRange_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *workspaceServiceClient) PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceMovePreview) + err := c.cc.Invoke(ctx, WorkspaceService_PreviewWorkspaceMove_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // WorkspaceServiceServer is the server API for WorkspaceService service. // All implementations must embed UnimplementedWorkspaceServiceServer // for forward compatibility. @@ -138,6 +167,13 @@ type WorkspaceServiceServer interface { AckWorkspaceRevoked(context.Context, *WorkspaceRevocationAck) (*WorkspaceEmpty, error) MoveWorkspace(context.Context, *WorkspaceMove) (*WorkspaceGrant, error) QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error) + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error) + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error) mustEmbedUnimplementedWorkspaceServiceServer() } @@ -169,6 +205,12 @@ func (UnimplementedWorkspaceServiceServer) MoveWorkspace(context.Context, *Works func (UnimplementedWorkspaceServiceServer) QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error) { return nil, status.Error(codes.Unimplemented, "method QueryWorkspace not implemented") } +func (UnimplementedWorkspaceServiceServer) QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error) { + return nil, status.Error(codes.Unimplemented, "method QueryWorkspaceLostRange not implemented") +} +func (UnimplementedWorkspaceServiceServer) PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error) { + return nil, status.Error(codes.Unimplemented, "method PreviewWorkspaceMove not implemented") +} func (UnimplementedWorkspaceServiceServer) mustEmbedUnimplementedWorkspaceServiceServer() {} func (UnimplementedWorkspaceServiceServer) testEmbeddedByValue() {} @@ -316,6 +358,42 @@ func _WorkspaceService_QueryWorkspace_Handler(srv interface{}, ctx context.Conte return interceptor(ctx, in, info, handler) } +func _WorkspaceService_QueryWorkspaceLostRange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspaceLostRangeQuery) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_QueryWorkspaceLostRange_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, req.(*WorkspaceLostRangeQuery)) + } + return interceptor(ctx, in, info, handler) +} + +func _WorkspaceService_PreviewWorkspaceMove_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspaceMove) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_PreviewWorkspaceMove_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, req.(*WorkspaceMove)) + } + return interceptor(ctx, in, info, handler) +} + // WorkspaceService_ServiceDesc is the grpc.ServiceDesc for WorkspaceService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -351,6 +429,14 @@ var WorkspaceService_ServiceDesc = grpc.ServiceDesc{ MethodName: "QueryWorkspace", Handler: _WorkspaceService_QueryWorkspace_Handler, }, + { + MethodName: "QueryWorkspaceLostRange", + Handler: _WorkspaceService_QueryWorkspaceLostRange_Handler, + }, + { + MethodName: "PreviewWorkspaceMove", + Handler: _WorkspaceService_PreviewWorkspaceMove_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "workspace.proto", diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index 0414ea99a2..5a227f6c79 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -13,6 +13,13 @@ service WorkspaceService { rpc AckWorkspaceRevoked(WorkspaceRevocationAck) returns (WorkspaceEmpty); rpc MoveWorkspace(WorkspaceMove) returns (WorkspaceGrant); rpc QueryWorkspace(WorkspaceVolume) returns (WorkspaceStatus); + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + rpc QueryWorkspaceLostRange(WorkspaceLostRangeQuery) returns (WorkspaceLostRanges); + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + rpc PreviewWorkspaceMove(WorkspaceMove) returns (WorkspaceMovePreview); } message WorkspaceIdentity { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; } message WorkspaceVolume { string volume_id = 1; } @@ -34,6 +41,32 @@ message WorkspaceGrant { string kind = 5; uint64 old_epoch = 6; uint64 new_epoch = 7; uint64 head_gen = 8; uint64 remote_lsn = 9; bool issued = 10; string old_host = 11; string new_host = 12; + // Forced grants only: the lost range stored before the issue (also on a + // replay). Absent on a forced grant means the readout is not proven, and + // lost_range_error says why; it never means "no loss". + WorkspaceLostRange lost_range = 13; + string lost_range_error = 14; +} +// What a forced move abandoned. head_gen 0: no published HEAD (everything the +// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read +// with HEAD at the move (1 s resolution), valid only when head_time_known. +// lost_until_ns is master time; the upper bound is a time, not an LSN. +message WorkspaceLostRange { + string request_id = 1; string volume_id = 2; uint64 new_epoch = 3; + string old_replica_id = 4; uint64 old_epoch = 5; + uint64 lost_after_lsn = 6; int64 lost_until_ns = 7; + uint64 head_gen = 8; int64 head_time_ns = 9; bool head_time_known = 10; +} +message WorkspaceLostRangeQuery { string volume_id = 1; string request_id = 2; } +message WorkspaceLostRanges { repeated WorkspaceLostRange ranges = 1; } +// lost_until_ns is when a forced move becomes admissible (0 if the master has +// no lease to judge). HEAD is read only when admitted, as for the move. +message WorkspaceMovePreview { + bool admitted = 1; string reason = 2; + int64 lost_until_ns = 3; int64 master_time_ns = 4; + bool head_read = 5; string head_error = 6; + uint64 head_gen = 7; uint64 head_epoch = 8; string head_holder = 9; uint64 head_remote_lsn = 10; + int64 head_time_ns = 11; bool head_time_known = 12; } message WorkspaceStatus { WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2; diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go new file mode 100644 index 0000000000..14370cfc09 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -0,0 +1,318 @@ +// Package wsclient is the operator client of the blockmaster workspace +// service for FORCED moves: the move itself, its read-only preview, and the +// lost-range readout. The sw-block CLI and other operator tools share it so +// the confirmation rule and the readout wording are the same everywhere. +// +// A forced move transfers AUTHORITY only. Starting the volume on the target +// is the next step, and nothing here bypasses the master's admission (lease +// horizon plus clock skew): there is no bypass. +package wsclient + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +// Outcome classifies a call's failure for the operator. +type Outcome int + +const ( + // OutcomeOK: the call succeeded. + OutcomeOK Outcome = iota + // OutcomeRefusedLocally: refused before any RPC (bad confirmation). + OutcomeRefusedLocally + // OutcomeRefused: the master answered with a definite refusal; nothing + // was moved by this call. + OutcomeRefused + // OutcomeUnknown: transport error or deadline; the move may or may not + // have been issued. Rerun with the SAME request id: the master replays + // an issued move's stored grant and never mints a second one. + OutcomeUnknown + // OutcomeReadoutUnproven: the lost range cannot be read (missing record + // or failed checks); it must never be reported as "no loss". + OutcomeReadoutUnproven +) + +// ErrConfirmation refuses a forced move locally: the confirmation must be +// exactly "@". +var ErrConfirmation = errors.New("forced move confirmation") + +// Error carries a classified failure. +type Error struct { + Outcome Outcome + Op string + Err error +} + +func (e *Error) Error() string { return e.Op + ": " + e.Err.Error() } +func (e *Error) Unwrap() error { return e.Err } + +// OutcomeOf returns err's outcome (OutcomeOK for nil). +func OutcomeOf(err error) Outcome { + if err == nil { + return OutcomeOK + } + var e *Error + if errors.As(err, &e) { + return e.Outcome + } + return OutcomeUnknown +} + +// classify maps a gRPC error: the master's definite answers are refusals, +// DataLoss is an unproven readout, anything else leaves the outcome unknown. +func classify(op string, err error) error { + if err == nil { + return nil + } + switch status.Code(err) { + case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.PermissionDenied, codes.Unimplemented: + return &Error{Outcome: OutcomeRefused, Op: op, Err: errors.New(status.Convert(err).Message())} + case codes.DataLoss: + return &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: errors.New(status.Convert(err).Message())} + } + return &Error{Outcome: OutcomeUnknown, Op: op, Err: err} +} + +// ParseConfirmation checks that confirm is exactly "@" for +// volume, with a positive decimal epoch, and returns that epoch: it is the +// expected epoch the move is sent with (the master refuses it unless it is +// the current one). +func ParseConfirmation(confirm, volume string) (uint64, error) { + if confirm == "" { + return 0, fmt.Errorf("%w: --confirm-forced %s@ is required", ErrConfirmation, volume) + } + at := strings.LastIndexByte(confirm, '@') + if at < 0 || confirm[:at] != volume { + return 0, fmt.Errorf("%w: %q does not name volume %q as %s@", ErrConfirmation, confirm, volume, volume) + } + digits := confirm[at+1:] + epoch, err := strconv.ParseUint(digits, 10, 64) + if err != nil || epoch == 0 || strconv.FormatUint(epoch, 10) != digits { + return 0, fmt.Errorf("%w: %q: the epoch must be a positive decimal number", ErrConfirmation, confirm) + } + return epoch, nil +} + +// ForcedMove names a forced move. TargetHost is the target node's server id. +type ForcedMove struct { + RequestID, VolumeID string + TargetHost, TargetDataAddr, TargetCtrlAddr string + // Confirm must be exactly "@". + Confirm string +} + +// Client calls the workspace service. +type Client struct { + rpc control.WorkspaceServiceClient + conn *grpc.ClientConn +} + +// New wraps an existing service client. +func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc} } + +// Dial connects to the blockmaster gRPC address (plaintext, as the other +// operator commands). +func Dial(addr string) (*Client, error) { + conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + return &Client{rpc: control.NewWorkspaceServiceClient(conn), conn: conn}, nil +} + +// Close closes a Dial connection. +func (c *Client) Close() error { + if c.conn == nil { + return nil + } + return c.conn.Close() +} + +// request checks the confirmation (no RPC on failure), resolves the +// holder's logical replica id at the confirmed epoch from QueryWorkspace +// (v1 keeps the replica id across moves) and builds the forced request. +func (c *Client) request(ctx context.Context, op string, m ForcedMove) (*control.WorkspaceMove, error) { + epoch, err := ParseConfirmation(m.Confirm, m.VolumeID) + if err != nil { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: err} + } + if m.RequestID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("a request id, target host and target data/ctrl addresses are required")} + } + st, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: m.VolumeID}) + if err != nil { + e := classify(op+": read the volume's holder", err) + var ce *Error + if errors.As(e, &ce) && ce.Outcome == OutcomeUnknown { + ce.Err = fmt.Errorf("no move was sent: %w", ce.Err) + } + return nil, e + } + replica := holderAt(st, epoch) + if replica == "" { + cur := "none" + if l := st.GetLease(); l != nil { + cur = fmt.Sprintf("%s@%d", l.GetReplicaId(), l.GetEpoch()) + } + return nil, &Error{Outcome: OutcomeRefused, Op: op, Err: fmt.Errorf("the master knows no holder of volume %q at epoch %d (current lease: %s); nothing was sent", m.VolumeID, epoch, cur)} + } + return &control.WorkspaceMove{RequestId: m.RequestID, VolumeId: m.VolumeID, ExpectedReplicaId: replica, ExpectedEpoch: epoch, TargetReplicaId: replica, + TargetServerId: m.TargetHost, TargetDataAddr: m.TargetDataAddr, TargetCtrlAddr: m.TargetCtrlAddr, Kind: "forced", Force: true}, nil +} + +// holderAt returns the logical replica id that held the volume at epoch: +// the current lease, or the journal (an issued move from or to that epoch, +// e.g. on a rerun after the move issued). +func holderAt(st *control.WorkspaceStatus, epoch uint64) string { + if l := st.GetLease(); l != nil && l.GetEpoch() == epoch && l.GetReplicaId() != "" { + return l.GetReplicaId() + } + for _, g := range st.GetMoves() { + if g.GetOldEpoch() == epoch && g.GetOldReplicaId() != "" { + return g.GetOldReplicaId() + } + if g.GetIssued() && g.GetNewEpoch() == epoch && g.GetNewReplicaId() != "" { + return g.GetNewReplicaId() + } + } + return "" +} + +// ForceMove sends the forced move (kind forced, force true) only when the +// confirmation matches. On success the grant is issued; its stored lost +// range is grant.LostRange, and when that is absent the error is +// OutcomeReadoutUnproven with the grant still returned. +func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.WorkspaceGrant, error) { + const op = "forced move" + q, err := c.request(ctx, op, m) + if err != nil { + return nil, err + } + g, err := c.rpc.MoveWorkspace(ctx, q) + if err != nil { + return nil, classify(op, err) + } + if err := checkGrant(g, q); err != nil { + return g, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)} + } + if err := checkRange(g.GetLostRange(), g); err != nil { + return g, &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: err} + } + return g, nil +} + +// checkGrant binds a successful answer to the request that was sent: an +// issued forced grant for this request id and volume, from the expected +// holder at the expected epoch to the requested target, at a higher epoch. +// Anything else leaves the outcome unknown. +func checkGrant(g *control.WorkspaceGrant, q *control.WorkspaceMove) error { + if !g.GetIssued() || g.GetKind() != "forced" || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() || + g.GetOldReplicaId() != q.GetExpectedReplicaId() || g.GetOldEpoch() != q.GetExpectedEpoch() || + g.GetNewReplicaId() != q.GetTargetReplicaId() || g.GetNewHost() != q.GetTargetServerId() || g.GetNewEpoch() <= g.GetOldEpoch() { + return fmt.Errorf("the answer does not match the request (issued=%t kind=%q request=%q volume=%q old=%s@%d new=%s@%d on %q)", + g.GetIssued(), g.GetKind(), g.GetRequestId(), g.GetVolumeId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost()) + } + return nil +} + +// checkRange: a forced grant must carry its own stored range, naming the +// same move and the same kept HEAD (generation and frontier). +func checkRange(r *control.WorkspaceLostRange, g *control.WorkspaceGrant) error { + if r == nil { + why := g.GetLostRangeError() + if why == "" { + why = "the master returned no lost range" + } + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but the lost range is not proven: %s", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), why) + } + if r.GetRequestId() != g.GetRequestId() || r.GetVolumeId() != g.GetVolumeId() || r.GetNewEpoch() != g.GetNewEpoch() || r.GetOldEpoch() != g.GetOldEpoch() || r.GetOldReplicaId() != g.GetOldReplicaId() { + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range names another move (volume %q request %q epoch %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetVolumeId(), r.GetRequestId(), r.GetNewEpoch()) + } + if r.GetHeadGen() != g.GetHeadGen() || r.GetLostAfterLsn() != g.GetRemoteLsn() { + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range disagrees with the kept HEAD (range gen %d LSN %d, grant gen %d LSN %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetHeadGen(), r.GetLostAfterLsn(), g.GetHeadGen(), g.GetRemoteLsn()) + } + return nil +} + +// PreviewForcedMove asks the master whether the forced move is admitted +// now, writing nothing. The confirmation is checked as for the move (the +// preview is evaluated at its epoch), but a preview never stands in for it. +func (c *Client) PreviewForcedMove(ctx context.Context, m ForcedMove) (*control.WorkspaceMovePreview, error) { + const op = "forced move preview" + q, err := c.request(ctx, op, m) + if err != nil { + return nil, err + } + p, err := c.rpc.PreviewWorkspaceMove(ctx, q) + return p, classify(op, err) +} + +// previewMove is PreviewForcedMove for an already built request. +func (c *Client) previewMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + p, err := c.rpc.PreviewWorkspaceMove(ctx, q) + return p, classify("forced move preview", err) +} + +// AdmissibleAt asks the preview for when a refused forced move becomes +// admissible; ok is false when the preview cannot tell (admitted already, +// no lease, or the preview failed). +func (c *Client) AdmissibleAt(ctx context.Context, m ForcedMove) (at time.Time, ok bool) { + q, err := c.request(ctx, "forced move preview", m) + if err != nil { + return time.Time{}, false + } + p, err := c.previewMove(ctx, q) + if err != nil || p.GetLostUntilNs() == 0 || p.GetLostUntilNs() <= p.GetMasterTimeNs() { + return time.Time{}, false + } + return time.Unix(0, p.GetLostUntilNs()), true +} + +// LostRanges returns the stored lost ranges of the volume's issued forced +// moves in issue order, or requestID's only. A missing or unreadable record +// is OutcomeReadoutUnproven. +func (c *Client) LostRanges(ctx context.Context, volume, requestID string) ([]*control.WorkspaceLostRange, error) { + r, err := c.rpc.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: volume, RequestId: requestID}) + if err != nil { + return nil, classify("lost range", err) + } + for _, x := range r.GetRanges() { + if x.GetVolumeId() != volume || (requestID != "" && x.GetRequestId() != requestID) { + return nil, &Error{Outcome: OutcomeReadoutUnproven, Op: "lost range", Err: fmt.Errorf("the answer names another range (volume %q request %q)", x.GetVolumeId(), x.GetRequestId())} + } + } + return r.GetRanges(), nil +} + +// HeadTimeClock labels a HEAD time: the filer entry's mtime, which the +// host that published the HEAD sets from its own clock. +const HeadTimeClock = "(publishing host clock as recorded in the filer, 1 s resolution)" + +// FormatTime prints a master or filer time. +func FormatTime(ns int64) string { return time.Unix(0, ns).UTC().Format(time.RFC3339Nano) } + +// Readout is the operator sentence for a stored lost range of volume. +func Readout(volume string, r *control.WorkspaceLostRange) string { + old := fmt.Sprintf("%s@%d", r.GetOldReplicaId(), r.GetOldEpoch()) + if r.GetHeadGen() == 0 { + return fmt.Sprintf("no remote image exists: everything written by %s is lost.", old) + } + at := "an unknown time (no filer time was recorded)" + if r.GetHeadTimeKnown() { + at = FormatTime(r.GetHeadTimeNs()) + " " + HeadTimeClock + } + return fmt.Sprintf("volume %s restored to the last published image at %s (gen %d, LSN %d): writes with LSN <= %d are preserved; "+ + "writes acknowledged by %s after that and before %s, master clock, may be lost; the upper bound is a time, not an LSN.", + volume, at, r.GetHeadGen(), r.GetLostAfterLsn(), r.GetLostAfterLsn(), old, FormatTime(r.GetLostUntilNs())) +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient_test.go b/seaweed-block/core/rpc/wsclient/wsclient_test.go new file mode 100644 index 0000000000..2d1c9fdbf9 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/wsclient_test.go @@ -0,0 +1,224 @@ +package wsclient + +import ( + "context" + "errors" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// fakeRPC answers QueryWorkspace and MoveWorkspace and counts every call. +type fakeRPC struct { + control.WorkspaceServiceClient // nil: other methods panic + calls int + status *control.WorkspaceStatus + moves []*control.WorkspaceMove + grant *control.WorkspaceGrant + moveErr error +} + +func (f *fakeRPC) QueryWorkspace(context.Context, *control.WorkspaceVolume, ...grpc.CallOption) (*control.WorkspaceStatus, error) { + f.calls++ + return f.status, nil +} + +func (f *fakeRPC) MoveWorkspace(_ context.Context, q *control.WorkspaceMove, _ ...grpc.CallOption) (*control.WorkspaceGrant, error) { + f.calls++ + f.moves = append(f.moves, q) + return f.grant, f.moveErr +} + +// INV-WS-FORCED-CONFIRM-001: the confirmation is exactly @. +func TestParseConfirmation(t *testing.T) { + for _, tc := range []struct { + confirm, volume string + epoch uint64 + }{ + {"vol@3", "vol", 3}, + {"a@b@7", "a@b", 7}, + {"", "vol", 0}, + {"vol", "vol", 0}, + {"vol@", "vol", 0}, + {"other@3", "vol", 0}, + {"vol@0", "vol", 0}, + {"vol@03", "vol", 0}, + {"vol@+3", "vol", 0}, + {"vol@-3", "vol", 0}, + {"vol@3 ", "vol", 0}, + {" vol@3", "vol", 0}, + {"VOL@3", "vol", 0}, + } { + got, err := ParseConfirmation(tc.confirm, tc.volume) + if got != tc.epoch || (err == nil) != (tc.epoch != 0) || (err != nil && !errors.Is(err, ErrConfirmation)) { + t.Errorf("ParseConfirmation(%q, %q) = %d, %v; want %d", tc.confirm, tc.volume, got, err, tc.epoch) + } + } +} + +var testMove = ForcedMove{RequestID: "req-1", VolumeID: "vol", TargetHost: "node-b", TargetDataAddr: "10.0.0.2:1", TargetCtrlAddr: "10.0.0.2:2", Confirm: "vol@3"} + +// INV-WS-FORCED-CONFIRM-001: force:true is sent only with a matching +// confirmation, and then always with kind forced and the confirmed epoch. +func TestForceMoveSendsForceOnlyWithTheConfirmation(t *testing.T) { + for _, bad := range []string{"", "vol@x", "other@3", "vol@0"} { + f := &fakeRPC{} + m := testMove + m.Confirm = bad + if _, err := New(f).ForceMove(context.Background(), m); OutcomeOf(err) != OutcomeRefusedLocally || f.calls != 0 { + t.Fatalf("confirmation %q: %v after %d RPCs; want a local refusal and none", bad, err, f.calls) + } + } + f := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, moveErr: status.Error(codes.FailedPrecondition, "not yet")} + if _, err := New(f).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused { + t.Fatalf("master refusal: %v", err) + } + q := f.moves[0] + if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" || q.TargetServerId != "node-b" { + t.Fatalf("sent %+v", f.moves) + } +} + +// The holder's replica id at the confirmed epoch comes from the lease, or +// on a rerun after the issue from the journal; an epoch the master never +// had is refused without sending a move. +func TestForceMoveResolvesTheHolder(t *testing.T) { + rerun := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 4}, + Moves: []*control.WorkspaceGrant{{RequestId: "req-1", OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4, Issued: true, Kind: "forced"}}}, moveErr: status.Error(codes.Unavailable, "down")} + if _, err := New(rerun).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown || len(rerun.moves) != 1 || rerun.moves[0].ExpectedReplicaId != "r1" { + t.Fatalf("rerun: %v %+v", err, rerun.moves) + } + stale := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 9}}} + if _, err := New(stale).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused || len(stale.moves) != 0 { + t.Fatalf("stale epoch: %v, %d moves sent", err, len(stale.moves)) + } +} + +// goodGrant is the issued forced grant for testMove with its own range. +func goodGrant() *control.WorkspaceGrant { + return &control.WorkspaceGrant{RequestId: "req-1", VolumeId: "vol", Kind: "forced", Issued: true, OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4, + OldHost: "node-a", NewHost: "node-b", HeadGen: 9, RemoteLsn: 42, + LostRange: &control.WorkspaceLostRange{RequestId: "req-1", VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: 1, HeadGen: 9}} +} + +func holderAt3() *control.WorkspaceStatus { + return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 3}} +} + +// A forced grant without its own stored range is issued but unproven. +func TestForceMoveGrantWithoutRangeIsUnproven(t *testing.T) { + g := goodGrant() + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); err != nil { + t.Fatalf("own range: %v", err) + } + g.LostRange = nil + got, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove) + if OutcomeOf(err) != OutcomeReadoutUnproven || got != g { + t.Fatalf("no range: %v", err) + } +} + +// The answer is bound to the request: each identity field of the grant +// corrupted on its own leaves the outcome unknown; each identity or +// frontier field of the range corrupted on its own leaves the readout +// unproven. Neither ever yields a successful readout. +func TestForceMoveBindsGrantAndRange(t *testing.T) { + grantFaults := map[string]func(*control.WorkspaceGrant){ + "not issued": func(g *control.WorkspaceGrant) { g.Issued = false }, + "kind": func(g *control.WorkspaceGrant) { g.Kind = "clean" }, + "request": func(g *control.WorkspaceGrant) { g.RequestId = "req-2" }, + "volume": func(g *control.WorkspaceGrant) { g.VolumeId = "vol2" }, + "old replica": func(g *control.WorkspaceGrant) { g.OldReplicaId = "r2" }, + "old epoch": func(g *control.WorkspaceGrant) { g.OldEpoch = 2 }, + "new replica": func(g *control.WorkspaceGrant) { g.NewReplicaId = "r2" }, + "target host": func(g *control.WorkspaceGrant) { g.NewHost = "node-c" }, + "epoch not up": func(g *control.WorkspaceGrant) { g.NewEpoch = 3 }, + } + for name, fault := range grantFaults { + g := goodGrant() + fault(g) + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown { + t.Errorf("grant %s corrupted: %v; want unknown", name, err) + } + } + rangeFaults := map[string]func(*control.WorkspaceLostRange){ + "request": func(r *control.WorkspaceLostRange) { r.RequestId = "req-2" }, + "volume": func(r *control.WorkspaceLostRange) { r.VolumeId = "vol2" }, + "new epoch": func(r *control.WorkspaceLostRange) { r.NewEpoch = 5 }, + "old epoch": func(r *control.WorkspaceLostRange) { r.OldEpoch = 2 }, + "old replica": func(r *control.WorkspaceLostRange) { r.OldReplicaId = "r2" }, + "head gen": func(r *control.WorkspaceLostRange) { r.HeadGen = 8 }, + "lost after": func(r *control.WorkspaceLostRange) { r.LostAfterLsn = 41 }, + } + for name, fault := range rangeFaults { + g := goodGrant() + fault(g.LostRange) + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Errorf("range %s corrupted: %v; want unproven", name, err) + } + } +} + +// lostRangeRPC answers QueryWorkspaceLostRange with fixed ranges. +type lostRangeRPC struct { + control.WorkspaceServiceClient + ranges []*control.WorkspaceLostRange +} + +func (f *lostRangeRPC) QueryWorkspaceLostRange(context.Context, *control.WorkspaceLostRangeQuery, ...grpc.CallOption) (*control.WorkspaceLostRanges, error) { + return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil +} + +// A lost-range answer that names another volume or request is unproven. +func TestLostRangesBindsTheAnswer(t *testing.T) { + r := goodGrant().LostRange + if got, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-1"); err != nil || len(got) != 1 { + t.Fatalf("matching answer: %v", err) + } + if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "other", ""); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Fatalf("another volume: %v", err) + } + if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-9"); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Fatalf("another request: %v", err) + } +} + +func TestClassify(t *testing.T) { + for code, want := range map[codes.Code]Outcome{ + codes.FailedPrecondition: OutcomeRefused, codes.NotFound: OutcomeRefused, codes.DataLoss: OutcomeReadoutUnproven, + codes.Unavailable: OutcomeUnknown, codes.DeadlineExceeded: OutcomeUnknown, codes.Canceled: OutcomeUnknown, codes.Internal: OutcomeUnknown, + } { + if got := OutcomeOf(classify("op", status.Error(code, "x"))); got != want { + t.Errorf("%v: %v; want %v", code, got, want) + } + } + if OutcomeOf(classify("op", context.DeadlineExceeded)) != OutcomeUnknown { + t.Error("a bare deadline is not unknown") + } +} + +// INV-WS-LOST-RANGE-READOUT-001: the readout wording (ruling A: HEAD time is +// the filer time; the upper bound is master time). +func TestReadoutWording(t *testing.T) { + r := &control.WorkspaceLostRange{OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: time.Date(2026, 11, 21, 1, 5, 0, 5, time.UTC).UnixNano(), + HeadGen: 9, HeadTimeNs: time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC).UnixNano(), HeadTimeKnown: true} + want := "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN." + if got := Readout("vol", r); got != want { + t.Fatalf("readout\n got %s\nwant %s", got, want) + } + r.HeadTimeKnown = false + want = "volume vol restored to the last published image at an unknown time (no filer time was recorded) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN." + if got := Readout("vol", r); got != want { + t.Fatalf("readout, time unknown\n got %s\nwant %s", got, want) + } + r.HeadGen = 0 + if got := Readout("vol", r); got != "no remote image exists: everything written by r1@3 is lost." { + t.Fatalf("no-HEAD readout: %s", got) + } +} diff --git a/seaweed-block/core/storage/base_install_reopen_v3_test.go b/seaweed-block/core/storage/base_install_reopen_v3_test.go index d2db295dc8..132b3b6f71 100644 --- a/seaweed-block/core/storage/base_install_reopen_v3_test.go +++ b/seaweed-block/core/storage/base_install_reopen_v3_test.go @@ -6,7 +6,7 @@ import ( "testing" ) -// Plan row 11a controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// Install-reopen controls: // a covering superseding begin after an installing reopen. // installThenCrashV3 begins install A at BaseLSN 10 over two acknowledged diff --git a/seaweed-block/core/storage/base_install_resume_v3_test.go b/seaweed-block/core/storage/base_install_resume_v3_test.go index 8c21abac9d..0637dd5449 100644 --- a/seaweed-block/core/storage/base_install_resume_v3_test.go +++ b/seaweed-block/core/storage/base_install_resume_v3_test.go @@ -7,7 +7,7 @@ import ( "testing" ) -// Plan row 11b controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// Install-resume controls: // the same-ID resume after an installing reopen. // An intact reopen (W 2 <= R 11; record 12 damaged, 13 beyond the gap) @@ -65,7 +65,7 @@ func TestBaseInstallV3ResumeRefusesADamagedSuffix(t *testing.T) { } } -// E below the persisted retainedHead (codex03 r17 check): the head was +// E below the persisted retainedHead: the head was // published past LSN 13 (white-box, as an earlier same-open recovery // would), then 13 is damaged, so the reopen's E ends after 12, below the // head. The resume is refused (E >= head is part of trusted-through-W). A @@ -121,9 +121,9 @@ func TestBaseInstallV3EBelowThePersistedHead(t *testing.T) { } } -// codex01 row 11b P1: a same-open Recover while this open's install is live +// A same-open Recover while this open's install is live // must not leave a resumable cut behind. The old handle stays valid -// (r17.4) and applies and acknowledges LSN 12 after the Recover; a resume +// and applies and acknowledges LSN 12 after the Recover; a resume // then refuses before any I/O, so the acknowledged record's bytes are // unchanged, and a crash and a physical reopen still resume the same ID and // serve LSN 12. Mutant: recording the recovered bounds on a same-open @@ -191,7 +191,7 @@ func readRawV3(t *testing.T, path string, off int64, n int) []byte { return b } -// codex01 04180c33 P1 (live continuation): BASE writes LBA 1 = B0, then the +// Live continuation: BASE writes LBA 1 = B0, then the // install lane applies and acknowledges LSN 11 at LBA 1; a same-open // Recover clears the dirty map; the ORIGINAL handle then applies and // acknowledges LSN 12 at LBA 2 and completes; reads in the same open must diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index dba6fb0aaa..c251b58cde 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -134,7 +134,7 @@ type installHandleV3 struct { // completed is set once this handle's own MarkBaseComplete succeeded: // the session's WAL lane may still be sending (the Sender sends BaseDone // from its base lane), so install-lane applies stay admitted until the - // next begin (codex01 row 9b P1). + // next begin. completed atomic.Bool } @@ -203,7 +203,7 @@ func (s *WALStore) beginBaseInstallV3(baseLSN uint64, id [16]byte) (*installHand // BaseLSN must also cover every appended LSN: an unacknowledged record // above BaseLSN would lie behind BaseCursor, so recovery from // max(CheckpointLSN, BaseLSN) would meet a hole where the allocator - // continued (codex01 row 9a P1-1). Such a begin is refused, writing + // continued. Such a begin is refused, writing // nothing; the records are never rewound or dropped to make room. w := max(d.W, v.wack.Load()) appended := v.appended.Load() @@ -448,7 +448,7 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane // a checkpoint does: one fsync for the BASE extent bytes and the // install-lane suffix (they share the file), the optional metadata and // chunk barriers, and a fresh owned-map candidate that carries the UNKNOWN -// coverage the BASE writes set (codex01 row 9a P1-2). It then publishes +// coverage the BASE writes set. It then publishes // installed with the same ID and that candidate in one publication // (retainedTail = max(retainedTail, P), 8.4), stops serving the superseded // pre-BASE records and moves the frontier to BaseLSN. A guest write that diff --git a/seaweed-block/core/storage/base_install_v3_test.go b/seaweed-block/core/storage/base_install_v3_test.go index 5e1c9311a5..8479271a72 100644 --- a/seaweed-block/core/storage/base_install_v3_test.go +++ b/seaweed-block/core/storage/base_install_v3_test.go @@ -10,9 +10,9 @@ import ( "time" ) -// Plan row 9a controls (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7): +// BASE install controls: // the v3 BASE begin, the install handle, complete, no abort and retirement. -// Owner: claude03. Each control names the mutant it qualifies. +// Each control names the mutant it qualifies. var ( idA = [16]byte{0xA} @@ -244,8 +244,7 @@ func TestBaseInstallV3ApplyInstallEntryOrderAndGap(t *testing.T) { // holdOnce returns a hook that parks the first call until release runs, // and reports through parked when it has parked. The test's cleanup always -// releases, so a failing test never leaves a parked goroutine behind -// (codex01 row 9a P2). +// releases, so a failing test never leaves a parked goroutine behind. func holdOnce(t *testing.T) (hook func(), parked chan struct{}, release func()) { parked = make(chan struct{}) gate := make(chan struct{}) @@ -262,7 +261,7 @@ func holdOnce(t *testing.T) (hook func(), parked chan struct{}, release func()) }, parked, release } -// Drain setup, held inside the mutation (plan row 9, codex01 r12 P2): +// Drain setup, held inside the mutation: // A's admitted write is held; B's begin waits for it; B then writes the // target block and stays installing; a further A attempt is refused with // B's block byte-identical. Mutants: begin taking installMu shared (A's @@ -316,8 +315,8 @@ func TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin(t *testing.T) { } } -// Premature-check setup, parked before admission (codex03 r11, plan row -// 9): A parks before acquiring installMu; B supersedes, writes the target +// Premature-check setup, parked before admission: +// A parks before acquiring installMu; B supersedes, writes the target // block and stays installing; A resumes and is refused under the lock. // Mutants: checking the ID before acquiring installMu, and no ID check. func TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession(t *testing.T) { @@ -355,7 +354,7 @@ func TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession(t *testing.T) { } } -// codex01 row 9a P1-1: W 1 with unacknowledged LSNs 2 and 3 appended. A +// W 1 with unacknowledged LSNs 2 and 3 appended. A // begin at BaseLSN 1 would put 2 and 3 behind BaseCursor while the // allocator continues at 4: after complete, an acknowledged write 4 and a // reopen from F = 1 meet the hole (strict: R 1 < W 4; lagged: 4 dropped). @@ -407,7 +406,7 @@ func TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN(t *testing.T) { } } -// codex01 row 9a P1-2: a BASE write makes its chunk's coverage UNKNOWN only +// A BASE write makes its chunk's coverage UNKNOWN only // in memory. Complete settles the map like a checkpoint: the installed // publication carries a fresh root with that UNKNOWN, so a crash and a // mapped reopen keep it. Setup: chunk 2 is clean in the durable root (as a @@ -473,7 +472,7 @@ func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing } } -// codex01 row 9b P1, store part: a completed handle keeps admitting +// Store side: a completed handle keeps admitting // install-lane applies (the session's WAL lane outlives its BaseDone) while // installed and after its retirement, until the next begin; a BASE write // after complete is refused; once a later begin has run (here after the diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index a5d79f6fbf..34b469a152 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -121,3 +121,90 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) { assertEveryHeadIsPrefixImage(t, f, w) assertNoIntentsLeft(t, f) } + +// Each of two deadlines interrupts the third upload, after two immutable chunks +// completed. The next pass must reuse those chunks rather than restart the set. +type deadlineProgressRemote struct { + successful map[string][]byte + *fakeChunkRemote + completed int + calls int +} + +func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error { + r.calls++ + if r.completed == 2 { + <-ctx.Done() + return ctx.Err() + } + err := r.fakeChunkRemote.Put(ctx, key, b) + if err == nil { + r.completed++ + if _, exists := r.successful[key]; exists { + return errors.New("test: retransmitted unchanged successful key") + } + if r.successful == nil { + r.successful = map[string][]byte{} + } + r.successful[key] = append([]byte(nil), b...) + } + return err +} +func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 5) + l.cfg.COWSpillLimit = ctChunkBytes + l.cfg.UploadConcurrency = 1 + r := &deadlineProgressRemote{fakeChunkRemote: f} + l.remote = r + base := f.stats().head.Gen + previous := 0 + lastSubmitted := s.NextLSN() - 1 + expectedImage := w.imageAt(lastSubmitted) + var finalHead chunkHead + 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() + if pass < 2 { + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("pass %d did not reach injected deadline: %v", pass, err) + } + if f.stats().head.Gen != base { + t.Fatal("deadline moved HEAD") + } + l.stMu.Lock() + cached := len(l.reusable) + l.stMu.Unlock() + if cached <= previous { + t.Fatalf("pass %d restarted dirty set: cached=%d previous=%d", pass, cached, previous) + } + previous = cached + } else if err != nil || result.Head.Gen != base+1 { + t.Fatalf("third pass failed to publish: %+v %v", result, err) + } else { + finalHead = result.Head + } + } + // Five changed chunks, five successful puts, no retransmission after expiry. + if len(r.successful) != 5 { + t.Fatalf("successful upload keys=%d want5", len(r.successful)) + } + totalBytes := 0 + for _, payload := range r.successful { + totalBytes += len(payload) + } + if totalBytes != 5*ctChunkBytes { + t.Fatalf("uploaded bytes=%d want%d", totalBytes, 5*ctChunkBytes) + } + assertEveryHeadIsPrefixImage(t, f, w) + if finalHead.RemoteLSN != lastSubmitted { + t.Fatalf("final frontier=%d want last submitted=%d", finalHead.RemoteLSN, lastSubmitted) + } + assertImage(t, "final complete submitted image", f.imageOf(t, finalHead), expectedImage) + if previous != 4 { + t.Fatalf("reusable chunks=%d", previous) + } + assertNoIntentsLeft(t, f) +} diff --git a/seaweed-block/core/storage/chunk_frontier_v3_test.go b/seaweed-block/core/storage/chunk_frontier_v3_test.go index c965d17fc0..d4f5c4859c 100644 --- a/seaweed-block/core/storage/chunk_frontier_v3_test.go +++ b/seaweed-block/core/storage/chunk_frontier_v3_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -// Plan row 9c controls (owner claude03): SeedChunkFrontier on a dark v3 +// Chunk-frontier controls: SeedChunkFrontier on a dark v3 // store uses the checkpoint's map/metadata barrier and the sole descriptor // publication (publishCheckpointV3), never the legacy superblock writer. diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go new file mode 100644 index 0000000000..5655491ec5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -0,0 +1,247 @@ +package storage + +import ( + "context" + "errors" + "sync" + "time" +) + +// HydrateProgress reports one HydrateAll call. +// - Filled: chunks this call made local. +// - Remaining: chunks still absent (HEAD-named, with a block not written +// locally) when the call returned; 0 means the volume is fully local. +// - Paused: times the walker yielded to guest read misses. +// - Deferred: times the host limiter refused a fill (retried later). +type HydrateProgress struct { + Filled int + Remaining int + Paused uint64 + Deferred uint64 +} + +// Walker pacing: a guest wait or a refused fill is retried after a short +// backoff that doubles up to the cap. +var ( + hydrateAllMinBackoff = 20 * time.Millisecond + hydrateAllMaxBackoff = 2 * time.Second +) + +// HydrateAll makes every chunk local that HEAD names and the volume does not +// hold yet (an independent restore's background hydrate). It walks +// the absent chunks lowest index first through the same shared fill flights +// as guest read misses (one fetch per chunk, the hydration queue bound and +// the read-miss timeout apply), so it never fetches a chunk twice or races a +// guest fill. It yields while any flight has guest waiters; its own flights +// have no waiters, so workers serve guest flights first. +// +// Each fill holds one host-limiter permit (cfg.Budget), admitted with ctx and +// no cut payload, the background fill/idle contract (hostlimit Acquire): the +// caller sets the class on ctx (hostlimit.WithClass(ctx, +// hostlimit.BackgroundFill)). The permit belongs to the flight, not the wait: +// it is released only when the flight's I/O is over, also when the walker +// returns early on cancellation, revocation or close. The limiter's abort +// callback (revocation) stops the walker, which then returns the cause. +// +// It returns when nothing is absent, when ctx ends or the permit is revoked, +// 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) { + var p HydrateProgress + walk, stop := context.WithCancelCause(ctx) + defer stop(nil) + backoff := hydrateAllMinBackoff + quit := func(err error) (HydrateProgress, error) { + p.Remaining = l.absentHydratable() + return p, err + } + wait := func() error { + t := time.NewTimer(backoff) + defer t.Stop() + if backoff *= 2; backoff > hydrateAllMaxBackoff { + backoff = hydrateAllMaxBackoff + } + select { + case <-t.C: + return nil + case <-walk.Done(): + return context.Cause(walk) + case <-l.ctx.Done(): + return errChunkLayerClosed + } + } + for { + if walk.Err() != nil { + return quit(context.Cause(walk)) + } + lba, ok, guests := l.nextHydrateTarget() + if !ok { + p.Remaining = 0 + return p, nil + } + if guests > 0 { + p.Paused++ + if hook := l.testHydrateAllPause; hook != nil { + hook() + } + if err := wait(); err != nil { + return quit(err) + } + continue + } + release, err := l.admitFill(walk, stop) + if err != nil { + p.Deferred++ + if err := wait(); err != nil { + return quit(err) + } + continue + } + f, err := l.startWalkerFill(lba, release) + if err != nil { + if errors.Is(err, ErrChunkHydrationPending) { + if err := wait(); err != nil { // queue full: retry later + return quit(err) + } + continue + } + return quit(err) + } + if f == nil { + continue // resolved meanwhile + } + select { + case <-f.done: + case <-walk.Done(): + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + return quit(errChunkLayerClosed) + } + l.stMu.Lock() + changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref + ferr := f.err + l.stMu.Unlock() + switch { + case changed: + // a newer absence or HEAD: the next pass looks again + case ferr == nil: + p.Filled++ + backoff = hydrateAllMinBackoff + case errors.Is(ferr, ErrChunkHydrationPending): + if err := wait(); err != nil { // the read-miss timeout: retry later + return quit(err) + } + default: + return quit(ferr) + } + } +} + +// startWalkerFill queues (or joins) the fill flight of lba's chunk without +// becoming a waiter, and hands the permit's release to the flight's +// settlement: a layer-owned goroutine releases it once the flight's I/O is +// over, whatever the walker does meanwhile. A nil flight means nothing is to +// fetch any more (release already called). +func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydrationFlight, error) { + idx := l.chunkOf(lba) + l.stMu.Lock() + defer l.stMu.Unlock() + if l.closed { + release() + return nil, errChunkLayerClosed + } + ref, named := l.head.Chunks[idx] + if !l.absent[idx] || l.localBlocks[lba] || !named { + release() + return nil, nil + } + f, _, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + release() + return nil, err + } + l.wakeHydrationLocked() + // Close joins wg only after taking stMu and marking closed; every queued + // flight is settled by closeHydrationLocked, every running one by its worker. + l.wg.Add(1) + go func() { + defer l.wg.Done() + <-f.settled + release() + }() + return f, nil +} + +// nextHydrateTarget returns a block of the lowest-index chunk that HEAD names, +// is absent and has a block without a local extent version (localBlocks: a +// chunk whose every block reached the extent needs no fetch; a write still only +// in the WAL does not count, and the fill never overwrites it), and the number +// of flights that have guest waiters. +func (l *chunkLayerImpl) nextHydrateTarget() (lba uint64, ok bool, guests int) { + l.stMu.Lock() + defer l.stMu.Unlock() + for _, f := range l.hydration { + if f.waiters > 0 { + guests++ + } + } + best := uint64(0) + for idx := range l.absent { + if !l.absent[idx] || (ok && idx >= best) { + continue + } + if b, has := l.hydratableBlockLocked(idx); has { + best, lba, ok = idx, b, true + } + } + return lba, ok, guests +} + +// absentHydratable counts the chunks nextHydrateTarget would still visit. +func (l *chunkLayerImpl) absentHydratable() int { + l.stMu.Lock() + defer l.stMu.Unlock() + n := 0 + for idx, absent := range l.absent { + if _, has := l.hydratableBlockLocked(idx); absent && has { + n++ + } + } + return n +} + +// hydratableBlockLocked returns a block of chunk idx that is not written +// locally, if HEAD names the chunk. Caller holds stMu. +func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { + if _, named := l.head.Chunks[idx]; !named { + return 0, false + } + 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 b, true + } + } + return 0, false +} + +// admitFill takes one background permit from the host limiter, if there is +// one: no cut payload (a fill/idle permit carries none and the limiter refuses +// one), the class from ctx. A revocation runs abort, which stops the walker. +// The returned release gives the permit back, once. +func (l *chunkLayerImpl) admitFill(ctx context.Context, abort func(error)) (func(), error) { + host := l.cfg.Budget + if host == nil { + return func() {}, nil + } + ticket, err := host.Admit(ctx, 0, abort) + if err != nil { + return nil, err + } + var once sync.Once + return func() { once.Do(func() { host.Release(ticket) }) }, nil +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go new file mode 100644 index 0000000000..b184105503 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -0,0 +1,408 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +func countGets(r *fakeChunkRemote) map[string]int { + r.mu.Lock() + defer r.mu.Unlock() + out := map[string]int{} + for _, op := range r.ops { + if key, ok := strings.CutPrefix(op, "get:"); ok { + out[key]++ + } + } + return out +} + +func fastWalker(t *testing.T) { + t.Helper() + minB, maxB := hydrateAllMinBackoff, hydrateAllMaxBackoff + hydrateAllMinBackoff, hydrateAllMaxBackoff = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { hydrateAllMinBackoff, hydrateAllMaxBackoff = minB, maxB }) +} + +// walkRun is one HydrateAll call on its own goroutine. Its ctx is cancelled +// and its return joined (bounded) at cleanup, registered before launch. +type walkRun struct { + done chan struct{} + cancel context.CancelFunc + p HydrateProgress + err error +} + +func startWalker(t *testing.T, layer *chunkLayerImpl, parent context.Context) *walkRun { + t.Helper() + ctx, cancel := context.WithCancel(parent) + w := &walkRun{done: make(chan struct{}), cancel: cancel} + t.Cleanup(func() { + cancel() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Error("cleanup: walker did not return") + } + }) + go func() { + w.p, w.err = layer.HydrateAll(ctx) + close(w.done) + }() + return w +} + +func (w *walkRun) wait(t *testing.T, what string) { + t.Helper() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Fatalf("%s: walker did not return", what) + } +} + +func walkerSignal[T any](t *testing.T, ch <-chan T, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(ctLocalBound): + t.Fatalf("timed out waiting for %s", what) + } +} + +// waitUntil polls cond (bounded by ctLocalBound); permits are released +// asynchronously, when each flight settles. +func waitUntil(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(ctLocalBound) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + time.Sleep(time.Millisecond) + } +} + +// fillLimiter is a real host limiter on pool dir with fillSlots fill permits. +func fillLimiter(t *testing.T, dir string, fillSlots int) *hostlimit.Limiter { + t.Helper() + c := hostlimit.DefaultConfig(dir) + c.FillSlots = fillSlots + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(l.Close) + return l +} + +// payloadRecorder passes admissions to a real Budget and records each payload. +type payloadRecorder struct { + Budget + mu sync.Mutex + payloads []int64 +} + +func (r *payloadRecorder) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + r.mu.Lock() + r.payloads = append(r.payloads, payload) + r.mu.Unlock() + return r.Budget.Admit(ctx, payload, abort) +} + +// boundedCtx bounds a synchronous walk so that a walker that never finishes +// fails the test instead of hanging it. +func boundedCtx(t *testing.T, parent context.Context) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(parent, ctLocalBound) + t.Cleanup(cancel) + return ctx +} + +func bgFill() context.Context { + return hostlimit.WithClass(context.Background(), hostlimit.BackgroundFill) +} + +func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + ctx := boundedCtx(t, context.Background()) + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { + t.Fatalf("hydrate all: %+v %v, want %d filled, 0 remaining", p, err, ctNumBlocks/ctChunkBlocks) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times, want exactly once", key, n) + } + } + for b := uint32(0); b < ctNumBlocks; b++ { + got, err := s.Read(b) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + before := len(countGets(remote)) + if p, err := layer.HydrateAll(ctx); err != nil || p.Filled != 0 || p.Remaining != 0 || len(countGets(remote)) != before { + t.Fatalf("a second walk of a full volume must do nothing: %+v %v", p, err) + } +} + +// A guest write that is still only in the WAL is not visible to the walker as +// local (localBlocks is set when the extent gets a local version), so the chunk +// may be fetched; the fill must never overwrite the local write (reads resolve +// the WAL first and the fill installs only blocks without a newer local version). +func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { + fastWalker(t) + s, layer, _, _ := hydrationFixture(t, 2, 64) + for i := uint32(0); i < ctChunkBlocks; i++ { // chunk 0 fully overwritten + if _, err := s.Write(i, makeBlock(ctBlockSize, 0xEE)); err != nil { + t.Fatal(err) + } + } + if _, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xEF)); err != nil { // one block of chunk 1 + t.Fatal(err) + } + p, err := layer.HydrateAll(boundedCtx(t, context.Background())) + if err != nil || p.Remaining != 0 { + t.Fatalf("hydrate all: %+v %v", p, err) + } + for i := uint32(0); i < ctChunkBlocks; i++ { + if got, _ := s.Read(i); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEE)) { + t.Fatalf("block %d: the local write was overwritten by the walker", i) + } + } + if got, _ := s.Read(ctChunkBlocks + 1); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEF)) { + t.Fatal("partial local write in chunk 1 overwritten") + } + if got, _ := s.Read(ctChunkBlocks); !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+ctChunkBlocks))) { + t.Fatal("the unwritten blocks of chunk 1 must read HEAD's bytes after the walk") + } +} + +// The walker's deferral is witnessed (its pause hook fires) while the guest's +// fetch is held, before anything is allowed to progress. +func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { + fastWalker(t) + s, layer, remote, registered := hydrationFixture(t, 2, 64) + paused := make(chan struct{}, 1) + layer.testHydrateAllPause = func() { + select { + case paused <- struct{}{}: + default: + } + } + entered, release := holdNextGet(t, remote) + guest := startHydrationRead(t, s, context.Background(), 5*ctChunkBlocks) + waitHydrationRegistration(t, registered, 1) + walkerSignal(t, entered, "the guest's fetch of chunk 5") + w := startWalker(t, layer, context.Background()) + walkerSignal(t, paused, "the walker to yield to the held guest fetch") + if n := len(countGets(remote)); n != 1 { + t.Fatalf("the walker fetched while a guest was waiting: %d distinct gets", n) + } + release() + if r := hydrationOutcome(t, guest); r.err != nil { + t.Fatalf("guest read: %v", r.err) + } + w.wait(t, "after the guest fill") + if w.err != nil || w.p.Remaining != 0 || w.p.Paused == 0 || w.p.Filled != ctNumBlocks/ctChunkBlocks-1 { + t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", w.p, w.err) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } +} + +type walkerClassKey struct{} + +type walkerBudget struct { + mu sync.Mutex + refuse int + admitted int + released int + classes []any + abort func(error) +} + +func (b *walkerBudget) Admit(ctx context.Context, _ int64, abort func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.classes = append(b.classes, ctx.Value(walkerClassKey{})) + b.abort = abort + if b.refuse > 0 { + b.refuse-- + return 0, errors.New("fill class over budget") + } + b.admitted++ + return uint64(b.admitted), nil +} +func (b *walkerBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *walkerBudget) Release(uint64) { + b.mu.Lock() + b.released++ + b.mu.Unlock() +} + +func (b *walkerBudget) counts() (admitted, released int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.admitted, b.released +} + +func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{refuse: 2} + layer.cfg.Budget = budget + ctx := boundedCtx(t, context.WithValue(context.Background(), walkerClassKey{}, "fill")) + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Deferred != 2 { + t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) + } + waitUntil(t, "every permit is released", func() bool { a, r := budget.counts(); return a == r }) + budget.mu.Lock() + defer budget.mu.Unlock() + if budget.admitted != p.Filled { + t.Fatalf("budget admitted %d, filled %d: every fill admitted once", budget.admitted, p.Filled) + } + for _, c := range budget.classes { + if c != "fill" { + t.Fatalf("the caller's limiter class did not reach Admit: %v", c) + } + } +} + +func TestHydrateAll_CancelReturnsWhileTheFetchIsHeld(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + entered, _ := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's first fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) || w.p.Remaining == 0 { + t.Fatalf("cancelled walk: %+v %v, want context.Canceled and chunks remaining", w.p, w.err) + } +} + +// The real limiter refuses a background permit that carries a cut payload: +// every fill must be admitted as a fill permit (no payload) under +// BackgroundFill, fill the HEAD image exactly, and give every permit back. +func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + lim := fillLimiter(t, t.TempDir(), 2) + rec := &payloadRecorder{Budget: lim} + layer.cfg.Budget = rec + ctx, cancel := context.WithTimeout(bgFill(), ctLocalBound) + defer cancel() + p, err := layer.HydrateAll(ctx) + // A refusal is possible while an earlier permit is still being closed by + // the limiter; it is a deferral, and the limiter counts it as a skip. + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { + t.Fatalf("hydrate all under the real limiter: %+v %v", p, err) + } + for b := uint32(0); b < ctNumBlocks; b++ { + if got, err := s.Read(b); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } + rec.mu.Lock() + for _, n := range rec.payloads { + if n != 0 { + t.Fatalf("fill admitted with a %d-byte cut payload", n) + } + } + rec.mu.Unlock() + waitUntil(t, "every fill permit is admitted once and released", func() bool { + st := lim.Snapshot().(hostlimit.Stats) + return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == p.Deferred + }) +} + +// The permit follows the owned flight, not the walker's wait: a cancelled +// walker returns at once, but its fill permit stays taken until the held +// physical Get settles. +func TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + dir := t.TempDir() + layer.cfg.Budget = fillLimiter(t, dir, 1) + contender := fillLimiter(t, dir, 1) + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, bgFill()) + walkerSignal(t, entered, "the walker's fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) { + t.Fatalf("cancelled walk: %v", w.err) + } + if tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil); err == nil { + contender.Release(tk) + t.Fatal("the fill permit was free while the walker's Get was still running") + } else if !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("contender: %v", err) + } + release() + waitUntil(t, "the permit is free after the Get settled", func() bool { + tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil) + if err == nil { + contender.Release(tk) + } + return err == nil + }) +} + +// A limiter revocation (the abort callback) stops the walker with the cause; +// the permit is still released only when the owned fetch settles. +func TestHydrateAll_RevocationStopsTheWalker(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{} + layer.cfg.Budget = budget + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's fetch") + budget.mu.Lock() + abort := budget.abort + budget.mu.Unlock() + abort(hostlimit.ErrRevoked) + w.wait(t, "revocation with the fetch still held") + if !errors.Is(w.err, hostlimit.ErrRevoked) { + t.Fatalf("revoked walk: %v, want ErrRevoked", w.err) + } + if _, r := budget.counts(); r != 0 { + t.Fatal("permit released before the owned fetch settled") + } + release() + waitUntil(t, "the permit is released after the fetch settled", func() bool { _, r := budget.counts(); return r == 1 }) +} + +func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + if n := layer.Stats().AbsentChunks; n != ctNumBlocks/ctChunkBlocks { + t.Fatalf("absent before the walk: %d, want %d", n, ctNumBlocks/ctChunkBlocks) + } + if _, err := layer.HydrateAll(boundedCtx(t, context.Background())); err != nil { + t.Fatal(err) + } + if n := layer.Stats().AbsentChunks; n != 0 { + t.Fatalf("absent after the walk: %d, want 0", n) + } +} diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 2291ea22cc..acd4e3f8af 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -34,6 +34,7 @@ type chunkHydrationFlight struct { ctx context.Context cancel context.CancelFunc done chan struct{} + settled chan struct{} // closed once its I/O is over: after fillOnce, or removal unrun running bool waiters int err error @@ -76,39 +77,15 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, hydrationPending(err) } - gen := l.absentGen[idx] - f := l.hydration[idx] - stale := f != nil && (f.gen != gen || f.ref != ref) - if stale { - f.cancel() - // The old worker remains owned and joined, but cannot delay a - // new generation or remove its replacement when it finishes. - delete(l.hydration, idx) - close(f.done) - f = nil + f, joined, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, err } - if f != nil && !stale { + if joined { l.stats.Hydration.Joined++ } - if f == nil { - if len(l.hydration) >= l.cfg.HydrationQueueDepth { - l.stats.Hydration.WaitRefusals++ - l.stMu.Unlock() - return nil, hydrationPending(nil) - } - if !l.hydrationStarted { - l.hydration = make(map[uint64]*chunkHydrationFlight) - l.hydrationWake = make(chan struct{}, 1) - l.hydrationStarted = true - l.wg.Add(l.cfg.HydrationWorkers) - for i := 0; i < l.cfg.HydrationWorkers; i++ { - go l.hydrationWorker() - } - } - work, cancel := context.WithCancel(l.ctx) - f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} - l.hydration[idx] = f - } f.waiters++ l.wakeHydrationLocked() l.stMu.Unlock() @@ -138,7 +115,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b f.waiters-- closed := l.closed changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref - err := f.err + err = f.err if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { l.stats.Hydration.WaitRefusals++ } @@ -157,6 +134,46 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b } } +// hydrationFlightLocked returns the flight for chunk idx's current absence +// (generation and HEAD ref): an existing one (joined) or a new queued one. A +// stale flight of an older generation is settled and replaced. It refuses with +// hydrationPending when the queue is full. The caller holds stMu, counts its +// own waiter and wakes the workers. +func (l *chunkLayerImpl) hydrationFlightLocked(idx uint64, ref chunkRef) (*chunkHydrationFlight, bool, error) { + gen := l.absentGen[idx] + f := l.hydration[idx] + if f != nil && (f.gen != gen || f.ref != ref) { + f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + if !f.running { + close(f.settled) // never picked up: no I/O will run + } + f = nil + } + if f != nil { + return f, true, nil + } + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + return nil, false, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{}), settled: make(chan struct{})} + l.hydration[idx] = f + return f, false, nil +} + func (l *chunkLayerImpl) wakeHydrationLocked() { select { case l.hydrationWake <- struct{}{}: @@ -196,6 +213,7 @@ func (l *chunkLayerImpl) hydrationWorker() { resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) cancel() next.cancel() + close(next.settled) l.stMu.Lock() if hydrationContextCauseOnly(err) { err = hydrationPending(err) @@ -225,6 +243,7 @@ func (l *chunkLayerImpl) closeHydrationLocked() { f.err = errChunkLayerClosed delete(l.hydration, idx) close(f.done) + close(f.settled) } } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index a1e3950549..3ed9ec97b5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -127,6 +127,7 @@ type chunkLayerImpl struct { // Test-only scheduling hooks; nil in production. testHydrationWait func(uint64) // after promise registration, outside locks + testHydrateAllPause func() // HydrateAll yielded to a guest waiter, outside locks testCOWWait func() testCOWSaverWait func() testCOWRead func(idx uint64, saved bool) @@ -1474,6 +1475,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Unlock() out.DirtyChunks = len(l.captureCandidates()) + out.AbsentChunks = l.absentHydratable() return out } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index ca42de1f14..d2721cfaaa 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -494,6 +494,9 @@ type chunkLayerStats struct { // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 + // 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 } // chunkCutResult is the outcome of one successful cut. diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 62310d03a4..8989612a6e 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -234,7 +234,7 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor if werr != nil && p.io.latch != nil { // Latch inside the leaf, before fileSyncMu is released: a store // Sync queued on fileSyncMu must not fsync and acknowledge - // through this uncertain slot (codex01 row 3 round 2). + // through this uncertain slot. p.io.latch(fmt.Errorf("%w: %w", ErrDescriptorPublishUncertain, werr)) } return werr diff --git a/seaweed-block/core/storage/descriptor_v3_test.go b/seaweed-block/core/storage/descriptor_v3_test.go index 2f490ab2b3..4a76b1c45e 100644 --- a/seaweed-block/core/storage/descriptor_v3_test.go +++ b/seaweed-block/core/storage/descriptor_v3_test.go @@ -420,7 +420,7 @@ func TestDescriptorV3BaseTransitionTable(t *testing.T) { } } -// codex01 row 3 review P1: a slot write error (full or partial), like an +// A slot write error (full or partial), like an // fsync error, latches the store, keeps the candidate pinned and refuses // every further publication, rollover and reuse with no further I/O. // Reopen (read back and select) is the positive control. @@ -492,7 +492,7 @@ func TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate(t *testing.T) { } } -// codex01 row 3 review P2: counters beyond 2^64-2 are refused at +// Counters beyond 2^64-2 are refused at // publication with ErrCounterExhausted, before any write. func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) { const over = counterMaxV3 + 1 @@ -518,7 +518,7 @@ func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) { } } -// codex01 row 3 round 2 P1: the store fault for a slot write error is +// The store fault for a slot write error is // latched inside the leaf, before fileSyncMu is released. An independent // store Sync B queued on fileSyncMu behind A's failing slot write must be // refused and must not fsync or acknowledge. The harness lets B run right diff --git a/seaweed-block/core/storage/install_log_v3_test.go b/seaweed-block/core/storage/install_log_v3_test.go index a0b9bf6a74..00a510f63c 100644 --- a/seaweed-block/core/storage/install_log_v3_test.go +++ b/seaweed-block/core/storage/install_log_v3_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -// Plan row 10a controls (DESIGN r17.4 section 7; owner claude03): the gated +// Install-log controls: the gated // logical Sync and the receiver-only install-log ack. // While installing, Sync returns exactly (0, ErrBaseInstalling) and writes @@ -91,7 +91,7 @@ func TestInstallLogV3IsModeAAndSurvivesACrash(t *testing.T) { } } -// codex01 row 10a P1 (the #172 ack boundary): an append of the same install +// The #172 ack boundary: an append of the same install // that fails and latches the store after SyncInstallLog's publication and // before its ack refuses the ack: no H, no volatile acknowledged frontier. // The held hook runs that append with a failing pwrite (the real latch). Mutant: no diff --git a/seaweed-block/core/storage/recovery_v3.go b/seaweed-block/core/storage/recovery_v3.go index 8e22c340cb..e4b203e3a1 100644 --- a/seaweed-block/core/storage/recovery_v3.go +++ b/seaweed-block/core/storage/recovery_v3.go @@ -161,9 +161,8 @@ func fenceRangesV3(E, floor, walSize uint64, sameNonce bool) ([]fenceRangeV3, er return nil, fmt.Errorf("storage: v3 fence: head %d below the reuse floor %d", E, floor) } // Interval-length arithmetic: floor+walSize is never formed, so a - // history ending at the last representable cursor still recovers - // (codex01 row 5 P2). The logical end may exceed 2^64-2; only the - // physical bytes matter. + // history ending at the last representable cursor still recovers. + // The logical end may exceed 2^64-2; only the physical bytes matter. used := E - floor if used >= walSize { return nil, nil diff --git a/seaweed-block/core/storage/recovery_v3_test.go b/seaweed-block/core/storage/recovery_v3_test.go index 38098bfa2b..dd139ff021 100644 --- a/seaweed-block/core/storage/recovery_v3_test.go +++ b/seaweed-block/core/storage/recovery_v3_test.go @@ -99,7 +99,7 @@ func TestRecoveryV3Decision(t *testing.T) { t.Fatal("intact installing error is not a plain ErrBaseIncomplete") } // A contradictory chain while installing keeps the outer not-ready - // outcome (codex01 row 5). + // outcome. bad := []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)} if _, err := decideRecoveryV3(inst, bad, 11); !errors.Is(err, ErrBaseIncomplete) || !errors.Is(err, ErrInstallSuffixDamaged) { t.Fatalf("contradictory installing chain: err = %v, want ErrBaseIncomplete wrapping ErrInstallSuffixDamaged", err) @@ -122,7 +122,7 @@ func TestRecoveryV3FenceRangesAreExact(t *testing.T) { sameNonce bool want []fenceRangeV3 }{ - // codex03 r13 example: WALSize 256, fallback tail 0, selected 100, + // WALSize 256, fallback tail 0, selected 100, // E 120. The fence is exactly [120, 256): physical [0, 100), which // the fallback still references, is untouched. {"floor bound, not the selected tail", 120, 0, 256, true, []fenceRangeV3{{120, 136}}}, @@ -158,7 +158,7 @@ func TestRecoveryV3FenceRangesAreExact(t *testing.T) { if _, err := fenceRangesV3(50, 100, 256, true); err == nil { t.Fatal("a head below the floor was accepted") } - // codex01 row 5 P2: a history ending at the last representable cursor + // A history ending at the last representable cursor // still fences exactly; floor+WALSize is never formed. got, err := fenceRangesV3(counterMaxV3, counterMaxV3-100, 256, true) if err != nil { diff --git a/seaweed-block/core/storage/reset_store_v3_test.go b/seaweed-block/core/storage/reset_store_v3_test.go index d06d8e9940..92df3a99ae 100644 --- a/seaweed-block/core/storage/reset_store_v3_test.go +++ b/seaweed-block/core/storage/reset_store_v3_test.go @@ -273,7 +273,7 @@ func TestWALStoreV3HalfResetRefusesWritesUntilRecover(t *testing.T) { readAllV3(t, r, 1, 3) } -// codex01 row 8 P1: a Read that resolved LBA 1's WAL position (cursor 0) +// A Read that resolved LBA 1's WAL position (cursor 0) // parks before its pread; the real flusher checkpoints and releases the // entry, the reset starts the new incarnation at cursor 0, and Write(2, B) // reuses that position. The resumed Read must not return B for LBA 1: it @@ -377,7 +377,7 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) { } } -// codex01 e72acd40 P2 (1): a same-open Recover can fence a dropped record +// A same-open Recover can fence a dropped record // and re-allocate its LSN to the same LBA at the same position. A read // parked across that saw the fenced bytes; on re-resolution the entry looks // unchanged (same position and LSN), but it is a new write: the read must @@ -426,7 +426,7 @@ func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage } } -// codex01 e72acd40 P2 (2): a failed pread is substrate I/O, never WAL +// A failed pread is substrate I/O, never WAL // integrity. EOF policy: the WAL region lies inside the file, so a file // shorter than its geometry (io.EOF) is substrate I/O too. func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { @@ -460,7 +460,7 @@ func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { }) } -// codex01 2fa56078 P2: a read already admitted (past Read's close check) +// A read already admitted (past Read's close check) // captures the recovery generation AFTER a Recover's start bump and the OLD // dirty entry BEFORE its clear; the recovery fences the dropped record and // a same-LBA write re-allocates the same position and LSN. Tuple and a diff --git a/seaweed-block/core/storage/superblock_v3_test.go b/seaweed-block/core/storage/superblock_v3_test.go index 378a6b2f29..7104c4c8db 100644 --- a/seaweed-block/core/storage/superblock_v3_test.go +++ b/seaweed-block/core/storage/superblock_v3_test.go @@ -93,7 +93,7 @@ func TestSlotV3ReferenceFields(t *testing.T) { d.BaseState != BaseNone || d.WMode != WModeLagged || d.MigrationPhase != MigrationNormal { t.Fatalf("reference fields differ: %+v", d) } - // The slot names codex03's map fixture root (DESIGN 9.5). + // The slot names the map fixture root (DESIGN 9.5). if got := d.MapRootHash; got[0] != 0xb4 || got[1] != 0x7d || got[31] != 0x1b { t.Fatalf("map root hash %x is not the 9.5 rootBodyDigest", got) } diff --git a/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py index 1fc65cd045..8e2ce8bf30 100644 --- a/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py +++ b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py @@ -29,7 +29,7 @@ assert crc32c(b"123456789") == 0xE3069283, "crc32c self-check failed" UUID = bytes(range(0x00, 0x10)) LINEAGE = bytes(range(0x10, 0x20)) NONCE = bytes(range(0x20, 0x30)) -# rootBodyDigest of codex03's reference root (DESIGN 9.5): this slot names that map. +# rootBodyDigest of the reference map root (DESIGN 9.5): this slot names that map. ROOT_HASH = bytes.fromhex("b47d24af8db0e0a2cd2494652c981c48f4d2a861c381f4a04cac4b35e2ac321b") diff --git a/seaweed-block/core/storage/walstore_batch_v3_test.go b/seaweed-block/core/storage/walstore_batch_v3_test.go index 1bd91b7e2d..914059ebd5 100644 --- a/seaweed-block/core/storage/walstore_batch_v3_test.go +++ b/seaweed-block/core/storage/walstore_batch_v3_test.go @@ -6,8 +6,8 @@ import ( "testing" ) -// v3 WriteBatch controls (DESIGN r17.4 sections 3.1 and 6.7; owner -// claude03): one multi-block record per batch, its replay and reads. +// v3 WriteBatch controls: +// one multi-block record per batch, its replay and reads. func batchBlocks(first byte, n int) [][]byte { out := make([][]byte, n) @@ -201,7 +201,7 @@ func TestWALStoreV3BatchFlushesEveryBlock(t *testing.T) { readBatchV3(t, r, 10, 0x40, 4, "after reopen") } -// The dark offline reader (codex03's walstore_readonly_v3.go) indexes and +// The dark offline reader (walstore_readonly_v3.go) indexes and // reads every block of a batch record. Mutant: indexing only a batch's // first block fails here. func TestWALStoreV3ReadOnlyReaderServesBatchBlocks(t *testing.T) { @@ -242,8 +242,8 @@ func TestWALStoreV3BatchRecordsMapCoverage(t *testing.T) { } } -// Ordinary replicated ApplyEntry on v3 (DESIGN 8.1, 6.7, r16.1; codex03 -// 12a inventory): applies append in LSN order and survive a crash; an LSN +// Ordinary replicated ApplyEntry on v3 (DESIGN 8.1, 6.7): +// applies append in LSN order and survive a crash; an LSN // at or below the highest is a superseded no-op when the LBA holds a higher // LSN and ErrWALLSNOrder otherwise; an unanchored gap is refused; an // ordinary apply while installing is refused (the install lane is the @@ -329,7 +329,7 @@ func TestWALStoreV3ScanLBAs(t *testing.T) { } } -// codex01 4caac700 P1s: v3 ScanLBAs is all or nothing. A corrupt middle +// v3 ScanLBAs is all or nothing. A corrupt middle // record makes the chain stop short of the head: a typed WAL integrity // failure carrying the scanner's stop cause, with nothing emitted (never // a short success, never WALRecycled). An installing diff --git a/seaweed-block/core/storage/walstore_close_v3_test.go b/seaweed-block/core/storage/walstore_close_v3_test.go index 0dd57c0e78..dd17ff6036 100644 --- a/seaweed-block/core/storage/walstore_close_v3_test.go +++ b/seaweed-block/core/storage/walstore_close_v3_test.go @@ -7,7 +7,7 @@ import ( "testing" ) -// codex01 row 7 slice 4 P1: WALStore.Close serialized the legacy superblock +// Regression: WALStore.Close serialized the legacy superblock // and pwrote it at offset 0, which on a v3 file is descriptor slot A. The // schedule: strict create (A gen 1), Recover (B gen 2), Write+Sync (A gen 3, // W 1), Close (slot A destroyed), reopen (B gen 2, W 0). A v3 Close writes diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index a8442123bb..a6514b8c0f 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -65,7 +65,7 @@ func (s *WALStore) CheckpointLSNForPOC() uint64 { } // scanLBAsV3 is ScanLBAs on a v3 store (the primary's catch-up source). -// It is all or nothing (codex01 4caac700 P1s): it captures the recovery +// It is all or nothing: it captures the recovery // generation, the descriptor and the head, refuses an installing source // (ErrBaseInstalling) before emitting anything, scans the trusted v3 chain // into memory, revalidates the capture (a Recover, reset or BASE transition diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index efb4a92aa7..6599c40467 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -38,15 +38,15 @@ type walStoreV3State struct { // leader role) for its whole run, between lifecycleMu and s.mu, and bumps // recoverGen first, under syncMu and s.mu. Every W publisher (the Sync // batch, refreshW, SetWMode) holds syncMu across capture -> publish -> - // acknowledgement, so no publication straddles a recovery (codex01 row - // 5d; Claude01's structural seam). The one boundary that cannot hold - // syncMu across its wait, the outer Sync() completion, captures - // recoverGen with its target and rechecks it under syncMu -> s.mu. + // acknowledgement, so no publication straddles a recovery. The one + // boundary that cannot hold syncMu across its wait, the outer Sync() + // completion, captures recoverGen with its target and rechecks it under + // syncMu -> s.mu. // // recoverGen is bumped at the start AND at the end of every recovery // and reset, the start+end pattern of the map proof epoch: a lock-free // reader whose attempt saw the same value before and after was not cut - // by a recovery's end (codex01 2fa56078 P2: a read admitted between the + // by a recovery's end (the case this closes: a read admitted between the // start bump and the dirty-map clear captured the new value with an old // entry, then a same-tuple rewrite after the recovery). // @@ -478,7 +478,7 @@ func (s *WALStore) recoverV3() (uint64, error) { if err != nil { if d.BaseState == BaseInstalling { // Installing keeps its typed not-ready outcome; the cause is a - // substrate error, not proven install-log damage (codex01 5b P2). + // substrate error, not proven install-log damage. return 0, fmt.Errorf("%w: scan: %w", ErrBaseIncomplete, err) } return 0, err @@ -503,11 +503,11 @@ func (s *WALStore) recoverV3() (uint64, error) { // never reuses an LSN the WAL still holds. // // Only a physical reopen records them: when this open began the - // installing ID, its handle stays valid (DESIGN r17.4: until the next - // begin) and may append and acknowledge past this cut, so a cached E - // would be stale and fencing from it could erase acknowledged - // records (codex01 row 11b P1). A resume or a fenced supersession - // then refuses before any I/O; the live install continues. + // installing ID, its handle stays valid (until the next begin) and + // may append and acknowledge past this cut, so a cached E would be + // stale and fencing from it could erase acknowledged records. A + // resume or a fenced supersession then refuses before any I/O; the + // live install continues. if d.BaseInstallID != v.liveInstallID { ro := &installReopenV3{id: d.BaseInstallID, E: o.E, R: o.R, damaged: o.Damaged, walSize: d.WALSize} for _, r := range scan.Records { @@ -533,11 +533,11 @@ func (s *WALStore) recoverV3() (uint64, error) { // closed; a physical reopen then decides intact or damaged. s.latchV3(fmt.Errorf("storage: v3 same-open installing recovery: recovered cut E %d is not the live writer head", o.E)) } else { - // The live install continues (r17.4). Its trusted install-lane + // The live install continues. Its trusted install-lane // records are republished in the dirty map, which this Recover // cleared, so the completed image serves them and not older BASE // bytes; the volatile map coverage (the BASE writes' UNKNOWN) is - // kept as it is (codex01 04180c33 P1). + // kept as it is. for _, r := range scan.Records { if r.Entry.LSN > o.R { break @@ -623,7 +623,7 @@ func (s *WALStore) recoverV3() (uint64, error) { // The volatile acknowledged frontier is the recovered prefix, never an // older in-memory maximum: a same-open recovery that dropped mode C's // newest batch must not let a later refresh publish a W the WAL no - // longer holds (codex01 5b P1). + // longer holds. v.appended.Store(o.R) v.wack.Store(o.R) return s.syncedLSN, nil @@ -864,7 +864,7 @@ func (s *WALStore) syncWALBatchV3Internal(pressureOnly bool) error { if h := v.testBatchBeforeAck; h != nil { h() } - // The acknowledgement boundary (codex01 row 5 P1): a queued append may + // The acknowledgement boundary: a queued append may // have failed and latched the store fault while this batch's slot I/O // was in flight. Recheck under the store lock, which that append holds // until it has latched, before acknowledging anything. @@ -931,7 +931,7 @@ func (s *WALStore) SetWMode(m WMode) error { // readDirtyV3 serves a v3 read from the dirty map, if the LBA has an entry // (handled false: read the extent). A reader holds no lock across its WAL // read, so the position it resolved may be reused before the pread: after a -// reset (cursor 0 again, codex01 row 8 P1) or a same-open recovery that +// reset (cursor 0 again) or a same-open recovery that // fenced and reused it. The read therefore validates the WHOLE record it // read, payload included (CRC, footer, write type, LBA and LSN against the // resolving entry), and re-resolves on a mismatch. LSN allocation runs on @@ -940,7 +940,7 @@ func (s *WALStore) SetWMode(m WMode) error { // to the same LBA at the same position, so the "entry unchanged" damage // verdict also requires the same recovery generation before and after the // whole attempt. A recovery bumps it at its start and its end, so any -// overlap changes it (codex01 e72acd40 and 2fa56078 P2s; see recoverGen). +// overlap changes it (see recoverGen). // A generation captured while a recovery runs can match only if the // verdict also falls inside that recovery, which holds s.mu: no write can // re-allocate the tuple, and the replay installs only validated records. A pread error is a diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go index 4e0654e6d8..298cd708c3 100644 --- a/seaweed-block/core/storage/walstore_v3_test.go +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -409,7 +409,7 @@ func TestWALStoreV3RefusesPathsOfLaterRows(t *testing.T) { } } -// codex01 row 5 P1-1: a batch's acknowledgement rechecks the store fault +// A batch's acknowledgement rechecks the store fault // under the store lock. Schedule, in both modes: batch A's slot write is // parked (A holds descMu); B's Write, already past capacity admission, // takes s.mu exclusively and waits on descMu in the writer's snapshot; @@ -468,7 +468,7 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { } } -// codex01 row 5 P2: a history ending at the last representable cursor +// A history ending at the last representable cursor // recovers; only further appends are refused. func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing.T) { const recSize = uint64(walEntryHeaderSizeV3 + v3TestBlock) @@ -496,7 +496,7 @@ func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing } } -// codex01 row 5 P2 (SetWMode evidence): a held mode-C batch completes and +// A held mode-C batch completes and // acknowledges under C before SetWMode(A) publishes the new mode. func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { s, _ := newStoreV3(t, WModeLagged) @@ -629,7 +629,7 @@ func recvErrV3(t *testing.T, ch <-chan error, what string) error { } } -// codex01 5b P1: a SAME-instance recovery that drops mode C's newest batch +// A SAME-instance recovery that drops mode C's newest batch // resets the acknowledged frontier to R, so a later refresh cannot publish // a W the WAL no longer holds and the next Recover does not report a false // corruption. Fresh-open tests mask this (they start from the slot W). @@ -674,7 +674,7 @@ func TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier(t *testing.T) { } } -// codex01 5b P2: a scan failure under an installing descriptor keeps the +// A scan failure under an installing descriptor keeps the // typed not-ready outcome and leaves the file unchanged. func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { s, path := newStoreV3(t, WModeLagged) @@ -707,7 +707,7 @@ func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { } } -// codex01 5b P2: the real flusher cycle performs the mode-C idle refresh, +// The real flusher cycle performs the mode-C idle refresh, // also when no dirty entries remain, so the window closes without a Sync. func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { s, path := newStoreV3(t, WModeLagged) @@ -731,7 +731,7 @@ func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { // heldV3 owns a parked hook and the workers a held control starts. Its // cleanup, registered before any worker starts and after the store crash // cleanup, first releases the hold, then joins every worker with a bound, -// so an early Fatal never strands store shutdown (codex01 row 5d P2). +// so an early Fatal never strands store shutdown. type heldV3 struct { t *testing.T parked chan struct{} @@ -792,7 +792,7 @@ func notDoneV3(t *testing.T, c chan error, what string) { } } -// codex01 row 5d schedule A: a refresh attempted DURING a same-open +// Schedule A: a refresh attempted DURING a same-open // recovery waits for it (Recover holds the leader role), then sees the // recovered frontier and publishes nothing. func TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing(t *testing.T) { @@ -821,7 +821,7 @@ func TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing(t *testing.T) { } } -// codex01 row 5d schedule B: a recovery attempted while a C batch is parked +// Schedule B: a recovery attempted while a C batch is parked // after its publication and before its acknowledgement waits for the batch; // the recovery then lowers the frontier and nothing revives the dropped cut. func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) { @@ -863,7 +863,7 @@ func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) } } -// codex01 row 5d: the outer Sync() completion is validated against the +// The outer Sync() completion is validated against the // recovery generation. A Sync whose batch finished, then waits while a // recovery drops its cut, must not acknowledge it; a fresh Sync after the // recovery acknowledges normally. @@ -899,7 +899,7 @@ func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) { } } -// codex01 row 5c P2: the empty-dirty-set branch of the flusher cycle runs the +// The empty-dirty-set branch of the flusher cycle runs the // idle refresh on its own (discriminated separately from the flush branch). func TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh(t *testing.T) { s, _ := newStoreV3(t, WModeLagged) diff --git a/seaweed-block/core/transport/replica_install_format_v3_test.go b/seaweed-block/core/transport/replica_install_format_v3_test.go index 5050dd6238..ab590de154 100644 --- a/seaweed-block/core/transport/replica_install_format_v3_test.go +++ b/seaweed-block/core/transport/replica_install_format_v3_test.go @@ -15,8 +15,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Plan row 10b controls (DESIGN r17.4 section 8.7, caller 2; owner -// claude03): the legacy single-lane rebuild on a dark v3 replica. The +// Replica install controls: +// the legacy single-lane rebuild on a dark v3 replica. The // first admitted rebuild message begins one install at its frontier hint; // blocks go through the handle; done completes, then Syncs, and a failure // closes the connection with no MsgBarrierResp. diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..480573c503 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -72,8 +72,8 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t | Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost | | Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume | -- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut. -- **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer. +- **When cuts happen.** At semantic points chosen by the integrator, on explicit request, and by the periodic timer (default 15m, minimum 5m in the OSS CLI; 0 disables). Periodic cuts update HEAD without creating named snapshots. `--chunk-dirty-threshold` bounds staging work and never triggers a cut. +- **Recoverable frontier.** The confirmed remote HEAD is the recovery point after host loss. The default capture interval is 15m; failed or expired attempts retry with bounded backoff and reusable uploads, and do not claim a newly durable recovery point. - Multi-replica workspaces combined with chunk snapshots are not supported. ## 3. Remote layout @@ -187,6 +187,7 @@ stateDiagram-v2 - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. - **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); @@ -205,7 +206,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD + [*] --> active: initial HEAD (gen 1, epoch 0), fork or restore HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) @@ -235,6 +236,48 @@ stateDiagram-v2 The attempt path is never removed, so a late create can never land after a delete. +Restore (target volume): + +```mermaid +stateDiagram-v2 + [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) + Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped + Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys + Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Independent --> [*] + Aborted --> [*]: target deleted +``` + +Snapshots of the target are refused in `Claimed` and `Restoring`. + +### Attached-volume scheduling + +Blockvolume defaults to periodic HEAD capture every 15 minutes (minimum 5 +minutes, 0 disables) and retention every hour. Named snapshots remain explicit. +A five-minute context covers the whole cut; completed immutable uploads survive +an expired attempt only under matching version/HEAD generation. Automatic GC is +opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog +scan cost. Scoped GC changes candidates, not the catalog root domain; each volume +has independent persisted mark coverage. CLI catalog mutations also check the +single-filer deployment constraint before mutation. + +```mermaid +stateDiagram-v2 + [*] --> PendingAttach + PendingAttach --> Armed: attached and healthy + Armed --> Running: staggered due event + Running --> Armed: retention and optional scoped GC settle + Running --> Draining: detach, fence, close + Armed --> Draining: detach, fence, close + Draining --> Closed: cancel and join every worker + Draining --> Armed: safe detach abort, same current handle +``` + +No catch-up queue is accumulated. Retention failure skips GC; incomplete marks +and configuration changes do not authorize reclamation. Unknown same-epoch CAS +intents remain rooted after restart; elapsed TTL is not a settlement proof. + ## 7. Lease, takeover and host moves **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cd20e0f2e5..5023b8dc8a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -93,10 +93,10 @@ 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` | `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; 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` | | 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 | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; 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 | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-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` | ### M3 Replica role and peer state @@ -197,6 +197,7 @@ stateDiagram-v2 | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | +| Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -205,6 +206,7 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th ```mermaid stateDiagram-v2 [*] --> Admit + [*] --> Refused: invalid frozen request; invalid_freeze_budget; no provider mutation Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid Admit --> PlainStop: plain detach and idle frontend lock acquired PlainStop --> Quiesce: frontend stopped; ordinary detached cut @@ -245,7 +247,7 @@ stateDiagram-v2 | 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` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | -| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; 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` | +| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | | Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` | | 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` | @@ -258,6 +260,11 @@ stateDiagram-v2 | Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | | Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | +Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes; +0 explicitly disables); they do not create named snapshots. One five-minute +context covers a cut, including uploads. Deadline-aborted uploads remain rooted +and reusable only while their chunk version and HEAD generation match. + ### M6 Chunk lifecycle HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). @@ -266,7 +273,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -285,6 +292,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | +| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -292,11 +302,26 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| 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 at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| 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` | +| 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` | +GC clock admission (`INV-GC-CLOCK-SKEW-001`): + +```mermaid +flowchart LR + stamp[Persisted timestamp] --> age[Observed age minus pairwise skew and timestamp precision] + age --> young[Not past grace: retain root or candidate] + age --> old[Past grace: existing authority and complete-mark guards] + future[Future or backward mark clock] --> reset[Discard elapsed coverage and start a fresh mark] + old --> reject[HTTP400: retain tombstone and report failure] + reject --> later[Continue later bindings and save complete mark] +``` + + --- ### Local WAL-pressure durability progress @@ -345,9 +370,19 @@ snapshot lifetime; local persistence does not bypass it. `free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +### M8. Attached-volume maintenance + +`PendingAttach -> Armed -> Due -> Running -> Armed`; elapsed ticks coalesce. +A stable volume phase staggers the one-hour retention schedule. GC is opt-in +pending density qualification. Detach/fence/Close cancels and joins before +catalog/storage release; only a still-current handle may re-arm after safe abort. +A pass has one minute for retention and optional GC; retention failure skips GC. +A scoped GC pass traces the whole catalog but mutates only its target volume, +with a separate scope/config-bound mark. Incomplete marks carry no coverage. + ## Part B. Invariant ledger -118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new. +135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -384,12 +419,12 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | @@ -407,9 +442,9 @@ Notes: - `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. - `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. - `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands, a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until the v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11. - `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. - `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). @@ -471,13 +506,17 @@ Notes: | `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 | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | +| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns carries its lost range as stored before the issue (the kept HEAD's remote LSN, LostUntil in master time, the kept HEAD's generation and the HEAD entry's filer mtime read with that HEAD, or "unknown"), also on a replay and after a restart; `QueryWorkspaceLostRange` returns the same stored ranges, all of them in issue order or one by request id, never recomputed. A forced move whose range record is missing or fails its checks (the range checksum or the HEAD-time checksum) makes the readout fail (a grant without a range and with the reason; `DataLoss` from the query; CLI exit 4) and is never reported as no loss. A failure after the issue (e.g. the binding reconciliation) is answered as `Internal` naming the move ISSUED, never as a refusal; the client reports it as an unknown outcome with the same-request-id recovery (never a new request id), and the master's audit log records the issued forced move. An issuing write that may have reached the store but reported an error (memory unissued), and any move on a volume whose workspace persistence is already uncertain, fail with `ErrWorkspaceOutcomeUncertain` and are answered as an unknown outcome (`Internal`, restart then rerun with the same request id), logged as unknown, never as a refusal; admission refusals and failures before the issue stay `FailedPrecondition`. The client accepts a grant only when it matches the request (request id, volume, expected holder and epoch, target replica and host, a higher epoch; else unknown) and its range only when it names the same move and kept HEAD (volume, request id, epochs, old replica, HEAD generation, frontier = remote LSN; else unproven). `PreviewWorkspaceMove` runs the forced admission and writes nothing. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`, `decodeLostRangeHeadTimes`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `PreviewWorkspaceForcedMove`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/authority/authority.go` `applyWithWorkspaceMove`; `core/host/master/workspace_service.go` `MoveWorkspace`, `grantWithLostRange`, `postIssueError`, `issuedRecord`, `logForcedGrant`, `QueryWorkspaceLostRange`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove`, `checkGrant`, `checkRange`, `LostRanges`, `Readout`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange`, `shellCommand` | `TestWorkspaceForcedMoveStoresHeadFilerTime`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeAccumulatesInIssueOrder`, `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected`, `TestWorkspaceForcedMovePreviewWritesNothing` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`); `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven`, `TestForceMoveBindsGrantAndRange`, `TestLostRangesBindsTheAnswer`, `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row7_ReadoutUnproven`, `TestWorkspaceForceMove_Row8_RerunSameRequestID`, `TestWorkspaceForceMoveRecoveryCommandRuns`, `TestWorkspaceForceMoveRejectsAMismatchedAnswer`, `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`); `TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome` (`cmd/sw-block/workspace_postissue_test.go`); `TestWorkspaceForceMoveUncertainIssueWriteIsUnknown` (`cmd/sw-block/workspace_uncertain_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-CONFIRM-001` | The OSS operator client (`sw-block ops workspace force-move`, `wsclient.ForceMove`) sends a move with `force: true` only when `--confirm-forced` is exactly `@` (that volume, a positive decimal epoch), and then always as kind forced at that epoch with the operator's request id; anything else is refused before any connection or RPC (exit 2). A confirmation at an epoch the master has no holder for is refused without sending a move. There is no bypass flag, and `--dry-run` is never a confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `ForceMove`, `holderAt`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestParseConfirmation`, `TestForceMoveSendsForceOnlyWithTheConfirmation`, `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally`, `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row5_MasterRefusal`, `TestWorkspaceForceMove_Row6_OutcomeUnknown`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. 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). - `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. ### B.5 Workspace: the cut pipeline @@ -487,6 +526,8 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-WS-FREEZE-ACCOUNTING-001` | A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible` (classification itself does not alter the admission model) | ACTIVE | +| `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | @@ -521,18 +562,27 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | +| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | +| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` | ACTIVE | | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | +| `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRejectsCopyDeadline` | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | Notes: -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing diff --git a/seaweed-block/docs/spec/GCClockSkew.tla b/seaweed-block/docs/spec/GCClockSkew.tla new file mode 100644 index 0000000000..2636df0b73 --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew.tla @@ -0,0 +1,24 @@ +------------------------- MODULE GCClockSkew ------------------------- +EXTENDS Integers, TLC +CONSTANTS G, S, Q, MaxT, IgnoreSkew, IgnoreResolution, AbortFuture +VARIABLES t, bias, rounded, stamp, phase, removed, removedOld +vars == <> +Born == 10 +Init == /\ t = Born /\ bias \in {-S,0,S} /\ rounded \in {0,Q} + /\ stamp = Born+bias-rounded /\ phase = "check" + /\ removed = FALSE /\ removedOld = FALSE +Allowance == (IF IgnoreSkew THEN 0 ELSE S)+(IF IgnoreResolution THEN 0 ELSE rounded) +Check == /\ phase = "check" + /\ removed' = (removed \/ (t-stamp > G+Allowance)) + /\ removedOld' = (removedOld \/ ~(AbortFuture /\ stamp > t)) + /\ phase' = "done" + /\ UNCHANGED <> +Tick == /\ phase = "done" /\ t < MaxT /\ t' = t+1 /\ phase' = "check" + /\ UNCHANGED <> +Next == Check \/ Tick +Spec == Init /\ [][Next]_vars +NoEarlyExpiry == removed => t-Born > G +FutureProtects == stamp > t => ~removed +IndependentProgress == phase = "done" => removedOld +EventuallyEligibleAtBound == (phase = "done" /\ t = MaxT) => removed +============================================================================= diff --git a/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg b/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg new file mode 100644 index 0000000000..f310ac305f --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = FALSE + AbortFuture = TRUE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg b/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg new file mode 100644 index 0000000000..e342a736aa --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = TRUE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg b/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg new file mode 100644 index 0000000000..a96481126d --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = TRUE + IgnoreResolution = FALSE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_safe.cfg b/seaweed-block/docs/spec/GCClockSkew_safe.cfg new file mode 100644 index 0000000000..ffdf4e61cc --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_safe.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = FALSE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCDeleteProgress.tla b/seaweed-block/docs/spec/GCDeleteProgress.tla new file mode 100644 index 0000000000..f8fd2f257d --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress.tla @@ -0,0 +1,24 @@ +------------------------ MODULE GCDeleteProgress ------------------------ +EXTENDS Integers, FiniteSets +CONSTANT StopOnReject +VARIABLES next, deleted, rejected, complete +vars == <> +Bad == 1 +Keys == 1..3 +Init == /\ next = 1 /\ deleted = {} /\ rejected = {} /\ complete = FALSE +Step == /\ next \in Keys + /\ IF next = Bad THEN + /\ rejected' = rejected \cup {next} + /\ deleted' = deleted + /\ next' = IF StopOnReject THEN 4 ELSE next+1 + /\ complete' = StopOnReject + ELSE + /\ deleted' = deleted \cup {next} + /\ rejected' = rejected + /\ next' = next+1 + /\ complete' = (next = 3) +Spec == Init /\ [][Step]_vars +NoFalseSuccess == Bad \notin deleted +FailureVisible == complete => Bad \in rejected +LaterProgress == complete => deleted = Keys \ {Bad} +============================================================================= diff --git a/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg b/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg new file mode 100644 index 0000000000..12d9560fec --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT StopOnReject = FALSE +INVARIANTS NoFalseSuccess FailureVisible LaterProgress +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg b/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg new file mode 100644 index 0000000000..524b8c2f1f --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT StopOnReject = TRUE +INVARIANTS NoFalseSuccess FailureVisible LaterProgress +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner.tla b/seaweed-block/docs/spec/MaintenanceOwner.tla new file mode 100644 index 0000000000..b389264468 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner.tla @@ -0,0 +1,37 @@ +------------------------- MODULE MaintenanceOwner ------------------------- +EXTENDS Naturals, TLC +CONSTANT AllowOverlap, ReleaseBeforeJoin, AllowStaleRearm +VARIABLES state, due, workers, released, owner, current, arms, closing +vars == <> +Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE + /\ owner = 1 /\ current = 1 /\ arms = 0 /\ closing = FALSE +Attach == /\ state = "pending" /\ state' = "armed" /\ arms' = arms+1 + /\ UNCHANGED <> +Tick == /\ state = "armed" /\ due' = TRUE + /\ UNCHANGED <> +Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap) + /\ workers < 2 /\ workers' = workers+1 /\ due' = FALSE + /\ UNCHANGED <> +Finish == /\ workers > 0 /\ workers' = workers-1 + /\ UNCHANGED <> +Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE + /\ closing' \in BOOLEAN /\ UNCHANGED <> +Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin) + /\ state' = IF closing THEN "closed" ELSE "idle" + /\ released' = TRUE /\ UNCHANGED <> +Rearm == /\ state = "idle" /\ arms < 3 /\ (owner = current \/ AllowStaleRearm) + /\ state' = "armed" /\ released' = FALSE /\ arms' = arms+1 + /\ UNCHANGED <> +ReplaceHandle == /\ state = "idle" /\ workers = 0 /\ current = 1 + /\ current' = 2 + /\ UNCHANGED <> +AttachCurrent == /\ state = "idle" /\ workers = 0 /\ owner # current /\ arms < 3 + /\ owner' = current /\ state' = "armed" /\ released' = FALSE + /\ arms' = arms+1 /\ UNCHANGED <> +Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join \/ Rearm \/ ReplaceHandle \/ AttachCurrent +Spec == Init /\ [][Next]_vars +OneOwner == workers <= 1 +JoinedBeforeRelease == released => workers = 0 +NoCatchupQueue == due \in BOOLEAN +CurrentHandleAtAdmission == workers > 0 => owner = current +============================================================================= diff --git a/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg new file mode 100644 index 0000000000..a9eb05e357 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = TRUE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg new file mode 100644 index 0000000000..6984971b3a --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = TRUE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg new file mode 100644 index 0000000000..deb0ac7c68 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg new file mode 100644 index 0000000000..46925d6f86 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = TRUE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0fb0a0bd28..920aa86a83 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,7 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore | Each `.cfg` names its spec on its first line. @@ -116,6 +117,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | ## Limits @@ -305,7 +307,7 @@ java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_red_noInterna The authored LIGHT receipts report exhaustive safe searches at 2,700 and 25,550 states, plus the expected mutant/witness failures. Source and configs are copied -from the sealed `claude05-walreclaim-tla-r0-20261119` artifact with line-ending +from the sealed authoring artifact with line-ending normalization only. Those are prior author runs, not a claim that this PR reran TLC. This is an abstraction: physical fsync success, byte layout, crash recovery, both-slot retirement, timing and multiple writers remain covered by their other @@ -335,6 +337,53 @@ four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. +## Attached-volume maintenance + +`MaintenanceOwner.tla` now includes joined-stop re-arm on the same current +handle, and replacement followed by a new attachment. At most three arms and +two handles make the graph finite. Local review-fold run 2026-11-21 03:47 UTC, +TLC2.19 / Java21 /512MiB, jar SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: + +```sh +java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config MaintenanceOwner_safe.cfg MaintenanceOwner +``` + +Positive exited0,105generated/54distinct, queue empty, depth12. Negative configs +`overlap` exited12 at OneOwner (20/14 depth6), `early_release` at +JoinedBeforeRelease (25/14 depth6), and `stale_rearm` at +CurrentHandleAtAdmission (50/33 depth8). Unique `-metadir` paths were used. +Native tests separately bind replica/epoch/endpoint and current handle/layer, +witness cancellation while held, and same-handle stop/join/re-arm. This finite +model does not establish physical-I/O cancellation or a fleet scheduling bound. + +`ScopedMaintenanceGC.tla` extends S9's scope correspondence: three keys across +two volumes, one foreign-only root, independent local coverage and crash/config +invalidation. `ScopedMaintenanceGC_safe.cfg` checks foreign-root preservation, +local candidate scope and coverage ownership: 20 generated / 10 distinct states, +depth 9, with the same TLC/jar. Its three negative configs narrow +the root domain, widen reclamation or import namespace coverage. Native tests +exercise the persisted mark records and real catalog root traversal; the finite +model abstracts the complete mark and grace, whose timing remains in S9. +No 50/200-volume density or metadata-RPC qualification is claimed; automatic GC +remains opt-in, while periodic HEAD capture and retention are enabled by the CLI. + +The unchanged S9 timing models were replayed with the same TLC/jar: +`cfg/S9_rule_G4.cfg` (`RetentionGCTiming`, D=2/G=4/MD=1/MaxT=10) +passed with 26,341 generated / 10,798 distinct states, depth 23; +`cfg/S9b_G3_MD1.cfg` (`RetentionGCMulti`, G=3/MD=1/MaxT=12) +passed with 11,303 / 5,743, depth 23. + +`cfg/Maintenance_lifecycle.cfg` replays unchanged `ChunkLifecycleFixed` with +one snapshot caller/deleter, MaxHostOps=1 and MaxRuns=1, fork/delete/create, +lost replies/pending/sweep enabled. Safety invariants and HeadMonotone passed: +42,133,769 generated / 7,224,016 distinct states, depth 47 (TLC 2.19, same jar). +This config permits terminal stuttering (`CHECK_DEADLOCK FALSE`); it does not +prove deadlock freedom. The original `Fix_mix_small` replay stopped with a +terminal deadlock at depth 23 after 28,242,446 / 5,592,191 states (callers Done, +gc_loop); it is not reported as a completed green run. No protocol guards in +ChunkLifecycleFixed were changed. + `PrecopyFixedAdmission.tla` checks cost admission over five physical rounds. A known estimate fits the 1.2-second allowance, or uses the five-second declared freeze limit when it is at least 90% of the previous comparable known estimate or on the final @@ -408,3 +457,41 @@ The same command with each negative config exited12 at its intended invariant: third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last `AuthorityAtPublication`. Source tests separately check time/metadata handling, no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch. + + +## GC clock allowance + +`GCClockSkew.tla` checks the time-admission portion of M6 GC: pairwise clock +bias -S/0/+S, timestamp truncation 0/Q, and retaining future-dated roots while +an independently eligible object progresses. It abstracts the existing complete +root scan, exclusive copy settlement and higher-epoch guards; it does not prove +those protocols or safety with clocks outside the configured bound. + +Local TLC2.19 / Java21 run 2026-11-21, jar SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: +`java -Xmx512m -cp tlc2.TLC -config GCClockSkew_safe.cfg GCClockSkew` +from `docs/spec`, each run with its own metadir. Bounds G=3, S=1, Q=1, +Born=10, MaxT=17. Positive exhausted: exit0, 96 generated / 96 distinct states, +queue empty, depth16. `GCClockSkew_no_skew.cfg` exited12 at `NoEarlyExpiry` +(43/43, depth8); `GCClockSkew_no_resolution.cfg` exited12 at `NoEarlyExpiry` +(44/44, depth8); `GCClockSkew_abort_future.cfg` exited12 at +`IndependentProgress` (11/11, depth2). Source tests independently cover +persisted-mark compatibility, future-clock resets and authority-preserving expiry. + + +## Per-object GC DELETE progress + +`GCDeleteProgress.tla` models the narrow sweep transition after a complete, +authorised mark: three ordered candidates, first DELETE definitively rejected, +later deletes accepted. It checks that the rejected fid is never reported +successful, the failure is visible, and later candidates progress. Root/epoch +admission, elapsed coverage and persistence are outside this small abstraction; +source tests retain those guards and reopen independent collectors between passes. + +Local TLC2.19 / Java21, same jar SHA256 as GCClockSkew above, 2026-11-21: +`java -Xmx512m -cp tlc2.TLC -config GCDeleteProgress_safe.cfg GCDeleteProgress` +from `docs/spec`, separate metadirs. Positive exhausted exit0, 4 generated /4 +distinct states, depth4. `GCDeleteProgress_stop.cfg` exits12 at `LaterProgress` +(2 generated /2 distinct, depth2). The HTTP source red uses an actual400 and +checks later reclamation, retained failed tombstones, younger-object progress +across separate collectors and permanent no-rebind behavior. diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla new file mode 100644 index 0000000000..796850fe6a --- /dev/null +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -0,0 +1,173 @@ +------------------------------ MODULE RestoreIndependence ------------------------------ +(***************************************************************************) +(* Independent restore: restore a snapshot into a volume that ends up *) +(* owning all its chunks, with no lineage to the source. *) +(* 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) *) +(* ; 2 hydrate (local, not modelled beyond "local" flags); 3 OWNING = *) +(* batch cuts, each re-uploads up to Batch V-owned indexes as T-owned fids *) +(* (intent -> upload -> HEAD CAS); 4 marker after the last V ref is gone, *) +(* then drop the claim. A GC (machine E, reduced: deletes only fids that *) +(* 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 *) +(* spec models only what the restore adds, not the superseded list/grace. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NIdx, \* indexes of the volume (1..NIdx) + Batch, \* indexes per independence batch cut + MaxCrash, \* restore-process crashes (each followed by a resume) + MaxGc, \* GC rounds + \* ---- mutants (FALSE = the design) ---- + DropClaimAtFork, \* r0 mutant: the claim on S is dropped right after the fork + CasBeforeUpload, \* batch CAS swaps a ref before its own upload is durable + ListForeign, \* the batch lists the replaced V fid for GC (rule 8 broken) + MarkerEarly, \* marker written before the last V ref is gone + MarkerBeforeCas, \* marker written before the final batch's HEAD CAS + ResumeLocal, \* a new owner trusts a local "done" flag instead of remote facts + SnapDuringRestore, \* a snapshot of T is allowed before the marker + 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 + +Idx == 1..NIdx +VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i +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>>] + +VARIABLES + store, \* Fids -> "none" | "pres" | "del" + vlive, \* V still exists (its HEAD roots V fids) + slive, \* S exists + claim, \* the restore's claim on S + thead, \* T's HEAD: Idx -> fid, or "none" before the fork + step, \* restore step: "c" claimed | "f" forked | "own" | "done" + up, \* T fids uploaded durably but not yet in HEAD (current batch) + marker, \* restore/INDEPENDENT exists (remote) + 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 + +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} +Roots == (IF vlive THEN SFids ELSE {}) + \cup (IF slive 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) + +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 + +\* step 0: S is sealed (given) and claimed +Claim == step = "start" /\ slive /\ claim' = TRUE /\ step' = "c" + /\ UNCHANGED <> + +\* 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. +ForkBegin == step = "c" /\ step' = "fk" + /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ thead' = VF /\ step' = "own" + /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) + /\ UNCHANGED <> + +\* 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} +Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload + /\ (\A i \in B : store[VF[i]] = "pres") \* reads its local copy (filled from V) + /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] + /\ up' = {TF[j] : j \in B} + /\ UNCHANGED <> +\* 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]] + /\ gclist' = (IF ListForeign THEN gclist \cup {VF[i] : i \in {j \in Idx : TF[j] \in up}} ELSE gclist) + /\ up' = {} + /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) + /\ UNCHANGED <> +\* 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 <> +UploadLate == CasBeforeUpload /\ step = "own" + /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" + /\ store' = [store EXCEPT ![TF[i]] = "pres"] + /\ UNCHANGED <> + +\* 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 <> +DropClaim == marker /\ claim /\ claim' = FALSE + /\ UNCHANGED <> + +\* a snapshot of T: refused before the marker (unless the mutant allows it) +SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) + /\ tsnap' = THeadFids + /\ UNCHANGED <> + +\* crash of the restore process; the new owner resumes from remote facts (thead, marker) +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") + /\ crashes' = crashes + 1 + /\ UNCHANGED <> + +\* user deletes V; retention deletes S when nothing holds it +DeleteV == vlive /\ vlive' = FALSE + /\ UNCHANGED <> +DeleteS == slive /\ ~ SHeld /\ slive' = FALSE + /\ 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 <> + +Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate + \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + +Spec == Init /\ [][Next]_vars + +---------------------------------------------------------------------------- +\* INV-RESTORE-NO-GAP: every index of T's HEAD resolves to a present fid +NoGap == thead = NoHead \/ \A i \in Idx : store[thead[i]] = "pres" +\* INV-RESTORE-INDEPENDENT: after the marker, T roots no V fid (HEAD or snapshot) +Independent == marker => (VRefs = {} /\ \A f \in tsnap : f[1] = "T") +\* INV-RESTORE-NO-FOREIGN-LIST: a restore never lists a V fid +NoForeignList == \A f \in gclist : f[1] = "T" +\* INV-RESTORE-CLAIM-UNTIL-INDEPENDENT +ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim +\* r0.2 option 1: the claim covers exactly the window in which T exists without a HEAD +ClaimUntilHead_Inv == (step = "fk") => claim +\* lifecycle independence: after the marker and the claim drop, nothing of T holds S +LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* 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 +\* 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) +============================================================================= diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC.tla b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla new file mode 100644 index 0000000000..e04fda664f --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla @@ -0,0 +1,25 @@ +------------------------ MODULE ScopedMaintenanceGC ------------------------ +EXTENDS Naturals, FiniteSets, TLC +CONSTANTS TraceForeign, LocalSweep, ImportGlobal +VARIABLES marks, localPasses, deleted, complete, early +vars == <> +Keys == {"rooted", "local", "foreign"} +Init == /\ marks = 0 /\ localPasses = 0 /\ deleted = {} /\ complete = FALSE /\ early = FALSE +\* A foreign-volume intent is the only root of the target's local key. +Roots == IF TraceForeign THEN {"rooted"} ELSE {} +Start == /\ ~complete /\ complete' = TRUE /\ UNCHANGED <> +Finish == /\ complete /\ localPasses < 2 + /\ LET coverage == IF ImportGlobal THEN 1 ELSE marks + scope == IF LocalSweep THEN {"rooted", "local"} ELSE Keys + IN /\ deleted' = deleted \cup (IF coverage = 1 THEN scope \ Roots ELSE {}) + /\ early' = (early \/ (coverage = 1 /\ localPasses = 0)) + /\ marks' = 1 + /\ localPasses' = localPasses + 1 /\ complete' = FALSE +CrashOrConfigChange == /\ marks' = 0 /\ localPasses' = 0 /\ complete' = FALSE + /\ UNCHANGED <> +Next == Start \/ Finish \/ CrashOrConfigChange +Spec == Init /\ [][Next]_vars +ForeignRootSurvives == "rooted" \notin deleted +OwnCoverageOnly == ~early +ForeignCandidatesUntouched == "foreign" \notin deleted +============================================================================= diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg new file mode 100644 index 0000000000..25bf2c2d66 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = TRUE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg new file mode 100644 index 0000000000..80c34ce5a2 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = FALSE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg new file mode 100644 index 0000000000..b428924006 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg new file mode 100644 index 0000000000..49e7263fa9 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = FALSE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/WALReclaim.tla b/seaweed-block/docs/spec/WALReclaim.tla index 4895234f72..3214a648d2 100644 --- a/seaweed-block/docs/spec/WALReclaim.tla +++ b/seaweed-block/docs/spec/WALReclaim.tla @@ -1,6 +1,6 @@ ----------------------------- MODULE WALReclaim ----------------------------- (***************************************************************************) -(* Liveness of v3 WAL reclaim under write pressure (claude05, 2026-11-19). *) +(* Liveness of v3 WAL reclaim under write pressure (2026-11-19). *) (* Abstracts core/storage at seaweed-block main 39f11d6a: *) (* head = WAL head LSN (records appended) *) (* wack = durable WAL frontier; today advanced only by Sync *) @@ -14,7 +14,7 @@ (* (walstore.go:829-832, admission at :850). A cut takes the capture *) (* write lock; Go's RWMutex makes a pending writer block new readers. *) (* *) -(* InternalOn: the fix under review (codex03 design r0) - under pressure *) +(* InternalOn: the fix under review - under pressure *) (* the store makes its own WAL durable (wack := head) with no guest Sync. *) (* Mut: *) (* "none" the design *) diff --git a/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg new file mode 100644 index 0000000000..c257d3d0a0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg @@ -0,0 +1,20 @@ +\* Maintenance safety replay: one snapshot caller/deleter, one host operation/run. +SPECIFICATION Spec +CONSTANTS + SnapCallers = {s1} + Deleters = {d1} + ForkOn = TRUE + DelSnapOn = TRUE + CreateOn = TRUE + MaxHostOps = 1 + MaxRuns = 1 + LostReply = TRUE + PendingOn = TRUE + SweepOn = TRUE + defaultInitValue = defaultInitValue +SYMMETRY Symm +INVARIANT TypeOK GCSafe SnapOnlyExplicitDelete AckedChunksSurvive CommitClean NoPublishAfterCommit NoIdReuse GiveBackReleases +PROPERTY HeadMonotone + +\* Bounded terminal states may stutter; safety, not deadlock freedom. +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg new file mode 100644 index 0000000000..70a61b6cee --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = TRUE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg new file mode 100644 index 0000000000..5dae146b29 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg @@ -0,0 +1,24 @@ +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 = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg new file mode 100644 index 0000000000..82592e7bc4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = TRUE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg new file mode 100644 index 0000000000..560a8c4cc7 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = TRUE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg new file mode 100644 index 0000000000..38b2ecc46a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = TRUE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg new file mode 100644 index 0000000000..b2ed698e1f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg @@ -0,0 +1,24 @@ +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 = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg new file mode 100644 index 0000000000..383cbda367 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = TRUE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + 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 new file mode 100644 index 0000000000..6c115a1f13 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg @@ -0,0 +1,24 @@ +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_red_snap_during_restore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg new file mode 100644 index 0000000000..dce285726d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = TRUE + RetentionIgnoresMarker = FALSE + 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 new file mode 100644 index 0000000000..682ed72f1f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -0,0 +1,24 @@ +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 = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg new file mode 100644 index 0000000000..bf269afeae --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 2 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg new file mode 100644 index 0000000000..34c9db075b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 4 + Batch = 2 + MaxCrash = 2 + MaxGc = 4 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg new file mode 100644 index 0000000000..9590e854ad --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg @@ -0,0 +1,24 @@ +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 +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg new file mode 100644 index 0000000000..1ab2298c47 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg @@ -0,0 +1,25 @@ +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 +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote + W_CrashResume diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg new file mode 100644 index 0000000000..3d9c60ac18 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg @@ -0,0 +1,25 @@ +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 = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote + W_Done diff --git a/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md b/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md index c41b16790c..e24dd426bb 100644 --- a/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md +++ b/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md @@ -30,7 +30,7 @@ component first -> product-backed gate only when the component boundary is green Milestone bundle: ```text -V:/share/g15d-k8s/testops-runs/iscsi-pressure-close/20260511-091432-d7f6 +/g15d-k8s/testops-runs/iscsi-pressure-close/20260511-091432-d7f6 ``` Remote product checkout used for the milestone gate: @@ -130,7 +130,7 @@ addressed them: Runner-native gate: ```text -swblock run --results-dir V:/share/g15d-k8s/testops-runs/iscsi-pressure-close \ +swblock run --results-dir /g15d-k8s/testops-runs/iscsi-pressure-close \ --env product_root=/tmp/seaweed-block-plan-roadmap-refresh-devrun \ --env ssh_key=C:/work/dev_server/testdev_key \ testops/scenarios/iscsi-os-initiator-compat-chain.yaml @@ -141,7 +141,7 @@ Result: ```text === iscsi-os-initiator-compat-chain === PASS (1m13.531s) 22 actions: 22 passed, 0 failed -run bundle: V:\share\g15d-k8s\testops-runs\iscsi-pressure-close\20260511-091432-d7f6 +run bundle: \g15d-k8s\testops-runs\iscsi-pressure-close\20260511-091432-d7f6 ``` The milestone gate re-proves the real Linux kernel initiator path after the diff --git a/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md b/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md index 5d571c4bcb..597acb24e8 100644 --- a/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md +++ b/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md @@ -29,7 +29,7 @@ From the Windows controller: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/cluster-ops-inventory ` + --results-dir /g15d-k8s/testops-runs/cluster-ops-inventory ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/cluster-ops-inventory-chain.yaml diff --git a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md index 9e8b020bf8..3026c649cc 100644 --- a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md +++ b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md @@ -9,7 +9,7 @@ Dev live gate evidence: - Scenario: `testops/scenarios/cluster-ops-inventory-chain.yaml` - Run id: `20260512-202811-1aa7` -- Bundle: `V:/share/g15d-k8s/testops-runs/lifecycle-gate/20260512-202811-1aa7` +- Bundle: `/g15d-k8s/testops-runs/lifecycle-gate/20260512-202811-1aa7` - Result: PASS, 9/9 phases, 73/73 actions ## Product Question @@ -201,7 +201,7 @@ Runner-native gate: ```powershell swblock run ` - -results-dir V:/share/g15d-k8s/testops-runs/lifecycle-gate ` + -results-dir /g15d-k8s/testops-runs/lifecycle-gate ` -env product_root=/tmp/seaweed-block-lifecycle-devrun ` -env ssh_key=C:/work/dev_server/testdev_key ` testops/scenarios/cluster-ops-inventory-chain.yaml diff --git a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md index e1ca0009c0..9092bb704a 100644 --- a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md +++ b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md @@ -10,7 +10,7 @@ Runner commit: sw-test-runner-standalone @ 6ec7abd (swblock 15.9 MB Windo Host: m02 (192.168.1.184) — Ubuntu 24.04.3 LTS / k3s v1.34.4+k3s1 Run id: 20260512-203746-8cf2 (QA-owned re-run) Dev run id (ref): 20260512-202811-1aa7 -Bundle: V:/share/g15d-k8s/testops-runs/lifecycle-gate/20260512-203746-8cf2 +Bundle: /g15d-k8s/testops-runs/lifecycle-gate/20260512-203746-8cf2 Scenario: testops/scenarios/cluster-ops-inventory-chain.yaml ``` diff --git a/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md b/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md index 830add77fd..235e6b4af6 100644 --- a/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md +++ b/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md @@ -29,7 +29,7 @@ Happy path: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/same-node-alpha-attach ` + --results-dir /g15d-k8s/testops-runs/same-node-alpha-attach ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/same-node-alpha-attach-chain.yaml @@ -39,7 +39,7 @@ Negative fixture: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/same-node-alpha-attach-negative ` + --results-dir /g15d-k8s/testops-runs/same-node-alpha-attach-negative ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/same-node-alpha-attach-negative-chain.yaml diff --git a/seaweed-block/internal/docs/ref/product-positioning-v1.md b/seaweed-block/internal/docs/ref/product-positioning-v1.md index f12b63680b..f3490eff08 100644 --- a/seaweed-block/internal/docs/ref/product-positioning-v1.md +++ b/seaweed-block/internal/docs/ref/product-positioning-v1.md @@ -366,7 +366,7 @@ by the SRA/RDMA project, not as a Kubernetes node for seaweed_block. |---|---| | M02 (k3s alpha lab) | `192.168.1.184`, user `testdev` | | SSH key (controller-side) | `C:/work/dev_server/testdev_key` | -| Shared SMB share | `V:/share` on Windows = `/mnt/smb/work/share` on Linux | +| Shared SMB share (``) | the internal evidence store; `/mnt/smb/work/share` on Linux | | TestOps artifact root on M02 | `/mnt/smb/work/share/g15d-k8s/-/` | | Default `KUBECONFIG` on M02 | `/etc/rancher/k3s/k3s.yaml` | | TestOps control directory (when used) | `--control-dir` flag to `sw-testops` | @@ -416,7 +416,7 @@ The `swblock` runner can drive scenarios on M02 over SSH: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/ ` + --results-dir /g15d-k8s/testops-runs/ ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/.yaml @@ -424,7 +424,7 @@ swblock run ` Scenario artifacts land under both: -- The Windows result bundle at `V:/share/g15d-k8s/testops-runs/...`, +- The Windows result bundle at `/g15d-k8s/testops-runs/...`, - The M02-side artifact dir at `/mnt/smb/work/share/g15d-k8s/-*/`. ### 9.5 Lab Hygiene After A Run diff --git a/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md b/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md index ebed5602ca..a4425ebde3 100644 --- a/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md +++ b/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md @@ -103,7 +103,7 @@ Run the full protocol release gate: ```bash swblock suite \ - --results-dir V:/share/g15d-k8s/testops-runs/protocol-release-gate-native \ + --results-dir /g15d-k8s/testops-runs/protocol-release-gate-native \ --env product_root=/tmp/seaweed-block-nvme-p4l \ --env ssh_key=C:/work/dev_server/testdev_key \ C:/work/seaweed_block/testops/suites/protocol-release-gate.yaml @@ -113,7 +113,7 @@ Validate a finished protocol release gate bundle: ```bash swblock validate-bundle --profile protocol-release-gate \ - V:/share/g15d-k8s/testops-runs/protocol-release-gate-native/ + /g15d-k8s/testops-runs/protocol-release-gate-native/ ``` ## Responsibility Boundary diff --git a/seaweed-block/testops/README.md b/seaweed-block/testops/README.md index 3f572c740d..2bab6216a4 100644 --- a/seaweed-block/testops/README.md +++ b/seaweed-block/testops/README.md @@ -154,7 +154,7 @@ controller, pointing it at the remote product checkout on m02: ```powershell swblock suite ` - --results-dir V:/share/g15d-k8s/testops-runs/protocol-release-gate-native ` + --results-dir /g15d-k8s/testops-runs/protocol-release-gate-native ` --env product_root=/tmp/seaweed-block-nvme-p4l ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/suites/protocol-release-gate.yaml @@ -164,7 +164,7 @@ Validate the bundle before manual artifact review: ```powershell swblock validate-bundle --profile protocol-release-gate ` - V:/share/g15d-k8s/testops-runs/protocol-release-gate-native/ + /g15d-k8s/testops-runs/protocol-release-gate-native/ ``` QA close evidence: @@ -264,7 +264,7 @@ Run shape: ```powershell swblock suite ` - --results-dir V:/share/g15d-k8s/testops-runs/beta-hardening-gate ` + --results-dir /g15d-k8s/testops-runs/beta-hardening-gate ` --env product_root=/tmp/seaweed-block-plan-roadmap-refresh-devrun ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/suites/beta-hardening-gate.yaml