diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md index 15de39f911..25ad685875 100644 --- a/seaweed-block/.github/pull_request_template.md +++ b/seaweed-block/.github/pull_request_template.md @@ -1 +1,26 @@ -Machine / invariants (INV ids) / spec covered: +Feature: +Machine/INV: / +Model: +Red-first: +Simplest: + + diff --git a/seaweed-block/.github/scripts/sametokens.go b/seaweed-block/.github/scripts/sametokens.go new file mode 100644 index 0000000000..c167f2429d --- /dev/null +++ b/seaweed-block/.github/scripts/sametokens.go @@ -0,0 +1,111 @@ +// Command sametokens reports whether two versions of a Go source file have the +// same tokens in the same order, ignoring comments that the compiler ignores. +// +// Usage: go run sametokens.go OLD NEW +// +// A missing file counts as empty. Directive comments are compared as tokens: +// //go:..., // +build, //line, /*line, //export; in a file that uses cgo +// (any "C" string literal, as in import "C"), every comment counts, since the +// preamble is code. Exit 0: same tokens; 1: different +// (the first difference is printed); 2: usage error or a file that does not scan. +package main + +import ( + "fmt" + "go/scanner" + "go/token" + "os" + "strings" +) + +type tok struct { + t token.Token + lit string +} + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: sametokens OLD NEW") + os.Exit(2) + } + a, err := tokens(os.Args[1]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + b, err := tokens(os.Args[2]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + for i := 0; i < len(a) || i < len(b); i++ { + if i >= len(a) || i >= len(b) || a[i] != b[i] { + fmt.Printf("token %d differs: %v vs %v\n", i, at(a, i), at(b, i)) + os.Exit(1) + } + } +} + +func at(ts []tok, i int) string { + if i >= len(ts) { + return "end of file" + } + return fmt.Sprintf("%s %q", ts[i].t, ts[i].lit) +} + +// tokens scans a file and keeps every token except comments the compiler +// ignores. An automatic semicolon is compared by kind only. +func tokens(path string) ([]tok, error) { + src, err := os.ReadFile(path) + if os.IsNotExist(err) { + return nil, nil + } else if err != nil { + return nil, err + } + fset := token.NewFileSet() + file := fset.AddFile(path, -1, len(src)) + var s scanner.Scanner + var scanErr error + s.Init(file, src, func(pos token.Position, msg string) { + if scanErr == nil { + scanErr = fmt.Errorf("%s: %s", pos, msg) + } + }, scanner.ScanComments) + var all []tok + for { + _, t, lit := s.Scan() + if t == token.EOF { + break + } + if t == token.SEMICOLON { + lit = "" + } + all = append(all, tok{t, lit}) + } + if scanErr != nil { + return nil, scanErr + } + cgo := false + for _, x := range all { + if x.t == token.STRING && x.lit == "\"C\"" { + cgo = true + } + } + var out []tok + for _, x := range all { + if x.t == token.COMMENT && !cgo && !directive(x.lit) { + continue + } + out = append(out, x) + } + return out, nil +} + +func directive(c string) bool { + for _, p := range []string{"//go:", "// +build", "//+build", "//line ", "/*line ", "//export "} { + if strings.HasPrefix(c, p) { + return true + } + } + return false +} 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..c5379d0ff5 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check-test.sh @@ -0,0 +1,153 @@ +#!/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" + + +# Kinds for PRs that change no behaviour: each is checked against its paths; +# DOCS also compares the old and new tokens of each changed non-test Go file. +# expect_kind WANT_EXIT NAME KIND OLD_GO NEW_GO [STATUS PATH]... +# OLD_GO/NEW_GO are core/x/s.go before and after ("-" = no blob for that side). +expect_kind() { + local want=$1 name=$2 k=$3 old=$4 new=$5 got=0 + shift 5 + printf '%s' "${ok/IMPL M5.Quiesce>Copy/$k} +$simplest" >"$tmp/body" + rm -rf "$tmp/blobs"; mkdir -p "$tmp/blobs/old/core/x" "$tmp/blobs/new/core/x" + [[ $old == - ]] || printf '%s' "$old" >"$tmp/blobs/old/core/x/s.go" + [[ $new == - ]] || printf '%s' "$new" >"$tmp/blobs/new/core/x/s.go" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" "$tmp/blobs" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +P=$'package x\n' +expect_kind 0 "DOCS: comment-only Go" DOCS "${P}var A = 1"$'\n' "${P}"$'// A is one.\nvar A = 1 // one\n' M docs/a.md M core/x/s.go A core/x/s_test.go +expect_kind 0 "DOCS: gofmt realignment" DOCS "${P}var A = 1"$'\n' "${P}var A = 1"$'\n' M core/x/s.go +expect_kind 0 "DOCS: block comment" DOCS "${P}var A = 1"$'\n' "${P}"$'/* doc */\nvar A = 1\n' M core/x/s.go +expect_kind 1 "DOCS: reorder" DOCS "${P}func f() { u(); p() }"$'\n' "${P}func f() { p(); u() }"$'\n' M core/x/s.go +expect_kind 1 "DOCS: build constraint comment" DOCS "$P" $'//go:build never\n\npackage x\n' M core/x/s.go +expect_kind 1 "DOCS: rune quote then // in a string" DOCS "${P}var _ = f('\"', \"http://a\")"$'\n' "${P}var _ = f('\"', \"http://b\")"$'\n' M core/x/s.go +expect_kind 1 "DOCS: line inside a raw string" DOCS "${P}var s = \`a"$'\n'"curl http://old | sh"$'\n'"\`"$'\n' "${P}var s = \`a"$'\n'"curl http://new | sh"$'\n'"\`"$'\n' M core/x/s.go +expect_kind 1 "DOCS: spaces inside a string" DOCS "${P}var s = \"a b\""$'\n' "${P}var s = \"a b\""$'\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble" DOCS "${P}// #include "$'\nimport "C"\n' "${P}// #include "$'\nimport "C"\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble, grouped import" DOCS "${P}// #include "$'\nimport (\n\t"C"\n)\n' "${P}// #include "$'\nimport (\n\t"C"\n)\n' M core/x/s.go +expect_kind 1 "DOCS: Go changed, no blob" DOCS - - M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail + +import ( + "C" +) +' "${P}// #include " DOCS - - M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail + +import ( + "C" +) +' M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $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..0021fa1a37 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Usage: spec-trace-check.sh BODY_FILE [BLOBS] < 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 ", "CHANGE ", or one of the kinds a PR that changes +# no behaviour may use, each checked against what it changes: +# DOCS (docs outside docs/spec/, tests, and non-test Go whose tokens are +# unchanged: BLOBS holds old/ and new/ for each changed non-test +# Go file, compared by sametokens.go), TEST (only tests, testdata and test +# helpers), CI (only .github/). NONE is not a kind. Known limit: a docs file +# that is go:embed-ed into a binary changes behaviour under DOCS (none today). +# - 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 [BLOBS] < changes} +blobs=${2-} +here=$(cd "$(dirname "$0")" && pwd) +[[ -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_]+|DOCS|TEST|CI)$end" +kind="" +mi=$(value Machine/INV:) +if [[ -n $mi && $mi != '<'* ]]; then + if [[ ! $mi =~ $kind_re ]]; then + problem "Machine/INV: must start with IMPL ., FIX , CHANGE , DOCS, TEST or CI" + else + token=${BASH_REMATCH[1]} + if [[ ${mi#"${BASH_REMATCH[0]}"} =~ (^|[^A-Za-z0-9_])(IMPL|FIX|CHANGE|DOCS|TEST|CI)([^A-Za-z0-9_]|$) ]]; then + problem "Machine/INV: names more than one kind; a PR is exactly one kind" + else + kind=${token%% *} + fi + fi +fi + +is_test() { [[ $1 == *_test.go || $1 == testdata/* || $1 == */testdata/* || $1 == */testutil/* ]]; } +# docs/spec holds the models: changing one is not a docs change. +is_doc() { [[ $1 != docs/spec/* ]] && [[ $1 == *.md || $1 == docs/* ]]; } +core=0 +paths=() +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; } + paths+=("$path") + 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 + +case $kind in +CI) + for p in ${paths[@]+"${paths[@]}"}; do + [[ $p == .github/* ]] || problem "kind CI: $p is outside .github/ (scripts/ holds shipped install and deploy scripts)" + done + ;; +TEST) + for p in ${paths[@]+"${paths[@]}"}; do + is_test "$p" || problem "kind TEST: $p is not a test, testdata or test helper" + done + ;; +DOCS) + gofiles=() + for p in ${paths[@]+"${paths[@]}"}; do + if is_doc "$p" || is_test "$p"; then continue; fi + if [[ $p == *.go ]]; then gofiles+=("$p"); continue; fi + problem "kind DOCS: $p is neither docs, a test, nor Go" + done + if ((${#gofiles[@]})); then + if [[ -z $blobs || ! -d $blobs ]]; then + problem "kind DOCS: non-test Go changed but no old/new blobs were given to compare" + else + # Built here, not run with "go run": that would take the .go + # arguments as more source files of the program. + bin=$(mktemp -d) + trap 'rm -rf "$bin"' EXIT + if ! go build -o "$bin/sametokens" "$here/sametokens.go"; then + echo "spec-trace: could not build sametokens.go; the DOCS check did not run" >&2 + exit 2 + fi + for p in "${gofiles[@]}"; do + if [[ ! -e $blobs/old/$p && ! -e $blobs/new/$p ]]; then + problem "kind DOCS: $p has no old or new blob, so it was not compared" + continue + fi + rc=0 + "$bin/sametokens" "$blobs/old/$p" "$blobs/new/$p" >/dev/null || rc=$? + case $rc in + 0) ;; + 1) problem "kind DOCS: $p changes more than comments (its Go tokens differ)" ;; + *) + echo "spec-trace: sametokens failed on $p (exit $rc); the DOCS check did not run" >&2 + exit 2 + ;; + esac + done + fi + fi + ;; +esac + +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..2e09b1c3cb --- /dev/null +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -0,0 +1,62 @@ +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: + # github.sha is the tip of the base branch when the event fires; the + # PR's base.sha can predate this workflow's own scripts. + ref: ${{ github.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 + # Old and new blobs of each changed non-test Go file, for kind DOCS + # (objects only; nothing from the PR is built or run). + mb=$(git merge-base "$BASE" "$HEAD") + git diff --name-only --no-renames -z "$mb" "$HEAD" -- "*.go" ":(exclude)*_test.go" | + while IFS= read -r -d "" p; do + mkdir -p "blobs/old/$(dirname "$p")" "blobs/new/$(dirname "$p")" + git show "$mb:$p" >"blobs/old/$p" 2>/dev/null || rm -f "blobs/old/$p" + git show "$HEAD:$p" >"blobs/new/$p" 2>/dev/null || rm -f "blobs/new/$p" + done + mkdir -p blobs + bash .github/scripts/spec-trace-check.sh body.txt blobs 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) } @@ -89,9 +98,6 @@ func validateChunkFlags(f flags) error { if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") } - if c.dirtyThreshold < 0 { - return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) - } return nil } @@ -106,14 +112,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 +140,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 +159,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..df897f59b0 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,33 +31,37 @@ 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 != 0 || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC { + t.Fatalf("scheduler defaults interval %s, want capture off (0), maintenance 1h and GC off", d.chunk.captureInterval) + } + on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=15m")) + if err != nil || on.chunk.captureInterval != 15*time.Minute { + t.Fatalf("opting in to a 15m periodic cut: %+v %v", on.chunk, err) } off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", - "--chunk-capture-interval=0", "--chunk-dirty-threshold=0")) - if err != nil || off.chunk.captureInterval != 0 || off.chunk.dirtyThreshold != 0 { - t.Fatalf("disabling both triggers: %+v %v", off.chunk, err) + "--chunk-capture-interval=0")) + if err != nil || off.chunk.captureInterval != 0 { + t.Fatalf("disabling the timer: %+v %v", off.chunk, err) } if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore")); err != nil { 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", "--chunk-filer=x:1", "--chunk-control-endpoint"), "zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"), "too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"), - "negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), - "threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), } for name, args := range refused { @@ -121,3 +125,13 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) { t.Fatalf("chunk holder %q, want m02/r1", got) } } + +// --chunk-dirty-threshold is gone: a cut stages by the +// copy-on-write budget (M5 Stage), so the flag never had an effect. A unit +// that still passes it fails at start. +func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "flag provided but not defined") { + t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ca2a80a683..6f17805b6b 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,11 +203,12 @@ 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 0: off; when set, at least 5m)") + 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)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") @@ -249,8 +250,8 @@ func parseFlags(args []string) (flags, error) { return flags{}, err } memoryFlagSet := false - fs.Visit(func(f *flag.Flag) { - if f.Name == "memory-limit-mib" { + fs.Visit(func(fl *flag.Flag) { + if fl.Name == "memory-limit-mib" { memoryFlagSet = true } }) @@ -658,10 +659,13 @@ 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 cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..7942b7a517 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -42,6 +42,33 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { return c, c.Close, nil } +// checkSingleFiler is the start check of a command that writes chunk +// metadata: block metadata goes through exactly one filer, the +// same rule blockvolume enforces at start. Tests replace it. +var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { + if s, ok := f.(*chunkstore.SWFS); ok { + return s.CheckSingleFiler(ctx) + } + return nil +} + +// refuseUnlessSingleFiler runs the start check within the command's own +// timeout (a stalled filer or master cannot hold the command longer); exit +// >= 0 means refused. +func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + err := checkSingleFiler(ctx, f) + switch { + case err == nil: + return -1 + case errors.Is(err, chunkstore.ErrNotSingleFiler): + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + default: + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "single-filer start check: "+err.Error(), true) + } +} + func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) @@ -259,7 +286,9 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { // chunkCatalog opens the catalog under --chunk-path on --chunk-filer. // It returns exit -1 on success, else the exit code after reporting. -func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { +// chunkCatalog dials the filer and opens the catalog; a command that writes +// (writes) first passes the single-filer start check. +func chunkCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } @@ -267,6 +296,12 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto if err != nil { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } + if writes { + if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { + _ = closeFn() + return nil, nil, exit + } + } cat, err := chunkstore.NewCatalog(f, base) if err != nil { _ = closeFn() @@ -364,7 +399,7 @@ func chunkSnapshots(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -392,7 +427,7 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || name == "" { return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -428,7 +463,7 @@ func chunkFork(args []string, stdout, stderr io.Writer) int { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) } - cat, closeFn, exit := chunkCatalog("fork", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("fork", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -456,7 +491,7 @@ func chunkShow(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("show", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("show", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..fb46e3bc85 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -27,7 +27,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace") fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address") fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only") - fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (must exceed the operation deadline plus mark time)") + fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)") fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry") fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls") if e := fs.Parse(args); e != nil { @@ -41,6 +41,11 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { return chunkResult("gc", nil, e, stdout, stderr) } defer closeFn() + if apply { + if exit := refuseUnlessSingleFiler("gc", f, timeout, stdout, stderr); exit >= 0 { + return exit + } + } blobs, ok := f.(chunkstore.BlobDeleter) if !ok { return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false) 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/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index 7b9702672c..dee26ad7a7 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -31,7 +31,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("usage", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -74,7 +74,7 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { if setPolicy && dryRun { return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) } - cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go new file mode 100644 index 0000000000..05ff3c2399 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// Every ops chunk command that writes chunk metadata runs the +// single-filer start check before it reads or writes anything, and refuses +// when the filer is not the only one of its group; read-only commands (and +// read-only modes) do not run it. +func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + writing := map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "fork": append([]string{"ops", "chunk", "fork", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "r"}, filer...), + "retain": append([]string{"ops", "chunk", "retain", "--volume", "v1"}, filer...), + "volume-delete": append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } + for name, args := range writing { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } + readOnly := map[string][]string{ + "snapshots": append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, filer...), + "show": append([]string{"ops", "chunk", "show", "--volume", "v1"}, filer...), + "usage": append([]string{"ops", "chunk", "usage", "--volume", "v1"}, filer...), + "retain --dry-run": append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, filer...), + "gc (read-only)": append([]string{"ops", "chunk", "gc", "--master", "m:1"}, filer...), + } + for name, args := range readOnly { + before := checks + var out, errb bytes.Buffer + run(args, &out, &errb) + if checks != before { + t.Errorf("%s: a read-only command ran the start check", name) + } + } +} + +// The start check runs within the command's own --timeout: a check stalled +// on its filer or master (here one that blocks until its context ends) ends +// the command at the timeout, as a retryable refusal. +func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"} + for name, args := range map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } { + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s: a stalled start check held the command past its 200ms --timeout", name) + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("%s: exit %d, out %q; want a retryable remote_unavailable refusal", name, code, out.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 52e05da0cc..0413f1709f 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -46,7 +46,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } 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/engine/projection.go b/seaweed-block/core/engine/projection.go index b2df857375..01e1f41418 100644 --- a/seaweed-block/core/engine/projection.go +++ b/seaweed-block/core/engine/projection.go @@ -13,16 +13,16 @@ const ( // ReplicaProjection is the operator-facing view derived from state. // Intentionally descriptive. Must NEVER be reused as control truth. type ReplicaProjection struct { - Mode Mode - RecoveryDecision RecoveryDecision - SessionKind SessionKind - SessionPhase SessionPhase - Epoch uint64 - EndpointVersion uint64 - R uint64 - S uint64 - H uint64 - Reason string + Mode Mode // the engine mode (idle, recovering, healthy, degraded) + RecoveryDecision RecoveryDecision // the recovery class the R/S/H boundaries call for + SessionKind SessionKind // the kind of the current recovery session, if any + SessionPhase SessionPhase // its phase + Epoch uint64 // the authority epoch + EndpointVersion uint64 // the endpoint version within the epoch + R uint64 // the replica's durable boundary (LSN) + S uint64 // the primary's recoverable start boundary (WAL tail LSN) + H uint64 // the primary's target boundary (head LSN) + Reason string // why the engine is in this mode or decision } // DeriveProjection computes the projection from current state. diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 3c872c4d09..ade786fa78 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -36,7 +36,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/geometry" - "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" @@ -70,9 +69,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). @@ -402,10 +404,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]) @@ -534,8 +536,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: @@ -755,11 +759,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 ( @@ -866,6 +877,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) + } + } shareToken := req.ShareToken if shareToken == "" { if shareToken, err = c.beginShare(ctx, vol, head); err != nil { @@ -1115,16 +1143,12 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, } continue // re-read: the path now holds a tombstone or the late snapshot case ref.info.State == SnapActive: - // The one mark path shared with retention: a live fork claim - // refuses. - m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) + // The one mark path shared with retention; forks do not hold it. + m, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err } - switch m { - case markClaimed: - return "", claimedErr(vol, name, live) - case markGone: + if m == markGone { continue } } @@ -1187,6 +1211,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 } @@ -1217,7 +1259,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) @@ -1237,9 +1279,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } } - // Claim the parent before using it (review of #142): one conditional - // write on the parent attempt's entry, which retention's delete mark - // is conditioned against (see retention.go). + // The deadline starts before the parent is read, and every attempt + // (a retry included) reads it again: a snapshot deleted before the read + // is refused, and one deleted after it stays rooted by GC's grace past + // readAt + deadline, the last moment this fork can publish + // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() var shareToken string if c.guard != nil { // the shared HEAD is the snapshot's, read below @@ -1247,18 +1291,13 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, remoteErr(err, "share guard for %s", req.Source) } } - snap, err := c.claimForkParent(ctx, req) + snap, err := c.readForkParent(ctx, req) if err != nil { return ForkResult{}, err } - // Read after the claim: a delete of the source marks its HEAD deleting - // before it reads claims, so either it sees this claim (and gives its - // mark back) or this read sees the mark and the fork gives the claim - // back before installing anything. if gone, err := c.volumeGone(ctx, req.Source); err != nil { return ForkResult{}, err } else if gone { - c.dropForkClaim(ctx, req, snap.attempt) return ForkResult{}, refuseDeleted(req.Source, "its snapshots cannot be forked") } if snap.geo == (Geometry{}) { @@ -1295,7 +1334,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 { @@ -1309,7 +1348,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) } } @@ -1364,115 +1403,33 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, err } if h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands - c.dropForkClaim(ctx, req, snap.attempt) // and this fork never needs the parent again + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) } if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } - c.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } -// claimForkParent adds fork req's claim to the parent attempt its -// snapshot name resolves to, conditioned on the entry being active with -// the claims read, and returns that snapshot. A parent deleting is -// refused (snapshot_deleting); a claim already there is reused. -func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { - root, err := c.volRoot(req.Source) +// readForkParent returns the published snapshot fork req names. A parent +// deleting is refused (snapshot_deleting), an absent or aborted one +// (snapshot_not_found). +func (c *Catalog) readForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) if err != nil { return SnapshotInfo{}, err } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 5; try++ { - ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) - if err != nil { - return SnapshotInfo{}, err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) - } - if ref.info.State == SnapDeleting { - return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) - } - if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { - return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - claims := decodeClaims(ref.entry) - for _, cl := range claims { - if cl == token { - return ref.info, nil - } - } - raw := ref.entry.Extended[extSnapClaims] - next := proto.Clone(ref.entry).(*filerpb.Entry) - setClaims(next, append(claims, token)) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: raw}) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a mark, another claim or a delete landed: read again - } - if err != nil { - // The claim may have landed; a retry finds and reuses it. - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, err, "fork %s: claim on %s/%s outcome unknown; retry with the same request id", req.Target, req.Source, req.Snapshot) - } - return ref.info, nil + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) } - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot) -} - -// dropForkClaim removes fork req's claim from its parent attempt once the -// fork no longer needs it (best effort: retention treats a claim whose -// target has a HEAD as dead anyway). -func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt string) { - _, _ = c.removeForkClaim(ctx, req, attempt) -} - -// removeForkClaim removes fork req's claim from its parent attempt and -// reports whether this call confirmed its removal (false with no error: -// the claim was not there). -func (c *Catalog) removeForkClaim(ctx context.Context, req ForkRequest, attempt string) (bool, error) { - root, err := c.volRoot(req.Source) - if err != nil || attempt == "" { - return false, err + if ref.info.State == SnapDeleting { + return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 3; try++ { - e, err := c.f.LookupEntry(ctx, dir, attempt) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, remoteErr(err, "read %s/%s attempt %s", req.Source, req.Snapshot, attempt) - } - claims := decodeClaims(e) - kept := claims[:0:0] - for _, cl := range claims { - if cl != token { - kept = append(kept, cl) - } - } - if len(kept) == len(claims) { - return false, nil - } - c.hook(hookClaimDrop, req.Snapshot) - // Conditioned on the state read too (review of f42e723): a - // delete that marked the entry meanwhile must never be undone by - // this stale copy. A lost condition re-reads a fresh copy. - raw := e.Extended[extSnapClaims] - next := proto.Clone(e).(*filerpb.Entry) - setClaims(next, kept) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}) - if err == nil { - return true, nil - } - if !errors.Is(err, ErrPrecondition) { - return false, remoteErr(err, "remove the claim of %s on %s/%s", req.Target, req.Source, req.Snapshot) - } + if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { + return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) } - return false, remoteErr(nil, "claim of %s on %s/%s kept changing", req.Target, req.Source, req.Snapshot) + return ref.info, nil } // AbortFork settles a dead fork for a GC sweep (W5): it claims the @@ -1506,7 +1463,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/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 44b67dffaa..b3fe22a6f5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "errors" - "path" "sort" "strings" "testing" @@ -166,22 +165,8 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { t.Fatalf("request id reused for another snapshot: %v, want target_exists", err) } - // The fork claims s1, so an explicit delete is refused. The image - // binding below still guards a - // fork made before claims existed: drop the claim as such a fork would - // never have written one. - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of a claimed parent: %v, want snapshot_claimed", err) - } - ref, _, err := c.resolveSnap(ctx, "v1", "s1") - if err != nil || ref.entry == nil { - t.Fatalf("read s1: %v", err) - } - delete(ref.entry.Extended, extSnapClaims) - if err := f.UpdateEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), ref.entry, nil); err != nil { - t.Fatal(err) - } - + // Forks do not hold their parent: the delete goes through while the + // fork is incomplete, and the image binding below guards the retry. // s1 is deleted and recreated over a newer source image. if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 7d6e23111d..2416e85f58 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,22 @@ 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 + // CASApplyBound is the margin for a publish applied after its fork's + // deadline check. Zero uses the catalog operation deadline. A publish + // known to have succeeded was applied before its context ended, and that + // context ends at readAt + deadline, so it is inside the deadline; an + // unknown outcome keeps the fork intent, which roots the keys until the + // target is resolved, with no time bound. This bound covers apply delay + // and clock-rate drift beyond those two. NewCollector requires + // Grace >= operation deadline + ClockSkew + CASApplyBound, so a snapshot + // deleted while a fork of it is in flight stays rooted until the fork can + // no longer publish (INV-SNAP-DELETE-ANY-ORDER-001). + CASApplyBound time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time } type GCRoot struct { @@ -47,10 +70,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 +106,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 @@ -86,8 +116,25 @@ type Collector struct { } func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { - 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 cat == nil || blobs == nil || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { + return nil, errors.New("chunkstore: GC requires catalog, blob deletion, 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.CASApplyBound == 0 { + cfg.CASApplyBound = cat.deadline() + } + const maxDur = time.Duration(1<<63 - 1) + d := cat.deadline() + if cfg.CASApplyBound < 0 || cfg.CASApplyBound > maxDur-d-cfg.ClockSkew { + return nil, errors.New("chunkstore: invalid GC CAS apply bound") + } + if need := d + cfg.ClockSkew + cfg.CASApplyBound; cfg.Grace < need { + return nil, fmt.Errorf("chunkstore: GC grace %v is below operation deadline %v + clock skew %v + CAS apply bound %v = %v", cfg.Grace, d, cfg.ClockSkew, cfg.CASApplyBound, need) } if cfg.Now == nil { cfg.Now = time.Now @@ -112,6 +159,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 +167,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 +261,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 +310,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 +370,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 } @@ -331,7 +392,21 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e if err = ctx.Err(); err != nil { return result, err } - if err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry); err != nil { + err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry) + if err != nil && ctx.Err() != nil { + err = ctx.Err() + } + if errors.Is(err, ErrBlobDeleteRejected) { + // INV-GC-DELETE-PROGRESS-001: a confirmed object rejection + // must not starve later candidates or invalidate a complete mark. + // Keep the fid/tombstone and retry; never record this object done. + 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 + } + if err != nil { return result, err } result.Reclaimed++ @@ -400,3 +475,11 @@ func reclaimBinding(ctx context.Context, f Filer, blobs BlobDeleter, dir string, e.Extended[extGCDeleted] = []byte("done") return f.UpdateEntry(ctx, dir, e, map[string][]byte{extFid: entry.Extended[extFid], extGCDeleted: []byte("1")}) } + +// INV-GC-CLOCK-SKEW-001: expiry uses a lower bound on elapsed time, +// never the raw difference of timestamps from different hosts. Subtracting +// separately avoids overflowing grace + skew for large configured durations. +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..ea5cfdc98f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -0,0 +1,251 @@ +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) + } +} + +// Grace must cover the operation deadline, the clock skew and the CAS apply +// bound (default: the deadline), so a snapshot deleted while a fork of it is +// in flight stays rooted until that fork can no longer publish. +func TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound(t *testing.T) { + _, b, c, g, _ := gcFixture(t) + need := c.deadline() + DefaultGCClockSkew + c.deadline() + for _, grace := range []time.Duration{0, c.deadline(), c.deadline() + DefaultGCClockSkew, need - time.Nanosecond} { + cfg := g.cfg + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = grace, 0, 0 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Errorf("accepted grace %s < deadline + skew + apply bound %s", grace, need) + } + } + cfg := g.cfg + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = need, 0, 0 + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatalf("grace = deadline + skew + apply bound: %v", err) + } + cfg.Grace, cfg.CASApplyBound = need, time.Second // an explicit, smaller bound + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatal(err) + } + cfg.CASApplyBound = -1 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatal("accepted a negative CAS apply bound") + } +} + +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..bcda46abf0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -0,0 +1,392 @@ +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) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a714cb82bc..561a5fd06e 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -8,13 +8,11 @@ import ( "path" "sort" "strconv" - "strings" "time" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" ) // Snapshot retention. @@ -34,7 +32,6 @@ import ( // + every snapshot younger than KeepYounger (a creation time in the // future, from clock skew, counts as young) // + the log-spaced keeps (below) -// + every snapshot a fork still needs // // and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs // is treated as unpinned. GC reclaims the chunks. @@ -50,34 +47,18 @@ import ( // record is removed only while it still names that attempt, so a // same-name replacement made after planning is never touched. // -// Fork parents (design from the review of #142). Protection is -// one conditional write on the parent attempt's own entry, nothing else: -// -// - Fork, before it reads the parent, adds its claim (target/request) -// to the entry's claims, conditioned on {state active, claims as read}. -// A parent already deleting is refused. -// - Retain marks an attempt deleting only conditioned on {state active, -// gen, no claims}. A lost condition re-reads and decides again. -// -// The two writes hit the same entry, so one of them sees the other: either -// the claim landed first and retain keeps the snapshot (fork_held), or the -// mark landed first and the fork refuses before installing anything. -// -// A claim is removed by the fork once its HEAD is installed. Retain removes -// (conditionally) only claims that can never matter again: the target has -// a HEAD (the fork completed, or a sweep aborted it), or the target's -// VOLUME belongs to another request (this one can never publish there). -// Any other claim keeps the snapshot, however old: a fork that died before -// publishing its VOLUME holds it until the fork is retried to completion or -// settled by AbortFork. Forks published before claims existed are still -// found by the fork-record scan (forkParentsNeeded). -// -// An explicit DeleteSnapshot goes through the same check and mark -// (markDeleting): it refuses a live claim with snapshot_claimed. +// Forks and restores do not hold their parent (INV-SNAP-DELETE-ANY-ORDER-001). +// A snapshot is deleted by retention or DeleteSnapshot whatever forks read +// it: a fork reads the parent after taking its deadline start and publishes +// its HEAD only before readAt + deadline, and GC keeps a deleted attempt +// rooted for its grace, which exceeds deadline + clock skew + CAS apply +// bound (NewCollector). A fork that reads after the delete mark gets +// snapshot_deleting or snapshot_not_found, also on a retry. A claims +// xattr left by an older version is ignored. // // A pass stopped after a mark (e.g. a lost response) leaves the attempt // deleting with its name still held; the next pass (and its dry run) lists -// it and frees the name. A deleting attempt cannot gain claims. +// it and frees the name. const ( SnapshotClassSemantic = "semantic" @@ -85,18 +66,12 @@ const ( CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" - // CodeSnapshotClaimed: an explicit delete of a snapshot a fork still - // claims. Not retryable as such: it clears - // when the fork publishes its HEAD or is aborted. - CodeSnapshotClaimed = "snapshot_claimed" DefaultKeepNewest = 10 DefaultKeepYounger = time.Hour extRetention = "retention" extRetentionRev = "retention_rev" - - extSnapClaims = "swb.snap.claims" ) // ValidateSnapshotClass refuses a class other than "", "semantic" and @@ -116,11 +91,11 @@ func (s SnapshotInfo) Pinned() bool { // RetentionPolicy is a volume's snapshot retention policy. type RetentionPolicy struct { - KeepNewest int `json:"keepNewest"` - KeepYoungerNs int64 `json:"keepYoungerNs"` - KeepHourly int `json:"keepHourly"` - KeepDaily int `json:"keepDaily"` - KeepWeekly int `json:"keepWeekly"` + KeepNewest int `json:"keepNewest"` // keep the newest N unpinned snapshots + KeepYoungerNs int64 `json:"keepYoungerNs"` // keep every snapshot younger than this (ns) + KeepHourly int `json:"keepHourly"` // keep the newest snapshot of each of the last N hours + KeepDaily int `json:"keepDaily"` // keep the newest snapshot of each of the last N days + KeepWeekly int `json:"keepWeekly"` // keep the newest snapshot of each of the last N weeks } // DefaultRetentionPolicy is the policy of a volume that never set one. @@ -217,21 +192,20 @@ type RetentionDecision struct { // The reasons a snapshot is kept. const ( - keepNewest = "newest" - keepPinned = "pinned" - keepYoung = "younger_than_policy" - keepHourly = "hourly" - keepDaily = "daily" - keepWeekly = "weekly" - keepForkParent = "fork_parent" - reasonExpired = "expired" + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + reasonExpired = "expired" ) // planRetention decides, from one listing, which snapshots policy keeps at -// now. needed names the snapshots a fork still needs. Unpinned snapshots +// now. Unpinned snapshots // are ranked newest first; equal creation times rank by name, so the plan // is deterministic. -func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision { +func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []RetentionDecision { ordered := append([]SnapshotInfo(nil), snaps...) sort.SliceStable(ordered, func(i, j int) bool { if ordered[i].CreatedNs != ordered[j].CreatedNs { @@ -280,9 +254,6 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo d.Reasons = append(d.Reasons, lk.reason) } } - if needed[s.Name] { - d.Reasons = append(d.Reasons, keepForkParent) - } d.Keep = len(d.Reasons) > 0 if !d.Keep { d.Reasons = []string{reasonExpired} @@ -314,7 +285,6 @@ type RetentionResult struct { Decisions []RetentionDecision `json:"decisions"` Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run) Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone - ForkHeld []string `json:"forkHeld"` // planned, but a fork took a hold meanwhile: kept Failed *RetentionFailure `json:"failed,omitempty"` // NotAttempted lists the expired snapshots not reached because the // pass stopped at Failed. @@ -350,13 +320,9 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio snaps = append(snaps, s) } } - needed, err := c.forkParentsNeeded(ctx, vol) - if err != nil { - return RetentionResult{}, err - } res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, - Deleted: []string{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}} - res.Decisions = planRetention(p, snaps, needed, c.now()) + Deleted: []string{}, Replaced: []string{}, NotAttempted: []string{}} + res.Decisions = planRetention(p, snaps, c.now()) var expired []RetentionDecision for _, d := range res.Decisions { if d.Keep { @@ -390,8 +356,6 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio res.Deleted = append(res.Deleted, d.Name) case retainReplaced: res.Replaced = append(res.Replaced, d.Name) - case retainForkHeld: - res.ForkHeld = append(res.ForkHeld, d.Name) } } return res, nil @@ -409,7 +373,6 @@ type retainOutcome int const ( retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed retainReplaced // the planned attempt is gone; another attempt holds the name - retainForkHeld // a live fork claim is on the attempt: kept, nothing written ) // deleteRetainedAttempt deletes the planned attempt of vol/name and only @@ -420,13 +383,9 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt if err != nil { return 0, false, err } - m, _, uncertain, err := c.markDeleting(ctx, vol, name, attempt) - if err != nil { + if _, uncertain, err := c.markDeleting(ctx, vol, name, attempt); err != nil { return 0, uncertain, err } - if m == markClaimed { - return retainForkHeld, false, nil - } return c.freeName(ctx, root, name, attempt) } @@ -435,90 +394,56 @@ type markResult int const ( markDone markResult = iota // this call marked the attempt deleting markGone // the attempt's entry is gone - markSettled // already deleting or aborted (no fork can claim it) - markClaimed // a live fork claim is on it: nothing written + markSettled // already deleting or aborted ) -// markDeleting marks attempt of vol/name deleting under the fork-claim -// rule, the one path for retention and explicit delete: the mark is -// conditioned on {state active, gen, no claims}; dead claims are cleared -// conditionally first; a lost condition re-reads and decides again. live -// lists the live claims when the result is markClaimed. uncertain -// reports, with an error, a mutation whose outcome is unknown. -func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, []string, bool, error) { +// markDeleting marks attempt of vol/name deleting, the one path for +// retention and explicit delete: the mark is conditioned on {state active, +// gen}; a lost condition re-reads and decides again. No fork claim is read +// (INV-SNAP-DELETE-ANY-ORDER-001). uncertain reports, with an error, a +// mutation whose outcome is unknown. +func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, bool, error) { root, err := c.volRoot(vol) if err != nil { - return 0, nil, false, err + return 0, false, err } dir := path.Join(root, snapsDir, name) for try := 0; try < 5; try++ { e, err := c.f.LookupEntry(ctx, dir, attempt) if errors.Is(err, ErrNotFound) { - return markGone, nil, false, nil + return markGone, false, nil } if err != nil { - return 0, nil, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) + return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) } if string(e.Extended[extSnapState]) != SnapActive { - return markSettled, nil, false, nil - } - raw := string(e.Extended[extSnapClaims]) - claims := decodeClaims(e) - live, err := c.liveClaims(ctx, vol, name, claims) - if err != nil { - return 0, nil, false, err - } - if len(live) > 0 { - return markClaimed, live, false, nil + return markSettled, false, nil } c.hook(hookChecked, name) next := proto.Clone(e).(*filerpb.Entry) - if len(claims) > 0 { - // Every claim is dead: clear them, then decide again. - delete(next.Extended, extSnapClaims) - err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)}) - if err != nil && !errors.Is(err, ErrPrecondition) && !errors.Is(err, ErrNotFound) { - return 0, nil, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) - } - continue - } next.Extended[extSnapState] = []byte(SnapDeleting) next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: e.Extended[extSnapGen], - extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], }) if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a claim, a delete or a replacement landed: decide again + continue // a delete or a replacement landed: decide again } if err != nil { - return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) } c.hook(hookMarked, name) - return markDone, nil, false, nil + return markDone, false, nil } - return 0, nil, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) -} - -// claimedErr is snapshot_claimed naming the claiming fork volumes. -func claimedErr(vol, name string, live []string) error { - targets := make([]string, 0, len(live)) - for _, cl := range live { - t, _, _ := strings.Cut(cl, "/") - targets = append(targets, t) - } - return catErr(CodeSnapshotClaimed, false, nil, "snapshot %s/%s is the parent of incomplete fork %s; it can be deleted once that fork completes or is aborted", vol, name, strings.Join(targets, ", ")) + return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) } // Test seams: hook stages in a Retain pass. const ( hookPlanned = "planned" // after planning, before any deletion - hookChecked = "checked" // an attempt's claims were read and none is live, before its mark + hookChecked = "checked" // an attempt was read active, before its mark hookMarked = "marked" // an attempt is marked deleting, before its name is freed - // hookClaimDrop: a completed fork read its parent entry to drop its - // claim, before the conditional write. - hookClaimDrop = "claim-drop" ) func (c *Catalog) hook(stage, name string) { @@ -539,61 +464,6 @@ func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (ret return 0, true, remoteErr(err, "remove the name record %s", name) } -// forkClaim is the claim a fork puts on its parent attempt. -func forkClaim(target, requestID string) string { return target + "/" + requestID } - -func decodeClaims(e *filerpb.Entry) []string { - raw := e.Extended[extSnapClaims] - if len(raw) == 0 { - return nil - } - var out []string - if json.Unmarshal(raw, &out) != nil { - return []string{string(raw)} // unreadable: kept as one live claim (safe) - } - return out -} - -func setClaims(e *filerpb.Entry, claims []string) { - if len(claims) == 0 { - delete(e.Extended, extSnapClaims) - return - } - sort.Strings(claims) - body, _ := json.Marshal(claims) - e.Extended[extSnapClaims] = body -} - -// liveClaims returns the claims on vol/name that a fork may still need: a -// claim is dead only when its target has a HEAD, or its target's VOLUME -// was made by another request (or from another parent). -func (c *Catalog) liveClaims(ctx context.Context, vol, name string, claims []string) ([]string, error) { - var live []string - for _, cl := range claims { - target, req, ok := strings.Cut(cl, "/") - if !ok || CheckVolumeID(target) != nil { - live = append(live, cl) // not ours to judge: keep the snapshot - continue - } - _, has, err := c.ReadHead(ctx, target) - if err != nil { - return nil, err - } - if has { - continue - } - v, ok, err := c.ReadVolume(ctx, target) - if err != nil { - return nil, err - } - if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) { - continue - } - live = append(live, cl) - } - return live, nil -} - // allSnapshots lists every published, not-deleting snapshot of vol, with // the attempt each name resolved to. func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { @@ -618,36 +488,3 @@ func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) after = next } } - -// forkParentsNeeded names the snapshots of vol a fork still needs by its -// published fork record: a volume whose fork record names vol and the -// snapshot, and which has no real published HEAD yet (absent or aborted). -// It covers forks published before fork holds existed; a newer fork is -// also covered, atomically, by its hold (deleteRetainedAttempt). -func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { - vols, err := c.ListVolumes(ctx) - if err != nil { - return nil, err - } - needed := map[string]bool{} - for _, other := range vols { - if other == vol { - continue - } - v, ok, err := c.ReadVolume(ctx, other) - if err != nil { - return nil, err - } - if !ok || v.Fork == nil || v.Fork.Source != vol { - continue - } - h, has, err := c.ReadHead(ctx, other) - if err != nil { - return nil, err - } - if !has || h.State == storage.ChunkHeadAborted { - needed[v.Fork.Snapshot] = true - } - } - return needed, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index 1570b55000..d04475e01c 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -143,7 +143,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) { // deadline exceeded) keeps its parent, and completes on retry; (3) a fork // that claims between retention's claim check and its mark makes the // filer refuse the mark (conditioned on no claims), so the parent is kept. -func TestIntegration_RetainHeldSchedules(t *testing.T) { +func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { c := startWeed(t) ctx := context.Background() const base = "/swblock/chunks" @@ -222,27 +222,18 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { t.Fatal(err) } cat.retainHook = nil - if len(res.Deleted) != 0 || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s02 s01]" { - t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want none / s00 / s02 s01", res.Deleted, res.Replaced, res.ForkHeld) + if fmt.Sprint(res.Deleted) != "[s02 s01]" || fmt.Sprint(res.Replaced) != "[s00]" { + t.Fatalf("retain: deleted=%v replaced=%v; want s02 s01 / s00 (forks do not hold their parent)", res.Deleted, res.Replaced) } b, err := cat.readSnap(ctx, "v1", "s00") if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) } - // An explicit delete of a claimed parent is refused. - if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err) - } + // A retry of either stopped fork reads its parent again and is refused. for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive { - t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err) + _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("fork %s retry after its parent was deleted: %v; want snapshot_not_found or snapshot_deleting", fk.target, err) } - if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}); err != nil { - t.Fatalf("fork %s retry: %v", fk.target, err) - } - } - res, err = cat.Retain(ctx, "v1", false) - if err != nil || fmt.Sprint(res.Deleted) != "[s02 s01]" { - t.Fatalf("after the forks completed: deleted=%v %v; want s02 s01 (s00 is pinned)", res.Deleted, err) } } diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index ab074525b3..0ebd5b8081 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -3,7 +3,6 @@ package chunkstore import ( "context" "errors" - "path" "strings" "testing" "time" @@ -26,7 +25,7 @@ func TestPlanRetention_RollingWindows(t *testing.T) { for _, a := range ages { snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) } - return kept(planRetention(p, snaps, nil, now)) + return kept(planRetention(p, snaps, now)) } now := at(10*time.Hour + 30*time.Minute) if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil { @@ -104,51 +103,6 @@ func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { return f, c } -// A fork that starts after the retention scan (its VOLUME published, its -// HEAD not yet) has claimed the parent: retention keeps it, and the fork -// completes on retry. -func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, _ string) { - if stage != hookPlanned { - return - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept for the fork", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want active", s, err) - } - c.retainHook = nil - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - // Completed: the hold is gone and the parent is no longer needed. - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after the fork completed: deleted=%v %v; want s01", res.Deleted, err) - } -} - -func claimsOf(t *testing.T, c *Catalog, name string) []string { - t.Helper() - ref, ok, err := c.resolveSnap(context.Background(), "v1", name) - if err != nil || !ok || ref.entry == nil { - t.Fatalf("read %s: ok=%t %v", name, ok, err) - } - return decodeClaims(ref.entry) -} - // A fork arriving after the mark finds the parent deleting and refuses // before installing anything (and leaves no claim). func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { @@ -176,105 +130,6 @@ func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { } } -// Schedule 1: retention read no claims, then a fork claims before the -// mark. The mark's condition (no claims) fails; retention reads again, -// sees the live claim and keeps the parent. -func TestCatalog_ClaimBetweenCheckAndMarkWins(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, name string) { - if stage != hookChecked || name != "s01" { - return - } - c.retainHook = nil - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent: %+v %v; want active", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/f" { - t.Fatalf("claims %v; want v2/f", got) - } -} - -// Schedule 2: a fork that claimed and died before publishing its VOLUME -// keeps the parent however much later retention runs (no lifetimes); the -// fork retried to completion releases it. -func TestCatalog_DeadForkClaimKeepsTheParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - f.failCreate = func(p string) error { - if p == catBase+"/v2/"+volumeName { - return errors.New("filer unavailable") - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err == nil { - t.Fatal("fork with a failing VOLUME create succeeded") - } - f.failCreate = nil - if _, ok, _ := c.ReadVolume(ctx, "v2"); ok { - t.Fatal("VOLUME published") - } - saved := c.now - c.SetClock(func() time.Time { return saved().Add(30 * 24 * time.Hour) }) - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.ForkHeld, ",") != "s01" { - t.Fatalf("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - if got := claimsOf(t, c, "s01"); len(got) != 0 { - t.Fatalf("claims after the fork completed: %v; want none", got) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after completion: deleted=%v %v; want s01", res.Deleted, err) - } -} - -// Schedule 3: a second request for the same target is refused without -// touching the first request's claim (claims are per target AND request, -// and a fork drops only its own, only once its HEAD exists). -func TestCatalog_RefusedSameTargetForkLeavesTheOtherClaim(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork a: %v", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "b"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("fork b (same target, other request): %v; want target_exists", err) - } - if _, err := c.Retain(ctx, "v1", false); err != nil { - t.Fatal(err) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want kept for request a", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/a" { - t.Fatalf("claims %v; want only a's, intact", got) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); err != nil { - t.Fatalf("fork a retry: %v", err) - } - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after a completed: deleted=%v %v; want s01 (b's claim dead)", res.Deleted, err) - } -} - // A failure part way reports the confirmed deletions, the failing // snapshot (uncertain: the mark's outcome is unknown) and what was not // attempted; a lost response leaves the snapshot deleting and the next @@ -355,84 +210,3 @@ func TestCatalog_UsageCountsForkHolders(t *testing.T) { t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) } } - -// An explicit delete of a snapshot an -// incomplete fork claims is refused (snapshot_claimed, not retryable, -// naming the fork); once the fork completes or is aborted the delete goes -// through. Retention and delete share the check (markDeleting). -func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v2: %v", err) - } - holdFirst(f, catBase+"/v3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s02", Target: "v3", RequestID: "g"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v3: %v", err) - } - for _, tc := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - _, err := c.DeleteSnapshot(ctx, "v1", tc.snap) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeSnapshotClaimed || ce.Retryable || !strings.Contains(ce.Detail(), tc.target) { - t.Fatalf("delete %s claimed by %s: %v; want snapshot_claimed, not retryable, naming %s", tc.snap, tc.target, err, tc.target) - } - if s, err := c.readSnap(ctx, "v1", tc.snap); err != nil || s.State != SnapActive { - t.Fatalf("%s after the refused delete: %+v %v; want active", tc.snap, s, err) - } - } - // Completed fork: its claim no longer blocks. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork v2 retry: %v", err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork completed: %q %v", got, err) - } - // Aborted fork (a sweep's tombstone): neither does its claim. - if claimed, err := c.AbortFork(ctx, "v3"); err != nil || !claimed { - t.Fatalf("abort v3: claimed=%t %v", claimed, err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork was aborted: %q %v", got, err) - } -} - -// Review of f42e723: a completed fork's claim cleanup that read the parent -// entry, then paused while an explicit delete marked it, must not write -// its stale copy back (resurrecting an unnamed snapshot as a GC root). -func TestCatalog_ClaimCleanupNeverUndoesADelete(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork: %v", err) - } - parent, err := c.readSnap(ctx, "v1", "s01") - if err != nil { - t.Fatal(err) - } - ran := false - c.retainHook = func(stage, name string) { - if stage != hookClaimDrop || name != "s01" || ran { - return - } - ran = true // the fork's HEAD exists now: its claim is dead - if _, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil { - t.Fatalf("delete during the claim cleanup: %v", err) - } - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - c.retainHook = nil - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s01"), parent.attempt) - if err != nil { - t.Fatal(err) - } - if !ran || string(e.Extended[extSnapState]) != SnapDeleting || len(e.Extended[extSnapDeletedNs]) == 0 { - t.Fatalf("ran=%t state=%q deleted_ns=%q; want the delete mark kept", ran, e.Extended[extSnapState], e.Extended[extSnapDeletedNs]) - } - if _, ok, err := c.resolveSnap(ctx, "v1", "s01"); ok || err != nil { - t.Fatalf("s01's name is back (%v)", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 10109d3916..f329ed96be 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -45,7 +44,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { for i := 0; i < 15; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(noYoung(), snaps, nil, now)) + k := kept(planRetention(noYoung(), snaps, now)) if len(k) != 10 { t.Fatalf("kept %d, want 10: %v", len(k), k) } @@ -55,7 +54,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { } } tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} - if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, nil, now)); len(k) != 1 || k["a"] == nil { + if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { t.Fatalf("tie: kept %v, want only a (name order)", k) } } @@ -71,7 +70,7 @@ func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil), snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), } - k := kept(planRetention(RetentionPolicy{}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{}, snaps, now)) if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil { t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k) } @@ -87,7 +86,7 @@ func TestPlanRetention_YoungAndClockSkew(t *testing.T) { snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil), snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil), } - k := kept(planRetention(p, snaps, nil, now)) + k := kept(planRetention(p, snaps, now)) if len(k) != 2 || k["young"] == nil || k["future"] == nil { t.Fatalf("kept %v; want young and future", k) } @@ -100,7 +99,7 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { for i := 0; i < 12; i++ { // every 30 min over the last 6 hours snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, now)) if len(k) != 3 { t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) } @@ -111,16 +110,6 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { } } -// A snapshot a fork still needs is kept whatever the policy says. -func TestPlanRetention_ForkParentKept(t *testing.T) { - now := retBase.Add(48 * time.Hour) - snaps := []SnapshotInfo{snapAt("parent", retBase, SnapshotClassSemantic, time.Time{}, nil)} - k := kept(planRetention(RetentionPolicy{}, snaps, map[string]bool{"parent": true}, now)) - if len(k) != 1 || k["parent"][0] != keepForkParent { - t.Fatalf("kept %v; want parent (fork_parent)", k) - } -} - // An agent that checkpoints every step stays bounded: one semantic // snapshot a minute for a day keeps at most N + T/step + hourly buckets. func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { @@ -132,14 +121,14 @@ func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { } now := start.Add(24 * time.Hour) bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly - if k := kept(planRetention(p, snaps, nil, now)); len(k) > bound { + if k := kept(planRetention(p, snaps, now)); len(k) > bound { t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) } // The bound holds however long the agent runs. for i := 24 * 60; i < 7*24*60; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - if k := kept(planRetention(p, snaps, nil, start.Add(7*24*time.Hour))); len(k) > bound { + if k := kept(planRetention(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) } } @@ -283,41 +272,6 @@ func TestCatalog_SnapshotClass(t *testing.T) { } } -// A fork whose HEAD is not yet written still needs its parent snapshot: -// retain keeps it; once the fork's HEAD is published it no longer does. -func TestCatalog_RetainKeepsParentOfAnIncompleteFork(t *testing.T) { - f, c, _, clock := retentionFixture(t, 3) - ctx := context.Background() - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - // The fake filer lists only directory entries it holds; a real filer - // has them for every volume directory. - 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.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - res, err := c.Retain(ctx, "v1", true) - if err != nil { - t.Fatal(err) - } - if k := kept(res.Decisions); len(k) != 1 || k["s01"] == nil || k["s01"][0] != keepForkParent { - t.Fatalf("incomplete fork: kept %v; want only s01 (fork_parent)", k) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - _ = clock - if res, err := c.Retain(ctx, "v1", true); err != nil || res.Kept != 0 { - t.Fatalf("published fork: kept %d (%v); want 0", res.Kept, err) - } -} - // publishTagged installs a HEAD for vol with chunks under keys tagged tag. func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead { t.Helper() diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go new file mode 100644 index 0000000000..35b05e3ed0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -0,0 +1,204 @@ +package chunkstore + +import ( + "bytes" + "context" + "fmt" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. + +// A fork stopped past its deadline does not keep its parent: the snapshot is +// deleted, and a retry of the same request reads the parent again and is +// refused; it never publishes from its first read. +func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + clock := time.Now() + c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances + c.OpDeadline = time.Nanosecond + if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) + } + c.OpDeadline = 0 + if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { + t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent of an incomplete fork: %q %v, want deleting", got, err) + } + _, err := c.Fork(ctx, req) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("retry after the parent was deleted: %v, want snapshot_not_found or snapshot_deleting", err) + } + if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { + t.Fatal("the retry published a HEAD from its first read of a deleted parent") + } +} + +// A delete that lands between a fork's read of its parent and its HEAD +// publish succeeds; the fork still publishes inside its deadline, and the +// target keeps every chunk after the source snapshot and volume are gone and +// GC has run past its grace. +func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x41), 2: chunkBytes(0x42)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + deleted := false + f.stallCreate = func(p string) bool { // runs before the fake takes its lock + if p == catBase+"/v2/"+headName && !deleted { + deleted = true + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Errorf("delete while the fork is in flight: %q %v", got, err) + } + } + return false + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork whose parent was deleted after its read: %v", err) + } + f.stallCreate = nil + if !deleted { + t.Fatal("the delete never ran inside the fork") + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + for i := 0; i < 3; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, err := r2.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + requireChunks(t, ctx, r2, h2, want, "fork") +} + +// An unknown publish outcome keeps the fork's intent, and that intent roots +// the parent's keys with no time bound: the snapshot deleted, the source +// volume deleted, GC run well past its grace, the keys survive while the +// intent exists. +func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x51), 1: chunkBytes(0x52)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + f.failCreate = func(p string) error { + if p == catBase+"/v2/"+headName { + return errTransport + } + return nil + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with an unknown HEAD create: %v", err) + } + f.failCreate = nil + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent: %q %v", got, err) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + intents := func() int { + list, err := f.ListEntries(ctx, path.Join(catBase, "v2", intentsDir), "", "", 0) + if err != nil { + t.Fatal(err) + } + return len(list) + } + if intents() == 0 { + t.Fatal("the unknown publish left no intent") + } + for i := 0; i < 4; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) // far past the grace + } + if intents() == 0 { + t.Fatal("GC settled the fork intent without the target being resolved") + } + r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + requireChunks(t, ctx, r1, h, want, "parent (fork intent still present)") +} + +// requireChunks fails unless h names exactly the indexes of want and each one +// reads back want's bytes (a missing index cannot pass by iterating h alone). +func requireChunks(t *testing.T, ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte, what string) { + t.Helper() + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("%s: %v", what, err) + } +} + +func chunksMismatch(ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte) error { + if len(h.Chunks) != len(want) { + return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), len(want)) + } + for idx, data := range want { + ref, ok := h.Chunks[idx] + if !ok { + return fmt.Errorf("HEAD lost chunk %d", idx) + } + if got, err := r.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, data) { + return fmt.Errorf("chunk %d unreadable or changed: %v", idx, err) + } + } + return nil +} + +// The check refuses a HEAD that lost an index, even when every chunk it +// still names reads back correctly. +func TestSnapshotDelete_ChunkCheckCatchesAMissingIndex(t *testing.T) { + f, b, _, h := catalogFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + want := map[uint64][]byte{} + missing := uint64(0) + for idx, ref := range h.Chunks { + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + want[idx] = data + if idx >= missing { + missing = idx + 1 + } + } + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("the matching HEAD failed the check: %v", err) + } + want[missing] = chunkBytes(0x62) // an index the HEAD does not name + if err := chunksMismatch(ctx, r, h, want); err == nil { + t.Fatal("a HEAD missing an expected chunk passed the check") + } +} 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/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index d8ec500960..472c1ed877 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -38,28 +38,28 @@ import ( // SnapshotUsage is one snapshot's share of a volume's space. type SnapshotUsage struct { - Name string `json:"name"` - CreatedNs int64 `json:"createdNs"` - Class string `json:"class"` - Pinned bool `json:"pinned"` - Chunks int `json:"chunks"` - ExclusiveBytes uint64 `json:"exclusiveBytes"` + Name string `json:"name"` // the snapshot name + CreatedNs int64 `json:"createdNs"` // when it was created (Unix ns) + Class string `json:"class"` // its retention class + Pinned bool `json:"pinned"` // retention never deletes it + Chunks int `json:"chunks"` // chunks its manifest references + ExclusiveBytes uint64 `json:"exclusiveBytes"` // bytes no other holder references: what deleting it makes eligible for GC } // VolumeUsage is a volume's space accounting. type VolumeUsage struct { - VolumeID string `json:"volumeID"` - ChunkBytes uint64 `json:"chunkBytes"` // one full chunk - LiveChunks int `json:"liveChunks"` - LiveBytes uint64 `json:"liveBytes"` - Snapshots []SnapshotUsage `json:"snapshots"` - ManifestBindings int `json:"manifestBindings"` - ManifestBytes uint64 `json:"manifestBytes"` - StoredBindings int `json:"storedBindings"` - StoredBytes uint64 `json:"storedBytes"` - StoredUpperBound bool `json:"storedUpperBound"` - Policy RetentionPolicy `json:"policy"` - PolicySet bool `json:"policySet"` + VolumeID string `json:"volumeID"` // the volume + ChunkBytes uint64 `json:"chunkBytes"` // one full chunk + LiveChunks int `json:"liveChunks"` // chunks HEAD references + LiveBytes uint64 `json:"liveBytes"` // their bytes (the last chunk clipped) + Snapshots []SnapshotUsage `json:"snapshots"` // one entry per live snapshot + ManifestBindings int `json:"manifestBindings"` // stored chunk-key bindings some manifest references + ManifestBytes uint64 `json:"manifestBytes"` // their exact bytes + StoredBindings int `json:"storedBindings"` // all chunk-key bindings in the filer, referenced or not + StoredBytes uint64 `json:"storedBytes"` // their bytes; unreferenced ones counted at full chunk size + StoredUpperBound bool `json:"storedUpperBound"` // StoredBytes is an upper bound (some bindings are unreferenced) + Policy RetentionPolicy `json:"policy"` // the snapshot retention policy in force + PolicySet bool `json:"policySet"` // the volume set its own policy (else the default applies) } // chunkSize is the byte size of chunk index idx under g. diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go index b1f4501a4d..28cc7b0e09 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go @@ -120,7 +120,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) { // GC: two marks past grace reclaim exactly A (only S1 and w2 reached // it) and D (only w2); B and C (w1's HEAD and S2) stay. - grace := 2 * DefaultOpDeadline + grace := 3 * DefaultOpDeadline // >= deadline + skew + CAS apply bound at := time.Now().Add(3 * grace) g, err := NewCollector(cat, cl, GCConfig{Grace: grace, IntentTTL: time.Hour, Now: func() time.Time { return at }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go index 0bb854fa48..c554bb76f0 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go @@ -331,7 +331,7 @@ func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { } } -// A fork that claims during the delete mark sees the deleting source and +// A fork that reads during the delete mark sees the deleting source and // refuses before installing anything; the delete refuses too (the forked // snapshot exists) and reverts. func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { @@ -355,9 +355,6 @@ func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { t.Fatal("the refused fork published its VOLUME") } - if got := claimsOf(t, c, "s1"); len(got) != 0 { - t.Fatalf("the refused fork left claims %v", got) - } } // P2 (incarnation): D1 checks under deleting generation G and pauses @@ -504,14 +501,14 @@ func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { t.Fatalf("fork w3: %v", err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete s2 under the incomplete fork: %v; want snapshot_claimed", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapDeleting { + t.Fatalf("delete s2 under the incomplete fork: %q %v; forks do not hold their parent", got, err) } if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { t.Fatalf("delete w3: %+v %v", res, err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { - t.Fatalf("delete s2 after w3 was deleted (its claim is dead): %v", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapAbsent { + t.Fatalf("delete s2 again: %q %v; want absent", got, err) } } 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/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index 9e58424413..6b2ea197c5 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -12,8 +12,12 @@ import ( const precopyQueueBudget = 5 * time.Second +var errPrecopyPaused = fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + type precopyWaiter struct { ready chan struct{} + deadline time.Time + err error signaled bool } type precopyAdmission struct { @@ -48,7 +52,7 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) once.Do(func() { b.mu.Lock() if b.precopy == p { - b.finishPrecopyLocked(b.operational.Load() && !b.closed) + b.finishPrecopyLocked() } b.mu.Unlock() }) @@ -73,30 +77,26 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) } } -func signalPrecopy(w *precopyWaiter) { - if !w.signaled { - close(w.ready) - w.signaled = true - } -} - -// Caller owns mu. Resume admits the old queue serially; a terminal stop wakes -// every command to observe the terminal gate, without issuing storage I/O. -func (b *StorageBackend) finishPrecopyLocked(resume bool) { +// Caller owns mu. INV-CUT-PRECOPY-001: ending the pause releases every +// waiter in FIFO admission order in this one lock hold, then normal gate checks +// and completion run independently. New arrivals cannot join the ended pause. +func (b *StorageBackend) finishPrecopyLocked() { p := b.precopy if p == nil { return } p.active = false - if !resume { - for _, w := range p.waiters { - signalPrecopy(w) + b.precopy = nil + for _, w := range p.waiters { + // INV-CUT-PRECOPY-001: expiry versus grant is decided under mu. + if !time.Now().Before(w.deadline) { + w.err = context.DeadlineExceeded + } + w.signaled = true + close(w.ready) + if hook := b.testPrecopyGranted; hook != nil && w.err == nil { + hook(w) } - b.precopy = nil - } else if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) } } @@ -112,69 +112,67 @@ func (b *StorageBackend) removePrecopyWaiter(p *precopyAdmission, w *precopyWait break } } - if !p.active { - if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) - } - } } // An unqueued caller races the pause only at admit's final registration check. // Waiting callers own no I/O lock and execute no storage/observer operation. func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), error)) (func(), error) { + arrival := time.Now() // INV-CUT-PRECOPY-001: one command-owned wait budget. for { b.mu.Lock() p := b.precopy - if p == nil { - b.mu.Unlock() - release, err := admit() - if err != nil { - b.mu.Lock() - pending := b.precopy != nil - b.mu.Unlock() - if pending { - continue - } + + b.mu.Unlock() + if p != nil { + if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { + return nil, err } - return release, err - } - b.mu.Unlock() - if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { - return nil, err - } - b.mu.Lock() - if b.precopy != p { + b.mu.Lock() + if b.precopy != p { + b.mu.Unlock() + continue + } + deadline := arrival.Add(precopyQueueBudget) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + w := &precopyWaiter{ready: make(chan struct{}), deadline: deadline} + p.waiters = append(p.waiters, w) b.mu.Unlock() - continue - } - w := &precopyWaiter{ready: make(chan struct{})} - p.waiters = append(p.waiters, w) - if !p.active && len(p.waiters) == 1 { - signalPrecopy(w) - } - deadline := p.started.Add(precopyQueueBudget) - b.mu.Unlock() - if hook := b.testPrecopyQueued; hook != nil { - hook() - } - waitCtx, cancel := context.WithDeadline(ctx, deadline) - select { - case <-w.ready: - case <-waitCtx.Done(): - } - cause := waitCtx.Err() - cancel() - if cause != nil { - b.removePrecopyWaiter(p, w) - return nil, b.attachReadyTimeout(cause) + if hook := b.testPrecopyQueued; hook != nil { + hook() + } + waitCtx, cancel := context.WithDeadline(ctx, deadline) + select { + case <-w.ready: + case <-waitCtx.Done(): + } + b.mu.Lock() + cause := waitCtx.Err() + if w.signaled { + cause = w.err + } + b.mu.Unlock() + // A timely queue grant cannot outlive the command's own deadline. + if cause == nil { + cause = ctx.Err() + } + cancel() + if cause != nil { + b.removePrecopyWaiter(p, w) + return nil, b.attachReadyTimeout(cause) + } } release, err := admit() - if err != nil { - b.removePrecopyWaiter(p, w) - return nil, err + // INV-CUT-PRECOPY-001 / INV-FE-LINEAGE-GATE-001: retry only the pause. + if errors.Is(err, errPrecopyPaused) { + b.mu.Lock() + pending := b.precopy != nil + b.mu.Unlock() + if pending { + continue + } } - return func() { release(); b.removePrecopyWaiter(p, w) }, nil + return release, err } } diff --git a/seaweed-block/core/frontend/durable/precopy_arrival_test.go b/seaweed-block/core/frontend/durable/precopy_arrival_test.go new file mode 100644 index 0000000000..c3da43764f --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_arrival_test.go @@ -0,0 +1,314 @@ +package durable + +import ( + "context" + "errors" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// INV-CUT-PRECOPY-001: an active pause may predate this command. Its queue +// allowance is measured once from this command's arrival, capped by its caller. +func TestPrecopyQueueBoundStartsAtCommandArrival(t *testing.T) { + for _, caller := range []time.Duration{2 * time.Second, 10 * time.Second} { + t.Run(caller.String(), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + resume, err := b.BeginPrecopyPause(context.Background()) + if err != nil { + t.Fatal(err) + } + defer resume() + // Let the active pause get older than five seconds before this arrival. + time.Sleep(6 * time.Second) + ctx, cancel := context.WithTimeout(context.Background(), caller) + defer cancel() + queued, done := make(chan struct{}), make(chan error, 1) + b.testPrecopyQueued = func() { close(queued) } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + joined := false + t.Cleanup(func() { + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("arrival-bounded waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + bound := 5 * time.Second + if caller < bound { + bound = caller + } + time.Sleep(bound - time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + t.Fatalf("fresh waiter inherited old pause deadline: %v", err) + default: + } + time.Sleep(time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expiry classification: %v", err) + } + default: + t.Fatal("arrival/caller deadline did not bound the waiter") + } + select { + case <-observed: + t.Fatal("expired paused waiter reached physical Sync") + default: + } + }) + }) + } +} + +// The queue grant and its deadline have one decision boundary even when a +// descheduled waiter cannot run until after its queue timer would have expired. +func TestPrecopyResumeGrantVersusExpiry(t *testing.T) { + for _, outcome := range []string{"grant-before-queue-expiry", "expiry-before-grant", "caller-expiry", "close-after-grant"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + caller := 10 * time.Second + if outcome == "caller-expiry" { + caller = 4 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), caller) + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceed := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(proceed) }) } + b.testPrecopyQueued = func() { close(queued); <-proceed } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + t.Cleanup(func() { + release() + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("boundary waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + if outcome == "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + resume() + if outcome != "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + if outcome == "close-after-grant" { + _ = b.Close() + } + release() + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("grant boundary did not settle") + } + switch outcome { + case "grant-before-queue-expiry": + if result != nil { + t.Fatalf("timely grant lost to later queue expiry: %v", result) + } + case "close-after-grant": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close did not retain terminal precedence: %v", result) + } + default: + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) { + t.Fatalf("expiry not refused as typed busy: %v", result) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused waiter performed Sync") + } + default: + if result == nil { + t.Fatal("successful grant did not perform Sync") + } + } + }) + }) + } +} + +func TestPrecopyGrantedWaiterFollowsReplacementPause(t *testing.T) { + for _, outcome := range []string{"resume", "caller-cancel", "close", "original-deadline"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + resumeA, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceedA := make(chan int, 2), make(chan struct{}) + calls := 0 + var once sync.Once + releaseA := func() { once.Do(func() { close(proceedA) }) } + b.testPrecopyQueued = func() { + calls++ + queued <- calls + if calls == 1 { + <-proceedA + } + } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + resumeB := func() {} + t.Cleanup(func() { + releaseA() + cancel() + resumeA() + resumeB() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("replacement-pause waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case n := <-queued: + if n != 1 { + t.Fatal("first pause registration missing") + } + case err := <-done: + joined = true + t.Fatalf("command ended before first pause registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + time.Sleep(2 * time.Second) + resumeA() + resumeB, err = b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + releaseA() + synctest.Wait() + select { + case n := <-queued: + if n != 2 { + t.Fatalf("requeue=%d", n) + } + case err := <-done: + joined = true + t.Fatalf("granted waiter returned replacement pause Busy instead of requeueing: %v", err) + default: + t.Fatal("waiter did not join replacement pause") + } + select { + case <-observed: + t.Fatal("waiter crossed replacement pause") + default: + } + switch outcome { + case "resume": + resumeB() + case "caller-cancel": + cancel() + case "close": + _ = b.Close() + case "original-deadline": + time.Sleep(3 * time.Second) + } + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("replacement boundary did not settle") + } + switch outcome { + case "resume": + if result != nil { + t.Fatal(result) + } + case "close": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close priority: %v", result) + } + case "caller-cancel": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.Canceled) { + t.Fatalf("caller priority: %v", result) + } + case "original-deadline": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) || ctx.Err() != nil { + t.Fatalf("requeue reset command allowance: %v ctx=%v", result, ctx.Err()) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused replacement waiter performed Sync") + } + default: + if result == nil { + t.Fatal("resumed replacement waiter did not Sync") + } + } + }) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index 7b41c5f2fe..ce8644ad14 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -83,100 +83,6 @@ func TestPrecopyHostDrainDoesNotCompleteHeldGuestIO(t *testing.T) { } } -func TestPrecopyQueueResumesInFIFOOrder(t *testing.T) { - b := precopyMemoryBackend(t) - ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) - queued := make(chan struct{}, 4) - b.testPrecopyQueued = func() { queued <- struct{}{} } - first, release := make(chan struct{}), make(chan struct{}) - var once sync.Once - unpark := func() { once.Do(func() { close(release) }) } - seen := make(chan byte, 4) - if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { - seen <- v - if v == 1 { - close(first) - select { - case <-release: - case <-ctx.Done(): - } - } - }}); err != nil { - t.Fatal(err) - } - resume, err := b.BeginPrecopyPause(ctx) - if err != nil { - t.Fatal(err) - } - var wg sync.WaitGroup - joined := make(chan struct{}) - errs := make(chan error, 4) - t.Cleanup(func() { - cancel() - unpark() - resume() - _ = b.Close() - go func() { wg.Wait(); close(joined) }() - select { - case <-joined: - case <-time.After(3 * time.Second): - t.Error("queue workers did not join") - } - }) - start := func(v byte) { - wg.Add(1) - go func() { defer wg.Done(); _, err := b.Write(ctx, 0, bytes.Repeat([]byte{v}, 4096)); errs <- err }() - select { - case <-queued: - case <-ctx.Done(): - t.Fatal("command was not queued") - } - } - start(1) - start(2) - start(3) - resume() - select { - case <-first: - case <-ctx.Done(): - t.Fatal("first queued write did not enter") - } - start(4) // New arrivals cannot bypass the old queue during an aborted cut. - if v := <-seen; v != 1 { - t.Fatalf("first write=%d", v) - } - select { - case v := <-seen: - t.Fatalf("write %d bypassed held FIFO head", v) - case <-time.After(30 * time.Millisecond): - } - unpark() - for _, want := range []byte{2, 3, 4} { - select { - case got := <-seen: - if got != want { - t.Fatalf("write=%d want%d", got, want) - } - case <-ctx.Done(): - t.Fatal("FIFO queue did not drain") - } - } - for i := 0; i < 4; i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-ctx.Done(): - t.Fatal("queued write did not finish") - } - } - data := make([]byte, 4096) - if _, err := b.Read(ctx, 0, data); err != nil || data[0] != 4 { - t.Fatalf("ordered final bytes=%d err=%v", data[0], err) - } -} - func TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture(t *testing.T) { b := precopyMemoryBackend(t) entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) @@ -258,7 +164,7 @@ func TestPrecopyQueueUsesFiveSecondCutoverBudget(t *testing.T) { // Releasing that lock before the fallback must not replace the pause identity. func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { for _, terminal := range []bool{false, true} { - name := "resume_fifo" + name := "resume_all" if terminal { name = "close" } @@ -365,12 +271,14 @@ func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { default: } } else { - for _, want := range []byte{1, 2} { + seenWrites := map[byte]bool{} + for i := 0; i < 2; i++ { select { case got := <-seen: - if got != want { - t.Fatalf("FIFO got %d want %d", got, want) + if got < 1 || got > 2 || seenWrites[got] { + t.Fatalf("unexpected resumed write %d", got) } + seenWrites[got] = true case <-ctx.Done(): t.Fatal("missing write") } diff --git a/seaweed-block/core/frontend/durable/precopy_resume_test.go b/seaweed-block/core/frontend/durable/precopy_resume_test.go new file mode 100644 index 0000000000..1f4c528663 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_resume_test.go @@ -0,0 +1,192 @@ +package durable + +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +// INV-CUT-PRECOPY-001: a completed pause releases admission, not one +// whole storage operation at a time. Independent LBAs must run concurrently. +func TestPrecopyResumeReleasesAllWaiters(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + queued := make(chan struct{}, 3) + var want, granted []*precopyWaiter + grantUnlocked := false + b.testPrecopyGranted = func(w *precopyWaiter) { + granted = append(granted, w) + if b.mu.TryLock() { + b.mu.Unlock() + grantUnlocked = true + } + } + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered := make(chan byte, 3) + release := make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { + entered <- v + select { + case <-release: + case <-ctx.Done(): + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + results := make(chan error, 3) + t.Cleanup(func() { + unpark() + cancel() + resume() + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("resumed writers did not join") + } + }) + for v := byte(1); v <= 3; v++ { + wg.Add(1) + go func(v byte) { + defer wg.Done() + _, err := b.Write(ctx, int64(v-1)*4096, bytes.Repeat([]byte{v}, 4096)) + results <- err + }(v) + select { + case <-queued: + b.mu.Lock() + want = append(want, b.precopy.waiters[len(b.precopy.waiters)-1]) + b.mu.Unlock() + case <-ctx.Done(): + t.Fatal("write did not queue") + } + } + select { + case v := <-entered: + t.Fatalf("paused write %d reached observer", v) + default: + } + resume() + if grantUnlocked || len(granted) != 3 { + t.Fatalf("FIFO grants not made together under mu: count=%d unlocked=%v", len(granted), grantUnlocked) + } + for i, w := range want { + if granted[i] != w { + t.Fatalf("grant %d bypassed arrival order", i) + } + } + seen := map[byte]bool{} + for i := 0; i < 3; i++ { + select { + case v := <-entered: + seen[v] = true + case <-ctx.Done(): + t.Fatalf("resume serialized independent I/O: %d/3 entered before any completion", len(seen)) + } + } + unpark() + for i := 0; i < 3; i++ { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("resumed write did not finish") + } + } + for v := byte(1); v <= 3; v++ { + got := make([]byte, 4096) + if _, err := b.Read(ctx, int64(v-1)*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{v}, 4096)) { + t.Fatalf("resumed LBA %d bytes incorrect: %v", v-1, err) + } + } +} + +// Real elapsed time, not a changed production budget: an admitted Sync remains +// held past the old pause's five-second clock while a fresh write must succeed. +func TestPrecopyResumedArrivalDoesNotInheritExpiredPause(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 9*time.Second) + queued := make(chan struct{}, 2) + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(ctx context.Context) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + // Capture the existing pause's origin only to wait beyond its public bound. + b.mu.Lock() + started := b.precopy.started + b.mu.Unlock() + var syncErr error + t.Cleanup(func() { + unpark() + cancel() + resume() + select { + case <-done: + case <-time.After(time.Second): + t.Error("held Sync did not join") + } + }) + go func() { defer close(done); syncErr = b.Sync(ctx) }() + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("Sync did not queue") + } + resume() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("Sync did not resume") + } + timer := time.NewTimer(time.Until(started.Add(5*time.Second + 50*time.Millisecond))) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + t.Fatal("caller expired before pause-age witness") + } + want := bytes.Repeat([]byte{7}, 4096) + if n, err := b.Write(ctx, 4096, want); err != nil || n != len(want) { + t.Fatalf("serving volume rejected a fresh arrival after ended pause aged past five seconds: n=%d err=%v", n, err) + } + got := make([]byte, 4096) + if _, err := b.Read(ctx, 4096, got); err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh write bytes: %v", err) + } + unpark() + select { + case <-done: + if syncErr != nil { + t.Fatal(syncErr) + } + case <-ctx.Done(): + t.Fatal("Sync did not finish") + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go new file mode 100644 index 0000000000..279f50d7a8 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go @@ -0,0 +1,52 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "testing" + "time" +) + +type precopyProjectionFunc func() frontend.Projection + +func (f precopyProjectionFunc) Projection() frontend.Projection { return f() } + +// Projection is the real gate seam: pause B begins before admittedIO increments, +// and that same observation returns stale ownership. B cannot erase this error. +func TestPrecopyNewPauseCannotEraseObservedStalePrimary(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + resumeB := func() {} + defer func() { resumeB() }() + calls := 0 + var startErr error + b.view = precopyProjectionFunc(func() frontend.Projection { + calls++ + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + startErr = err + return frontend.Projection{} + } + resumeB = resume + return frontend.Projection{VolumeID: b.id.VolumeID, ReplicaID: b.id.ReplicaID, Epoch: b.id.Epoch + 1, EndpointVersion: b.id.EndpointVersion, Healthy: true} + }) + observed := false + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed = true; return nil }}); err != nil { + t.Fatal(err) + } + err := b.Sync(ctx) + if startErr != nil { + t.Fatal("start B from projection:", startErr) + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("observed stale ownership replaced by pause retry: %v", err) + } + b.mu.Lock() + admitted := b.admittedIO + b.mu.Unlock() + if calls != 1 || observed || admitted != 0 { + t.Fatalf("stale observation retried or admitted I/O: calls=%d observed=%v admitted=%d", calls, observed, admitted) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 6d6e5c0b70..39f54d80c2 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 @@ -202,13 +209,6 @@ type ProviderConfig struct { // be delivered. It must return without blocking and without remote calls: // enqueue work to your own worker (it is a guest-visible wait on detach). ChunkOnPublishSettled func(ctx context.Context, volumeID string, prev, next storage.ChunkHead) - // ChunkDirtyThreshold is the number of candidate chunks above which - // a cut pre-copies (stages) chunks before its barrier, in rounds of - // this size; copy-before-write copies the rest outside the barrier. - // It never triggers a cut: the remote holds snapshots, and cuts are - // published only by CaptureVolume, MakeVolumeRemoteDurable - // (snapshot, detach) and the timer. Zero: no pre-copy. - ChunkDirtyThreshold int // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. @@ -276,9 +276,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 @@ -293,23 +294,23 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus - DataSync *storage.DataSyncStatus `json:",omitempty"` - CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` + VolumeID string // the volume + Path string // its store path under --durable-root + Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...) + ReplicaID string // the replica this store holds + Epoch uint64 // the epoch the store is latched to; 0 before an assignment + EndpointVersion uint64 // the endpoint version it is latched to + Latched bool // an assignment latched the store (epoch and endpoint version set) + Operational bool // the backend admits I/O now + FrontierKnown bool // DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries + DurableLSN uint64 // R: the newest LSN made durable + RetainedLSN uint64 // S: the oldest LSN the WAL still retains + HeadLSN uint64 // H: the newest LSN written + Evidence string // why the backend is or is not operational + Closed bool // the backend was closed + WriteProfile WriteProfileStatus // write-path counters since start + DataSync *storage.DataSyncStatus `json:",omitempty"` // data-file sync state, where the store has one + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // checkpoint persistence state, where the store has one // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus @@ -324,12 +325,12 @@ type VolumeStatus struct { // AwaitingAuthority: recovered, the layer waits for master authority to // attach. Stats is zero until the layer is attached. type ChunkStatus struct { - Attached bool - AwaitingAuthority bool - Fenced bool - RemoteLSN uint64 - Stats storage.ChunkLayerStats - HostBudget any `json:",omitempty"` + Attached bool // the chunk layer is attached to the remote + AwaitingAuthority bool // recovered; the layer waits for master authority to attach + Fenced bool // a newer holder fenced this layer: it publishes nothing + RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) + Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached + HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir } // NewDurableProvider constructs a provider. view is the ONLY @@ -346,6 +347,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 de343127d1..8fe788e8e1 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) { @@ -384,7 +386,6 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, - BarrierBound: p.cfg.ChunkDirtyThreshold, UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, @@ -467,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 @@ -636,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; @@ -761,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) @@ -770,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) @@ -790,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) { @@ -832,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 @@ -842,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 @@ -864,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_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 15a736988e..74526bc5b6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -15,13 +15,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration, threshold int) *durable.DurableProvider { +func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration) *durable.DurableProvider { t.Helper() p, err := durable.NewDurableProvider(durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval, - ChunkDirtyThreshold: threshold, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, }, v1View()) if err != nil { @@ -41,12 +40,12 @@ func headGen(t *testing.T, remote storage.ChunkRemote) storage.ChunkHead { } // The remote holds snapshots: with the timer off, no number of dirty -// chunks publishes a cut on its own (the threshold only bounds a cut). -func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { +// chunks publishes a cut on its own. +func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, 0, 2) + p := schedProvider(t, remote, 0) s := openRecovered(t, p) - for c := uint32(0); c < 4; c++ { // four dirty chunks, twice the threshold + for c := uint32(0); c < 4; c++ { // four dirty chunks if _, err := s.Write(c*pcChunkBlocks+1, block(byte(c+1))); err != nil { t.Fatal(err) } @@ -72,7 +71,7 @@ func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { const interval = 3 * time.Second remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) s := openRecovered(t, p) begin := time.Now() @@ -243,7 +242,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { var releaseOnce sync.Once release := func() { releaseOnce.Do(func() { close(remote.release) }) } t.Cleanup(release) - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) events := make(chan loopEvent, 64) durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) { select { diff --git a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go index a4c3945460..5fd481e6d3 100644 --- a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go @@ -47,9 +47,6 @@ func TestWALStoreChunk_LedgerWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) @@ -243,9 +240,6 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } if raw := os.Getenv("SWBLOCK_MEMORY_CHUNKS"); raw != "" { chunks, e := strconv.Atoi(raw) if e != nil || chunks <= 0 { 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..1f38b998b2 --- /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) + 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/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index f1c9e3779c..9ac6db58e4 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,8 +149,9 @@ type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). testBeforeIOLock func() - testPrecopyQueued func() // after FIFO registration, outside mu - testPrecopyStopFallback func() // before fallback lock attempts, outside mu + testPrecopyQueued func() // after FIFO registration, outside mu + testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook + testPrecopyStopFallback func() // before fallback lock attempts, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -368,7 +369,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true - b.finishPrecopyLocked(false) + b.finishPrecopyLocked() b.notifyReadReadyLocked() return nil } @@ -488,7 +489,7 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { // teardown. Keep a final pre-copy queue parked until Close or its budget; // publishing readiness loss must not complete commands on that path. if ok || b.precopy == nil || !b.precopy.active { - b.finishPrecopyLocked(ok) + b.finishPrecopyLocked() } b.notifyReadReadyLocked() } @@ -829,7 +830,7 @@ func (b *StorageBackend) admit() (func(), error) { if b.precopy != nil && b.precopy.active { b.mu.Unlock() b.ioMu.RUnlock() - return nil, fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return nil, errPrecopyPaused } b.admittedIO++ b.mu.Unlock() @@ -879,7 +880,7 @@ func (b *StorageBackend) readyCheck() error { return frontend.ErrStalePrimary } if precopyPending { - return fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return errPrecopyPaused } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) diff --git a/seaweed-block/core/frontend/durable/write_profile.go b/seaweed-block/core/frontend/durable/write_profile.go index 6a2906f655..9192555c67 100644 --- a/seaweed-block/core/frontend/durable/write_profile.go +++ b/seaweed-block/core/frontend/durable/write_profile.go @@ -12,55 +12,55 @@ import ( // It is not a performance API; callers use it to prove which product-owned // path observed the write and roughly where time accumulated. type WriteProfileStatus struct { - DurabilityLatency DurabilityLatencyStatus - TargetWriteOps uint64 - TargetWriteBytes uint64 - TargetWriteRequestMaxBytes uint64 - TargetWriteDurationNanos uint64 - BackendWriteRequestOps uint64 - BackendWriteRequestBytes uint64 - BackendWriteRequestMaxBytes uint64 - BackendWriteOps uint64 - BackendWriteBytes uint64 - BackendWriteDurationNanos uint64 - BackendStorageWriteCalls uint64 - BackendStorageWriteBlocks uint64 - BackendStorageBatchCalls uint64 - BackendStorageBatchBlocks uint64 - BackendFullBlockBatchCalls uint64 - BackendFullBlockBatchBlocks uint64 - BackendFullBlockBatchMax uint64 - WALCopyOps uint64 - WALCopyBytes uint64 - WALCopyDurationNanos uint64 - WALEncodeOps uint64 - WALEncodeBytes uint64 - WALEncodeDurationNanos uint64 - WALChecksumOps uint64 - WALChecksumBytes uint64 - WALChecksumDurationNanos uint64 - WALAppendOps uint64 - WALAppendBytes uint64 - WALAppendDurationNanos uint64 - WALAppendLockWaitOps uint64 - WALAppendLockWaitNanos uint64 - WriteCommitLockWaitOps uint64 - WriteCommitLockWaitNanos uint64 - WALAppendWriteAtCalls uint64 - WALAppendWriteAtBytes uint64 - WALAppendWriteAtMaxBytes uint64 - WALAppendWrapCount uint64 - WALAppendPaddingBytes uint64 - DirtyMapUpdateOps uint64 - DirtyMapUpdateDurationNanos uint64 - BackendSyncOps uint64 - BackendSyncDurationNanos uint64 + DurabilityLatency DurabilityLatencyStatus // latency distributions of writes, flushes and syncs + TargetWriteOps uint64 // writes the protocol target handed to the volume + TargetWriteBytes uint64 // their bytes + TargetWriteRequestMaxBytes uint64 // the largest of them + TargetWriteDurationNanos uint64 // their total time at the target + BackendWriteRequestOps uint64 // write requests that entered the durable backend + BackendWriteRequestBytes uint64 // their bytes + BackendWriteRequestMaxBytes uint64 // the largest of them + BackendWriteOps uint64 // backend writes completed + BackendWriteBytes uint64 // their bytes + BackendWriteDurationNanos uint64 // their total time + BackendStorageWriteCalls uint64 // single-write calls into the store + BackendStorageWriteBlocks uint64 // blocks they wrote + BackendStorageBatchCalls uint64 // batch-write calls into the store + BackendStorageBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchCalls uint64 // batch calls made only of whole blocks + BackendFullBlockBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchMax uint64 // the largest such batch, in blocks + WALCopyOps uint64 // WAL record payload copies + WALCopyBytes uint64 // their bytes + WALCopyDurationNanos uint64 // their total time + WALEncodeOps uint64 // WAL record encodes + WALEncodeBytes uint64 // their bytes + WALEncodeDurationNanos uint64 // their total time + WALChecksumOps uint64 // WAL record checksums + WALChecksumBytes uint64 // their bytes + WALChecksumDurationNanos uint64 // their total time + WALAppendOps uint64 // WAL appends + WALAppendBytes uint64 // their bytes + WALAppendDurationNanos uint64 // their total time + WALAppendLockWaitOps uint64 // appends that waited for the WAL append lock + WALAppendLockWaitNanos uint64 // their total wait + WriteCommitLockWaitOps uint64 // writes that waited for the commit lock + WriteCommitLockWaitNanos uint64 // their total wait + WALAppendWriteAtCalls uint64 // file WriteAt calls made by WAL appends + WALAppendWriteAtBytes uint64 // their bytes + WALAppendWriteAtMaxBytes uint64 // the largest of them + WALAppendWrapCount uint64 // times the WAL append wrapped to the start of the log + WALAppendPaddingBytes uint64 // padding bytes written at those wraps + DirtyMapUpdateOps uint64 // dirty-map updates after writes + DirtyMapUpdateDurationNanos uint64 // their total time + BackendSyncOps uint64 // backend syncs (flush, FUA, explicit sync) + BackendSyncDurationNanos uint64 // their total time } type DurabilityLatencyStatus struct { - Frontend iolatency.RequestStatus - BackendSync iolatency.Distribution - WAL *storage.DurabilityLatencyStatus `json:",omitempty"` + Frontend iolatency.RequestStatus // per-request latency at the frontend, by stage + BackendSync iolatency.Distribution // latency of backend syncs + WAL *storage.DurabilityLatencyStatus `json:",omitempty"` // the WAL's own sync latency, where the store reports it } type writeProfile struct { diff --git a/seaweed-block/core/frontend/nvme/stats.go b/seaweed-block/core/frontend/nvme/stats.go index e167cccb4c..055c45278b 100644 --- a/seaweed-block/core/frontend/nvme/stats.go +++ b/seaweed-block/core/frontend/nvme/stats.go @@ -15,36 +15,38 @@ import ( // includes socket wait and decode. R2T collection includes target send, // initiator response, and H2CData receive. type Stats struct { - SessionsAccepted uint64 `json:"sessions_accepted"` - AdminConnects uint64 `json:"admin_connects"` - IOConnects uint64 `json:"io_connects"` + SessionsAccepted uint64 `json:"sessions_accepted"` // TCP sessions accepted + AdminConnects uint64 `json:"admin_connects"` // admin-queue Connect commands + IOConnects uint64 `json:"io_connects"` // I/O-queue Connect commands - ReadCommands uint64 `json:"read_commands"` - WriteCommands uint64 `json:"write_commands"` - FlushCommands uint64 `json:"flush_commands"` + ReadCommands uint64 `json:"read_commands"` // Read commands received + WriteCommands uint64 `json:"write_commands"` // Write commands received + FlushCommands uint64 `json:"flush_commands"` // Flush commands received - InlineWriteCommands uint64 `json:"inline_write_commands"` - InlineWriteBytes uint64 `json:"inline_write_bytes"` - R2TWriteCommands uint64 `json:"r2t_write_commands"` - R2TWriteBytes uint64 `json:"r2t_write_bytes"` + InlineWriteCommands uint64 `json:"inline_write_commands"` // writes whose data came inline in the command capsule + InlineWriteBytes uint64 `json:"inline_write_bytes"` // their data bytes + R2TWriteCommands uint64 `json:"r2t_write_commands"` // writes whose data the target requested with R2T + R2TWriteBytes uint64 `json:"r2t_write_bytes"` // their data bytes - H2CDataPDUs uint64 `json:"h2c_data_pdus"` - H2CDataBytes uint64 `json:"h2c_data_bytes"` - C2HDataPDUs uint64 `json:"c2h_data_pdus"` - C2HDataBytes uint64 `json:"c2h_data_bytes"` + H2CDataPDUs uint64 `json:"h2c_data_pdus"` // host-to-controller data PDUs received + H2CDataBytes uint64 `json:"h2c_data_bytes"` // their bytes + C2HDataPDUs uint64 `json:"c2h_data_pdus"` // controller-to-host data PDUs sent (read data) + C2HDataBytes uint64 `json:"c2h_data_bytes"` // their bytes - WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` - WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` - R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` - R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` - WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` - WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` - WriteHandlerOps uint64 `json:"write_handler_ops"` - WriteHandlerNanos uint64 `json:"write_handler_ns"` - WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` - WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` - WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` - WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` + // Write phase attribution: for each phase, the operations timed and + // their total nanoseconds (overlapping phases can overlap in time). + WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` // write capsules received and decoded (includes socket wait) + WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` // total nanoseconds of those operations + R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` // R2T data collections (R2T send to the last H2CData) + R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` // total nanoseconds of those operations + WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` // waits for a write handler to take the command + WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` // total nanoseconds of those operations + WriteHandlerOps uint64 `json:"write_handler_ops"` // write handler runs (the backend write) + WriteHandlerNanos uint64 `json:"write_handler_ns"` // total nanoseconds of those operations + WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` // waits of a completion for the send queue + WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` // total nanoseconds of those operations + WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` // completion sends to the host + WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` // total nanoseconds of those operations } type targetStats struct { diff --git a/seaweed-block/core/frontend/types.go b/seaweed-block/core/frontend/types.go index b61c2b42a1..920666050a 100644 --- a/seaweed-block/core/frontend/types.go +++ b/seaweed-block/core/frontend/types.go @@ -31,11 +31,11 @@ type Identity struct { // Mode into a single value that ProjectionView.Projection() // returns. type Projection struct { - VolumeID string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Healthy bool + VolumeID string // the volume this host serves + ReplicaID string // this host's replica of it + Epoch uint64 // the authority epoch of the current assignment + EndpointVersion uint64 // the assignment's endpoint version within the epoch + Healthy bool // the replica may serve I/O at this epoch } // ProjectionView is the read-only seam between adapter/engine @@ -50,15 +50,16 @@ type ProjectionView interface { // Backend is a per-lineage handle for one open frontend session. // // Lifecycle ownership (BUG-005 2026-04-22): -// Backend.Close() is OWNED BY THE PROVIDER. Session-layer -// consumers (iSCSI session, NVMe controller, etc.) MUST NOT -// call Close on a Backend obtained from Provider.Open — -// treat the returned Backend as a BORROWED reference for the -// duration of the session. DurableProvider caches one Backend -// per volumeID; a session-level Close would mark the cached -// Backend closed and break every subsequent session. Session -// teardown should release conn + session-local state only. -// Provider.Close tears down all Backends in correct order. +// +// Backend.Close() is OWNED BY THE PROVIDER. Session-layer +// consumers (iSCSI session, NVMe controller, etc.) MUST NOT +// call Close on a Backend obtained from Provider.Open — +// treat the returned Backend as a BORROWED reference for the +// duration of the session. DurableProvider caches one Backend +// per volumeID; a session-level Close would mark the cached +// Backend closed and break every subsequent session. Session +// teardown should release conn + session-local state only. +// Provider.Close tears down all Backends in correct order. // // T3a extends the interface with two methods (all existing // implementations gain trivial impls in the same commit): diff --git a/seaweed-block/core/frontend/ublk/dispatch.go b/seaweed-block/core/frontend/ublk/dispatch.go index e2c9c7a8ed..429127b5bb 100644 --- a/seaweed-block/core/frontend/ublk/dispatch.go +++ b/seaweed-block/core/frontend/ublk/dispatch.go @@ -50,12 +50,12 @@ type handler struct { // counted when it is received, before the backend call; Errors counts the // requests that completed with a negative result. type Stats struct { - ReadRequests uint64 `json:"read_requests"` - WriteRequests uint64 `json:"write_requests"` - FlushRequests uint64 `json:"flush_requests"` - FUAWrites uint64 `json:"fua_writes"` - OtherRequests uint64 `json:"other_requests"` - Errors uint64 `json:"errors"` + ReadRequests uint64 `json:"read_requests"` // read requests received + WriteRequests uint64 `json:"write_requests"` // write requests received + FlushRequests uint64 `json:"flush_requests"` // flush requests received + FUAWrites uint64 `json:"fua_writes"` // writes with forced unit access + OtherRequests uint64 `json:"other_requests"` // requests of any other operation + Errors uint64 `json:"errors"` // requests completed with a negative result } type counters struct { 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 c51ccbd292..e446a72514 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -93,7 +93,7 @@ type ChunkCutStatsBody struct { StagedChunks int `json:"stagedChunks"` StagedChunksUsed int `json:"stagedChunksUsed"` BarrierCopyChunks int `json:"barrierCopyChunks"` - BarrierOverBound bool `json:"barrierOverBound"` + BarrierOverBound bool `json:"barrierOverBound"` // always false in production: its bound is set only by legacy test fixtures } func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { @@ -174,7 +174,14 @@ type snapshotBody struct { Replayed bool `json:"replayed"` } +type chunkFrozenRefusalBody struct { + storage.FrozenBudget + RemainingFreeze time.Duration `json:"remainingFreezeNs"` + GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs"` +} + type chunkErrorBody struct { + *chunkFrozenRefusalBody Code string `json:"code"` Message string `json:"message"` Retryable bool `json:"retryable"` @@ -198,9 +205,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 @@ -255,7 +264,14 @@ func writeChunkFailure(w http.ResponseWriter, err error) { if errors.As(err, &ce) { msg = ce.Detail() // the code is in its own field } - writeChunkJSON(w, status, chunkErrorBody{Code: code, Message: msg, Retryable: retryable}) + body := chunkErrorBody{Code: code, Message: msg, Retryable: retryable} + var refusal *storage.FrozenRefusal + // INV-WS-FREEZE-ACCOUNTING-001: transport observation, never a second forecast. + if code == "frozen_tail_too_large" && errors.As(err, &refusal) { + r := refusal.Report + body.chunkFrozenRefusalBody = &chunkFrozenRefusalBody{FrozenBudget: r.FrozenBudget, RemainingFreeze: r.RemainingFreeze, GuestFreezeElapsed: r.GuestFreezeElapsed} + } + writeChunkJSON(w, status, body) } // chunkErrorCode maps an operation's error to (HTTP status, code, @@ -308,7 +324,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 +548,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_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go index 918ead3a02..89d333a9bc 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -29,9 +29,6 @@ func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { t.Fatalf("%s maps to %d, want 400", code, s) } } - if s := catalogStatus(chunkstore.CodeSnapshotClaimed); s != http.StatusConflict { - t.Fatalf("snapshot_claimed maps to %d, want 409", s) - } info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { 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..f905b2fe6f 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -5,8 +5,10 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" "net/http" + "sync" "testing" "time" ) @@ -64,3 +66,173 @@ 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) + } + } +} + +func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) { + report := storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 5570 * time.Millisecond, FrozenEstimateKnown: true, FreezeLimit: 5 * time.Second}, Estimate: 5570 * time.Millisecond, RemainingFreeze: 4 * time.Second, GuestFreezeElapsed: time.Second, Reason: "frozen_tail_too_large"} + refusal := &storage.FrozenRefusal{Report: report} + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}, err: refusal} + srv := chunkServer(t, NewChunkControl(p, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(-time.Second).UnixNano()) + w := serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + var got map[string]json.RawMessage + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 409 { + t.Fatalf("refusal %d %s", w.Code, w.Body) + } + for key, want := range map[string]int64{"frozenEstimateNs": 5570000000, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": 0, "remainingFreezeNs": 4000000000, "guestFreezeElapsedNs": 1000000000} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, w.Body) + } else if err := json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want%d", key, raw, want) + } + } + var known bool + if err := json.Unmarshal(got["frozenEstimateKnown"], &known); err != nil || !known { + t.Errorf("known lost: %s", w.Body) + } + p.err = &storage.FrozenRefusal{Report: storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 300 * time.Millisecond, FreezeLimit: 5 * time.Second}, Estimate: 300 * time.Millisecond, Reason: "frozen_tail_too_large", RemainingFreeze: 5 * time.Second}} + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + _ = json.Unmarshal(w.Body.Bytes(), &got) + if string(got["frozenEstimateKnown"]) != "false" || string(got["maxRefreezeQuiesceNs"]) != "0" || string(got["frozenEstimateNs"]) != "300000000" { + t.Fatalf("unknown refusal became an actionable estimate: %s", w.Body) + } + p.err = errors.Join(storage.ErrChunkLayerClosed, refusal) + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + if json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatal(w.Body) + } + status, code, _ := chunkErrorCode(storage.ErrChunkLayerClosed) + var gotCode string + _ = json.Unmarshal(got["code"], &gotCode) + if w.Code != status || gotCode != code { + t.Fatalf("terminal precedence lost: %d %s", w.Code, w.Body) + } + if _, ok := got["frozenEstimateNs"]; ok { + t.Fatalf("terminal response offered retry budget: %s", w.Body) + } +} + +// Hold a real admitted Sync through the replication observer, so the actual +// frontend drain expires before storage frozen admission. No report is injected. +type frozenDrainObserver struct{ entered, release chan struct{} } + +func (*frozenDrainObserver) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (o *frozenDrainObserver) Sync(ctx context.Context, _ uint64) error { + close(o.entered) + select { + case <-o.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} +func TestChunkFrozenDrainRefusalCarriesObservedBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + dp, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, + ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + if _, err = dp.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + backend, err := dp.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = backend.Write(ctx, 4096, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + observer := &frozenDrainObserver{make(chan struct{}), make(chan struct{})} + if err = backend.(*durable.StorageBackend).SetWriteObserver(observer); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + var once sync.Once + t.Cleanup(func() { + once.Do(func() { close(observer.release) }) + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("Sync did not join") + } + }) + go func() { done <- backend.Sync(ctx) }() + select { + case <-observer.entered: + case <-ctx.Done(): + t.Fatal("Sync never admitted") + } + before, _ := remote.GetHead(ctx) + puts := remote.Puts() + server := chunkServer(t, NewChunkControl(dp, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, time.Now().Add(-time.Second).UnixNano()) + response := serve(t, server, http.MethodPost, "/chunk/detach", body, "") + var got struct { + Code string `json:"code"` + storage.FrozenBudget + Remaining time.Duration `json:"remainingFreezeNs"` + Elapsed time.Duration `json:"guestFreezeElapsedNs"` + } + if err = json.Unmarshal(response.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if response.Code != 409 || got.Code != "frozen_tail_too_large" || got.FreezeLimit != 5*time.Second || got.Elapsed < time.Second || got.Remaining <= 0 || got.Elapsed+got.Remaining != got.FreezeLimit || got.FrozenEstimateKnown || got.MaxRefreezeQuiesce != 0 { + t.Fatalf("real drain refusal lost observation: %d %s", response.Code, response.Body) + } + after, _ := remote.GetHead(ctx) + if after.Gen != before.Gen || remote.Puts() != puts { + t.Fatal("failed drain uploaded or published") + } +} diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 3a15daa127..b1ee1950bc 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -11,13 +11,13 @@ import ( // ProcessMemoryStatus separates live heap from resident pages awaiting return // to the OS. RSS fields are zero on systems without /proc/self/status. type ProcessMemoryStatus struct { - HeapAllocBytes uint64 - HeapInuseBytes uint64 - HeapSysBytes uint64 - HeapReleasedBytes uint64 - SoftLimitBytes int64 - RSSBytes uint64 - AnonymousRSSBytes uint64 + HeapAllocBytes uint64 // Go heap bytes in live objects (runtime.MemStats.HeapAlloc) + HeapInuseBytes uint64 // Go heap bytes in in-use spans (HeapInuse) + HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) + HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) + SoftLimitBytes int64 // the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) + RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux + AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } func processMemoryStatus() ProcessMemoryStatus { diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go new file mode 100644 index 0000000000..348909f843 --- /dev/null +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -0,0 +1,308 @@ +package volume + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" +) + +// statusRoutes are the status routes and the type each one encodes. The +// anonymous bodies of /status/peers and /status/durable are restated here +// field for field; TestStatusBodiesMatchTheRoutes checks they still match. +var statusRoutes = []struct { + route, note string + typ reflect.Type +}{ + {"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})}, + {"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})}, + {"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})}, + {"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})}, + {"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.VolumeUsage{})}, + {"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})}, + {"/status/ublk", "ublk frontend counters", reflect.TypeOf(UblkStatus{})}, + {"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})}, +} + +type peersStatusBody struct { + VolumeID string // the served volume + ReplicaID string // this host's replica + PeerCount int // number of entries in Peers + Peers []replication.ReplicaPeerStatus // this primary's replication peers +} + +type durableStatusBody struct { + VolumeID string // the served volume + ReplicaID string // this host's replica + VolumeCount int // number of entries in Volumes + Volumes []durable.VolumeStatus // the durable store state of the served volume +} + +const ( + statusSchemaDoc = "../../../docs/status-schema.md" + statusSchemaBegin = "" + statusSchemaEnd = "" + modulePath = "github.com/seaweedfs/seaweed-block/" +) + +// fieldDocs maps "pkgpath.Type.Field" to the field's doc or line comment. +type fieldDocs map[string]string + +func (d fieldDocs) load(t *testing.T, pkgPath string) { + t.Helper() + if !strings.HasPrefix(pkgPath, modulePath) { + return + } + if _, done := d["pkg:"+pkgPath]; done { + return + } + d["pkg:"+pkgPath] = "" + dir := filepath.Join("..", "..", "..", strings.TrimPrefix(pkgPath, modulePath)) + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { + return !strings.HasSuffix(fi.Name(), "_test.go") || fi.Name() == "status_schema_test.go" // the restated bodies + }, parser.ParseComments) + if err != nil { + t.Fatalf("parse %s: %v", dir, err) + } + for _, p := range pkgs { + for _, f := range p.Files { + ast.Inspect(f, func(n ast.Node) bool { + ts, ok := n.(*ast.TypeSpec) + if !ok { + return true + } + st, ok := ts.Type.(*ast.StructType) + if !ok { + return true + } + // A doc comment above a run of fields with no blank line + // between them describes the whole run (a group comment). + group, groupFirst, prevEnd := "", "", -1 + for _, fl := range st.Fields.List { + text := "" + line := fset.Position(fl.Pos()).Line + switch { + case fl.Doc != nil: + text = fl.Doc.Text() + group, groupFirst = strings.Join(strings.Fields(text), " "), "" + if len(fl.Names) > 0 { + groupFirst = fl.Names[0].Name + } + case fl.Comment != nil: + text = fl.Comment.Text() + case group != "" && line == prevEnd+1: + text = "(group of `" + groupFirst + "`) " + group + default: + group = "" + } + prevEnd = fset.Position(fl.End()).Line + text = strings.Join(strings.Fields(text), " ") + for _, name := range fl.Names { + d[pkgPath+"."+ts.Name.Name+"."+name.Name] = text + } + } + return true + }) + } + } +} + +// schemaRows walks t's JSON fields; prefix is the dotted JSON path so far. +func schemaRows(t *testing.T, docs fieldDocs, typ reflect.Type, prefix string, seen map[reflect.Type]bool, rows *[]string) { + for typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + if typ.Kind() != reflect.Struct || seen[typ] { + return + } + seen[typ] = true + defer delete(seen, typ) + docs.load(t, typ.PkgPath()) + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() { + continue + } + tag := f.Tag.Get("json") + if tag == "-" { + continue + } + name, opts, _ := strings.Cut(tag, ",") + if f.Anonymous && name == "" { + schemaRows(t, docs, f.Type, prefix, seen, rows) + continue + } + if name == "" { + name = f.Name + } + path := name + if prefix != "" { + path = prefix + "." + name + } + ft, suffix := f.Type, "" + for { + switch ft.Kind() { + case reflect.Pointer: + ft = ft.Elem() + continue + case reflect.Slice, reflect.Array: + if ft.Elem().Kind() != reflect.Uint8 { + ft, suffix = ft.Elem(), suffix+"[]" + continue + } + case reflect.Map: + ft, suffix = ft.Elem(), suffix+"{}" + continue + } + break + } + typeName := ft.Kind().String() + if ft.Kind() == reflect.Struct { + typeName = "object" + if ft.PkgPath() == "time" && ft.Name() == "Time" { + typeName = "time (RFC 3339)" + } + } else if ft.Name() != "" && ft.PkgPath() != "" { + typeName = ft.Name() + " (" + ft.Kind().String() + ")" + } + if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.Uint8 { + typeName = "bytes (base64)" + } + desc := docs[typ.PkgPath()+"."+typ.Name()+"."+f.Name] + if desc == "" { + desc = "—" + } + if strings.Contains(opts, "omitempty") { + desc += " (omitted when empty)" + } + desc = strings.ReplaceAll(desc, "|", "\\|") + *rows = append(*rows, fmt.Sprintf("| `%s%s` | %s | %s |", path, suffix, typeName, desc)) + if ft.Kind() == reflect.Struct && !(ft.PkgPath() == "time" && ft.Name() == "Time") { + schemaRows(t, docs, ft, path+suffix, seen, rows) + } + } +} + +func generateStatusSchema(t *testing.T) string { + t.Helper() + docs := fieldDocs{} + var b strings.Builder + b.WriteString(statusSchemaBegin + "\n") + for _, r := range statusRoutes { + var rows []string + schemaRows(t, docs, r.typ, "", map[reflect.Type]bool{}, &rows) + fmt.Fprintf(&b, "\n### `GET %s`\n\n%s. Go type `%s`.\n\n| Field | Type | Meaning |\n|---|---|---|\n", r.route, upperFirst(r.note), r.typ.String()) + b.WriteString(strings.Join(rows, "\n") + "\n") + } + b.WriteString("\n" + statusSchemaEnd) + return b.String() +} + +func upperFirst(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// The status schema document lists every field the status routes return, +// generated from the Go types and their field comments. A field added, +// removed or renamed without regenerating the document fails here. +func TestStatusSchemaDoc(t *testing.T) { + want := generateStatusSchema(t) + raw, err := os.ReadFile(statusSchemaDoc) + if err != nil { + t.Fatal(err) + } + doc := strings.ReplaceAll(string(raw), "\r\n", "\n") + i, j := strings.Index(doc, statusSchemaBegin), strings.Index(doc, statusSchemaEnd) + if i < 0 || j < i { + t.Fatalf("%s has no generated block", statusSchemaDoc) + } + got := doc[i : j+len(statusSchemaEnd)] + if got == want { + return + } + if os.Getenv("STATUS_SCHEMA_UPDATE") == "1" { + if err := os.WriteFile(statusSchemaDoc, []byte(doc[:i]+want+doc[j+len(statusSchemaEnd):]), 0o644); err != nil { + t.Fatal(err) + } + return + } + gl, wl := strings.Split(got, "\n"), strings.Split(want, "\n") + for k := 0; k < len(gl) || k < len(wl); k++ { + var g, w string + if k < len(gl) { + g = gl[k] + } + if k < len(wl) { + w = wl[k] + } + if g != w { + t.Fatalf("%s is out of date at line %d of the generated block:\n doc: %s\n code: %s\nregenerate with STATUS_SCHEMA_UPDATE=1", statusSchemaDoc, k+1, g, w) + } + } +} + +// The restated bodies of /status/peers and /status/durable keep the +// handlers' field names and types. +func TestStatusBodiesMatchTheRoutes(t *testing.T) { + fields := func(v any) []string { + var out []string + ty := reflect.TypeOf(v) + for i := 0; i < ty.NumField(); i++ { + out = append(out, ty.Field(i).Name+":"+ty.Field(i).Type.String()) + } + sort.Strings(out) + return out + } + src, err := os.ReadFile("status_server.go") + if err != nil { + t.Fatal(err) + } + s := string(src) + for _, f := range append(fields(peersStatusBody{}), fields(durableStatusBody{})...) { + name, typ, _ := strings.Cut(f, ":") + typ = strings.TrimPrefix(typ, "volume.") + if !strings.Contains(s, "\t\t"+name+" ") || !strings.Contains(s, typ) { + t.Errorf("status_server.go no longer declares body field %s %s", name, typ) + } + } +} + +// Every /status route the server registers is in the schema. +func TestStatusSchemaCoversEveryRoute(t *testing.T) { + listed := map[string]bool{} + for _, r := range statusRoutes { + listed[r.route] = true + } + for _, file := range []string{"status_server.go", "chunk_control.go"} { + src, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(src), "\n") { + i := strings.Index(line, `HandleFunc("/status`) + if i < 0 { + continue + } + route := line[i+len(`HandleFunc("`):] + route = route[:strings.Index(route, `"`)] + if !listed[route] { + t.Errorf("%s registers %s, which docs/status-schema.md does not cover", file, route) + } + } + } +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index e8fa35391e..eda1faaa63 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -131,39 +131,39 @@ type RuntimeRebuildResult struct { } type FrontendTransportCapability struct { - Protocol string `json:"protocol"` - Transport string `json:"transport"` - Supported bool `json:"supported"` - ListenerImplemented bool `json:"listenerImplemented"` - ListenerStarted bool `json:"listenerStarted"` - StartAllowed bool `json:"startAllowed"` - StartReason string `json:"startReason,omitempty"` - Reason string `json:"reason"` - Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` + Protocol string `json:"protocol"` // the block protocol (iscsi, nvme, ublk) + Transport string `json:"transport"` // its transport (tcp, rdma, local) + Supported bool `json:"supported"` // this build and host can serve it + ListenerImplemented bool `json:"listenerImplemented"` // a listener exists for it in this binary + ListenerStarted bool `json:"listenerStarted"` // the listener is running now + StartAllowed bool `json:"startAllowed"` // the preflight checks allow starting it + StartReason string `json:"startReason,omitempty"` // why it may or may not start + Reason string `json:"reason"` // why it is or is not supported + Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` // the host facts checked for it } type FrontendTransportPreflightFact struct { - Name string `json:"name"` - Available bool `json:"available"` - Reason string `json:"reason"` - Detail string `json:"detail,omitempty"` + Name string `json:"name"` // the host fact checked (a module, device or privilege) + Available bool `json:"available"` // the fact holds on this host + Reason string `json:"reason"` // why it holds or not + Detail string `json:"detail,omitempty"` // extra detail, such as the path probed } type FrontendCapabilitiesStatus struct { - VolumeID string `json:"volumeID"` - HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` - FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` + VolumeID string `json:"volumeID"` // the served volume + HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` // always false: host facts, not a supported-product claim + FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` // one entry per protocol and transport } type NVMeStatus struct { - VolumeID string `json:"volumeID"` - Stats nvme.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats nvme.Stats `json:"stats"` // the NVMe/TCP target's counters since start } // UblkStatus is the /status/ublk body: the ublk device's request counters. type UblkStatus struct { - VolumeID string `json:"volumeID"` - Stats ublk.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats ublk.Stats `json:"stats"` // the ublk device's request counters since start } const ( @@ -184,10 +184,16 @@ const ( // replica readiness from authority movement. type StatusProjection struct { frontend.Projection - Memory ProcessMemoryStatus + // Memory is the process's memory use at the time of the request. + Memory ProcessMemoryStatus + // FrontendPrimaryReady: this replica is the healthy, non-superseded + // primary and may serve guest I/O. FrontendPrimaryReady bool - AuthorityRole string - ReplicationRole string + // AuthorityRole is primary, superseded or unknown. + AuthorityRole string + // ReplicationRole is none (a primary), recovering, not_ready, + // replica_ready or unknown. + ReplicationRole string // RoleAdmissionFailure (G1) explains a not-Healthy projection caused // by a failed role call on the replica listener; empty otherwise. RoleAdmissionFailure string `json:",omitempty"` diff --git a/seaweed-block/core/iolatency/latency.go b/seaweed-block/core/iolatency/latency.go index 21a2a82688..c722f6000b 100644 --- a/seaweed-block/core/iolatency/latency.go +++ b/seaweed-block/core/iolatency/latency.go @@ -16,11 +16,11 @@ type Histogram struct { sum atomic.Uint64 } type Distribution struct { - Count uint64 - SumNanos uint64 - P50UpperNanos uint64 - P99UpperNanos uint64 - Buckets [64]uint64 + Count uint64 // samples observed + SumNanos uint64 // their total nanoseconds + P50UpperNanos uint64 // upper bound of the bucket holding the median + P99UpperNanos uint64 // upper bound of the bucket holding the 99th percentile + Buckets [64]uint64 // bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns } func (h *Histogram) Observe(d time.Duration) { @@ -69,16 +69,16 @@ type Requests struct { writes, flushes, fua, failed atomic.Uint64 } type RequestStatus struct { - WriteTotal Distribution - FlushTotal Distribution - FUATotal Distribution - ReceiveToBackend Distribution - AckDispatch Distribution - RequestTotal Distribution - Writes uint64 - Flushes uint64 - FUAWrites uint64 - Failed uint64 + WriteTotal Distribution // end-to-end latency of writes + FlushTotal Distribution // end-to-end latency of flushes + FUATotal Distribution // end-to-end latency of forced-unit-access writes + ReceiveToBackend Distribution // from request receipt to the backend call + AckDispatch Distribution // from backend completion to the acknowledgement sent + RequestTotal Distribution // end-to-end latency of every request + Writes uint64 // writes observed + Flushes uint64 // flushes observed + FUAWrites uint64 // forced-unit-access writes observed + Failed uint64 // requests that completed with an error } func (c *Requests) Snapshot() RequestStatus { 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/replication/peer.go b/seaweed-block/core/replication/peer.go index 6280721502..42dfadcedc 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -178,15 +178,15 @@ type ReplicaPeer struct { // append-only: status endpoints and TestOps gates use it to assert // peer recovery state without scraping logs. type ReplicaPeerStatus struct { - ReplicaID string - State string - Epoch uint64 - EndpointVersion uint64 - DataAddr string - CtrlAddr string - SessionID uint64 - ProbeInFlight bool - Closed bool + ReplicaID string // the peer replica + State string // the peer state (the replica peer table, M3) + Epoch uint64 // the epoch the peer was assigned at + EndpointVersion uint64 // the peer's endpoint version within the epoch + DataAddr string // the peer's data-path address + CtrlAddr string // the peer's control-path address + SessionID uint64 // the current recovery or shipping session; 0 when none + ProbeInFlight bool // a reachability probe of the peer is running + Closed bool // the peer handle was closed (it no longer ships) } // NewReplicaPeer constructs a per-replica runtime handle and registers 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/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 68303be17a..4a2ae329e2 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -14,12 +14,12 @@ import ( // LastAdvance stays frozen. Fields are cumulative atomic observations, not a // coherent frontier. type CheckpointPersistenceStatus struct { - Successes uint64 - Refusals uint64 - Failures uint64 - CheckpointLSN uint64 - Advances uint64 - LastAdvance time.Time + Successes uint64 // checkpoint calls that succeeded (including unchanged ones) + Refusals uint64 // checkpoint calls refused because the map coverage was stale + Failures uint64 // checkpoint calls that failed with an error + CheckpointLSN uint64 // the persisted checkpoint LSN + Advances uint64 // successes that moved CheckpointLSN forward + LastAdvance time.Time // when the latest advance happened; zero if none in this open } func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { 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_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index 4f6ce4090e..1e87bba27b 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -17,6 +17,35 @@ type FrozenDetachOptions struct { StartedAt time.Time AllowOverBudget bool } + +// FrozenBudget reports the storage-owned admission forecast and quiesce slack. +// A tail above the existing 60s ceiling is a saturated rejection sentinel, +// not a complete duration: it stays known but offers zero quiesce slack. +// INV-WS-FREEZE-ACCOUNTING-001: same-host durations; admission still rechecks. +type FrozenBudget struct { + FrozenEstimate time.Duration `json:"frozenEstimateNs"` + FrozenEstimateKnown bool `json:"frozenEstimateKnown"` + FreezeLimit time.Duration `json:"freezeLimitNs"` + MaxRefreezeQuiesce time.Duration `json:"maxRefreezeQuiesceNs"` +} + +func (r PrecopyReport) frozenBudgetEstimate() FrozenBudget { + b := FrozenBudget{FrozenEstimate: r.Estimate, FrozenEstimateKnown: r.Reason != "samples_unknown" && r.Estimate > 0, FreezeLimit: precopyFreezeLimit} + if b.FrozenEstimateKnown { + b.MaxRefreezeQuiesce = max(time.Duration(0), b.FreezeLimit-b.FrozenEstimate) + } + return b +} + +// FrozenRefusal keeps the admission observation attached to the typed error. +type FrozenRefusal struct{ Report PrecopyReport } + +func (e *FrozenRefusal) Error() string { + r := e.Report + return fmt.Sprintf("%s: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) +} +func (e *FrozenRefusal) Unwrap() error { return ErrFrozenTailTooLarge } + type frozenDetachKey struct{} func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) { @@ -35,11 +64,17 @@ func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { return r.admitFrozenAt(opts, time.Now()) } -func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { +func (r *PrecopyReport) observeFrozenAt(opts FrozenDetachOptions, now time.Time) { + r.FrozenBudget = r.frozenBudgetEstimate() r.GuestFrozen = true r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) - r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) - known := r.Reason != "samples_unknown" && r.Estimate > 0 + budget := r.FrozenBudget + r.RemainingFreeze = max(time.Duration(0), budget.FreezeLimit-r.GuestFreezeElapsed) +} + +func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { + r.observeFrozenAt(opts, now) + known := r.FrozenBudget.FrozenEstimateKnown if opts.AllowOverBudget { r.Reason = "over_budget" r.OverBudget = true @@ -56,19 +91,31 @@ func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) b return true } func frozenRefusal(r PrecopyReport) error { - return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) + return &FrozenRefusal{Report: r} } // IsReplay distinguishes a replayed applied point from a newly completed freeze. // The original report remains unchanged on the wire. func (r PrecopyReport) IsReplay() bool { return r.replayed } -func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { +func (l *chunkLayerImpl) frozenNow() time.Time { now := time.Now() if hook := l.testFrozenNow; hook != nil { now = hook() } - return r.admitFrozenAt(opts, now) + return now +} + +// M5 frozen-detach report: observe before drain/reason handling, without +// deciding admission or overriding an existing refusal. +func (l *chunkLayerImpl) observeFrozen(r *PrecopyReport, opts FrozenDetachOptions, enabled bool) { + if enabled { + r.observeFrozenAt(opts, l.frozenNow()) + } +} + +func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { + return r.admitFrozenAt(opts, l.frozenNow()) } // RememberDetachReport completes the telemetry kept with an applied or still diff --git a/seaweed-block/core/storage/chunk_frozen_report_test.go b/seaweed-block/core/storage/chunk_frozen_report_test.go new file mode 100644 index 0000000000..22430ec208 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_report_test.go @@ -0,0 +1,102 @@ +package storage + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" +) + +func TestCandidateTailReportsCompleteFrozenBudget(t *testing.T) { + for _, tc := range []struct { + name string + fixed time.Duration + samples int + tail uint64 + estimate, slack int64 + known bool + }{ + {"d05_fixed_does_not_fit", 5370 * time.Millisecond, 3, 1000, 5570000000, 0, true}, + {"small_complete_estimate", 200 * time.Millisecond, 3, 1000, 400000000, 4600000000, true}, + {"known_zero_tail", 200 * time.Millisecond, 1, 0, 300000000, 4700000000, true}, + {"zero_tail_without_fixed_sample", 0, 0, 0, 0, 0, false}, + {"ceiling_boundary_is_complete", 200 * time.Millisecond, 3, 600000, 60300000000, 0, true}, + {"saturated_tail_is_non_actionable", 200 * time.Millisecond, 3, 610000, 60000000000, 0, true}, + {"partial_unknown_rate", 200 * time.Millisecond, 1, 1000, 300000000, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < tc.samples; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: tc.fixed, rate: 20000}) + } + tail := l.estimateCandidateTail(tc.tail) + b, err := json.Marshal(tail) + if err != nil { + t.Fatal(err) + } + var got map[string]json.RawMessage + if err = json.Unmarshal(b, &got); err != nil { + t.Fatal(err) + } + for key, want := range map[string]int64{"frozenEstimateNs": tc.estimate, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": tc.slack} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, b) + } else if err = json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want %d", key, raw, want) + } + } + var known bool + if raw, ok := got["frozenEstimateKnown"]; !ok { + t.Errorf("missing frozenEstimateKnown: %s", b) + } else if err = json.Unmarshal(raw, &known); err != nil || known != tc.known { + t.Errorf("known=%s want %v", raw, tc.known) + } + }) + } +} + +func TestFrozenRefusalRetainsUnknownCompleteEstimate(t *testing.T) { + l := &chunkLayerImpl{precopySamples: []precopySample{{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}}} + r := l.precopyEstimate(1000, 0) + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) { + t.Fatal("unknown rate admitted") + } + refusal, ok := frozenRefusal(r).(*FrozenRefusal) + if !ok || refusal.Report.FrozenEstimateKnown || refusal.Report.MaxRefreezeQuiesce != 0 || refusal.Report.FrozenEstimate != 300*time.Millisecond { + t.Fatalf("partial estimate became known after reason changed: %+v", r) + } +} + +func TestFrozenDrainObservationPreservesKnownBeforeReasonMutation(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x71) + seedFrozenSamples(l, 200*time.Millisecond) + before := f.stats() + result, err := l.PrecopyDetachWithAdmission(frozenContext(t, time.Second, false), func(context.Context) (func(), error) { return nil, context.Canceled }, func() bool { t.Fatal("drain refusal stopped I/O"); return true }) + var refusal *FrozenRefusal + if !errors.As(err, &refusal) || result.Precopy.Reason != "drain_refused" { + t.Fatalf("drain path not witnessed: %+v %v", result.Precopy, err) + } + r := refusal.Report + if !r.FrozenEstimateKnown || r.FrozenEstimate != r.Estimate || r.FreezeLimit != 5*time.Second || r.GuestFreezeElapsed < time.Second || r.RemainingFreeze <= 0 || r.RemainingFreeze+r.GuestFreezeElapsed != 5*time.Second { + t.Fatalf("drain reason destroyed known observation: %+v", r) + } + after := f.stats() + if after.puts != before.puts || after.cas != before.cas { + t.Fatal("drain refusal did remote work") + } +} +func TestFrozenSaturatedTailRemainsKnownButNonActionable(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}) + } + r := l.precopyEstimate(610000, 0) // safe rate 10000 B/s -> 61s tail, beyond the existing ceiling. + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) || r.Estimate != 60*time.Second || r.TailEstimate != 60*time.Second || !r.FrozenEstimateKnown || r.FrozenEstimate != 60*time.Second || r.FreezeLimit != 5*time.Second || r.MaxRefreezeQuiesce != 0 { + t.Fatalf("saturated sentinel became actionable or changed admission: %+v", r) + } +} 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..510ed56ed2 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -16,16 +16,16 @@ const defaultHydrationQueueDepth = 64 // ChunkHydrationStats separates wait refusals from owned fetch outcomes. // A wait refusal is not necessarily a wire completion (a caller may cancel). type ChunkHydrationStats struct { - WorkerLimit int - QueueDepth int - Active int - Queued int - WaitCalls uint64 - Joined uint64 - WaitRefusals uint64 - Fetches uint64 - Completed uint64 - FetchErrors uint64 + WorkerLimit int // fetch workers allowed (--chunk-hydration-workers) + QueueDepth int // fetch queue capacity (--chunk-hydration-queue-depth) + Active int // fetches running now + Queued int // fetches waiting for a worker now + WaitCalls uint64 // reads that waited for a chunk to arrive + Joined uint64 // of those, reads that joined a fetch already running + WaitRefusals uint64 // waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) + Fetches uint64 // fetches started + Completed uint64 // fetches that installed the chunk + FetchErrors uint64 // fetches that failed } type chunkHydrationFlight struct { @@ -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 ad4f45955a..daf1adaeae 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -132,6 +132,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) @@ -1481,6 +1482,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_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index f62da76818..526e52c9e7 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -80,6 +80,7 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + FrozenBudget replayed bool // transport-local marker; never replaces the original freeze telemetry. // Live barrier prefix is diagnostic, not additive to the selected forecast. @@ -218,6 +219,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool { report = l.precopyEstimate(tail, report.Attempts) + l.observeFrozen(&report, guestFreeze, externallyFrozen) report.Drain = drain report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) if drainErr != nil { @@ -524,5 +526,5 @@ func (l *chunkLayerImpl) candidateTailBytes() uint64 { func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail { r := l.precopyEstimate(bytes, 0) - return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} + return &ChunkCandidateTail{FrozenBudget: r.frozenBudgetEstimate(), Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 7be66e2e10..3b9818c5fa 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -375,10 +375,10 @@ type chunkLayerConfig struct { // impl3 uses its owned LSN map and never calls this optional legacy object. Bitmap chunkBitmapStore - // BarrierBound bounds how many chunks a cut copies under its barrier: - // beyond it, chunks are pre-copied outside the barrier in staging - // rounds (at most chunkStageRounds; then the barrier takes the rest). - // Zero: unbounded, no staging. + // BarrierBound is for legacy test fixtures only: it sets + // BarrierOverBound when a cut copies more chunks than this under its + // barrier. Production staging is by the copy-on-write side budget (M5 + // Stage), and production leaves this zero. BarrierBound int // UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8). @@ -414,14 +414,14 @@ type chunkLayerConfig struct { // value means "not measured". // SyncPhaseStats are nested details of SyncNs; never add them to SyncNs. type SyncPhaseStats struct { - LifecycleWaitNs int64 `json:"lifecycleWaitNs"` - StoreWaitNs int64 `json:"storeWaitNs"` - GroupCommitNs int64 `json:"groupCommitNs"` - CompletionWaitNs int64 `json:"completionWaitNs"` + LifecycleWaitNs int64 `json:"lifecycleWaitNs"` // waiting for the store's lifecycle lock + StoreWaitNs int64 `json:"storeWaitNs"` // waiting for the store lock + GroupCommitNs int64 `json:"groupCommitNs"` // in the group commit that made the data durable + CompletionWaitNs int64 `json:"completionWaitNs"` // waiting for the sync leader role to validate the completion } type chunkCutStats struct { - SyncPhases SyncPhaseStats + SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it) // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 @@ -459,11 +459,12 @@ type chunkCutStats struct { MapPersistNs int64 CASResult string TotalNs int64 - // Pre-copy (BarrierBound > 0): StageRounds staging rounds staged - // StagedChunks chunks outside the barrier; StagedChunksUsed of the - // uploads in HEAD came from staging. BarrierCopyChunks were copied - // under the barrier; BarrierOverBound: more than the bound (the - // staging rounds did not converge). + // Pre-copy (staging by the copy-on-write side budget, M5 Stage): + // StageRounds staging rounds staged StagedChunks chunks outside the + // barrier; StagedChunksUsed of the uploads in HEAD came from staging. + // BarrierCopyChunks were copied under the barrier. BarrierOverBound: + // more than the legacy fixture BarrierBound; always false in + // production, where that bound is zero. StageRounds int StagedChunks int StagedChunksUsed int @@ -491,25 +492,28 @@ type chunkCutStats struct { // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the // last successful cut, whatever triggered it. type chunkLayerStats struct { - Hydration ChunkHydrationStats - CutsOK uint64 - CutsNoop uint64 - CutsFailed uint64 - CutsRefused map[string]uint64 - CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload - CASConflicts uint64 - CASUnknown uint64 - PendingUnresolved bool - DirtyChunks int - Reconciling bool - ReconcileDone int - ReconcileTotal int - LastCut chunkCutStats - LastCutH uint64 - LastCutNs int64 + Hydration ChunkHydrationStats // lazy fetches of absent chunks from the remote + CutsOK uint64 // cuts that installed a HEAD + CutsNoop uint64 // cuts with nothing new (no CAS) + CutsFailed uint64 // every other cut failure + CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload + CASConflicts uint64 // HEAD CAS precondition failures + CASUnknown uint64 // HEAD CAS results still unresolved after the re-read + PendingUnresolved bool // an unresolved HEAD proposal is held now + DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation) + Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile + ReconcileDone int // chunks compared so far + ReconcileTotal int // chunks to compare + LastCut chunkCutStats // the last successful cut's measurements + LastCutH uint64 // the LSN the last successful cut published + LastCutNs int64 // when it completed (wall clock, Unix ns) // 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. @@ -526,6 +530,7 @@ type chunkLayerStats struct { // Bytes and rate/estimate belong to one sampler observation; Known=false must // never be interpreted as a zero-cost tail. Admission rechecks at its barrier. type ChunkCandidateTail struct { + FrozenBudget Bytes uint64 `json:"bytes"` Estimate time.Duration `json:"estimateNs"` BytesPerSecond float64 `json:"bytesPerSecond"` diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 960cdf8400..d9c09de74e 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -38,8 +38,8 @@ func selectedDataSyncMode(f *os.File) (string, string, error) { // DataSyncStatus is immutable for the lifetime of an open volume. type DataSyncStatus struct { - Mode string - Reason string + Mode string // the data-file sync call in use (fsync or fdatasync) + Reason string // why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) } func (s *WALStore) DataSyncPolicy() DataSyncStatus { return s.dataSyncStatus } 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/durability_latency.go b/seaweed-block/core/storage/durability_latency.go index d72c974cf2..aab547da7e 100644 --- a/seaweed-block/core/storage/durability_latency.go +++ b/seaweed-block/core/storage/durability_latency.go @@ -5,9 +5,9 @@ import "github.com/seaweedfs/seaweed-block/core/iolatency" // DurabilityLatencyStatus separates request queue residence from physical file // sync attempts. A shared sync has one sample, not one sample per waiter. type DurabilityLatencyStatus struct { - WALAppend iolatency.Distribution - GroupCommitWait iolatency.Distribution - FileSync iolatency.Distribution + WALAppend iolatency.Distribution // WAL append latency + GroupCommitWait iolatency.Distribution // time a sync request waited in the group commit queue + FileSync iolatency.Distribution // physical file syncs (one sample per sync, however many waiters) } func (s *WALStore) DurabilityLatency() DurabilityLatencyStatus { 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/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index cce3021c5c..a40f5f7c7f 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -113,9 +113,6 @@ SWB_CHUNK_REPLICATION= SWB_CHUNK_CAPTURE_INTERVAL=0 # --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads. SWB_CHUNK_UPLOAD_CONCURRENCY=8 -# --chunk-dirty-threshold (default 512 chunks = 2 GiB; 0 = unbounded). Bound -# on one cut's barrier copy; never triggers a cut. -SWB_CHUNK_DIRTY_THRESHOLD=512 # --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot, # snapshots, snapshot/delete, detach) on the status listener; needs # SWB_STATUS_ADDR. diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index 37fdd5fb1a..c15dcbb0a2 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -60,7 +60,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index a17b9d7980..28675f37ce 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -59,7 +59,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..d5318a20df 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 (off by default; when set, at least 5m in the OSS CLI). Periodic cuts update HEAD without creating named snapshots. Dirty chunks never trigger a cut. +- **Recoverable frontier.** The confirmed remote HEAD is the recovery point after host loss. With the periodic timer off (the default), HEAD advances at explicit cuts, snapshots and detach; 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 @@ -122,7 +122,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `chunkLayerImpl.captureLocked` (`core/storage/chunk_layer.go`; contract in the `chunk_seam.go` header). A checkpoint is not a prefix image (the extent can already hold blocks newer than the checkpoint), so a cut is a quiesced point, not a checkpoint boundary. 1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease). -2. **Pre-copy:** while more than `BarrierBound` chunks would be copied under the barrier (`--chunk-dirty-threshold`, default 512), stage up to that many per round outside the barrier, for at most `chunkStageRounds` (3) rounds (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. +2. **Pre-copy:** while the chunks that would be copied under the barrier exceed half the copy-on-write side budget, stage the hottest of them per round outside the barrier, repeating only while the remainder shrinks (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. 3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent. 4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes. 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). @@ -145,10 +145,10 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto **Design.** 1. **Short barrier; `capMu` held for the whole cut.** The chunk layer's `capMu` stays held from admission to the end of the cut, as today; it already serializes Capture with Evict and Begin/EndBaseInstall, so no BASE install can start inside a window. Under `captureMu` exclusive the cut's `Sync` fixes H and the candidate set D is fixed as today (the owned chunk LSN map relative to HEAD plus retained WAL and in-memory mutations). A COW window `{H, D, state per chunk, refcount}` is installed in the chunk layer, then only `captureMu` is released. The stall becomes `Sync` plus fixing D, independent of the bytes to copy. 2. **Per-chunk state and one owner.** Each chunk of D is `pending`, then exactly one owner moves it on, under a small per-chunk mutex that is never held across I/O: - - the copier: `pending â†' copying â†' done`; - - a writer: `pending â†' saving â†' saved` (the copier later reads the saved bytes: `saved â†' done`). + - the copier: `pending �' copying �' done`; + - a writer: `pending �' saving �' saved` (the copier later reads the saved bytes: `saved �' done`). Everyone else who finds `copying` or `saving` waits on that chunk's condition until it reaches `done` or `saved`, or until the window is aborted (step 5). -3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) â†' per-chunk COW mutex (leaf, released before any read) â†' the read path's own locks. +3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) �' per-chunk COW mutex (leaf, released before any read) �' the read path's own locks. - chunk not in D, `done` or `saved`: proceed; - `pending`: become the owner (`saving`), read the chunk (still its content at H), put it in the side store, mark `saved`, wake waiters, proceed; - `copying` or `saving`: wait (step 2), then re-check. @@ -186,8 +186,10 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. -- **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. -- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Fork** (`Catalog.Fork`): take the deadline start and read the parent snapshot (every attempt reads it again; a parent deleting or gone refuses; the parent is not claimed), 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`; until its first HEAD the parent stays rooted by GC's grace after any delete, 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. Model: `docs/spec/RestoreIndependence.tla`. +- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; no snapshot is kept because of a fork or restore; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Snapshot delete in any order with forks** (no claims): a fork publishes only before its read time + operation deadline, and GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector` refuses otherwise); an unknown publish keeps the fork intent, which roots the keys until the target is resolved. Model: `ForkDelete` (`G >= D + E + P`). - **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`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; @@ -199,13 +201,13 @@ stateDiagram-v2 2. **Run GC with `--apply`.** The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates. 3. **Volume vacuum in SeaweedFS.** GC deletes the needle; SeaweedFS returns the disk space when it vacuums that volume. Until then the bytes stay on the volume servers. - **Why a reachability mark and not reference counts.** Chunks and segments are shared by snapshots and forks of any number of volumes. A reference count kept in filer entries and changed by several hosts can be lost or applied twice by a crash or an unknown outcome; a lost increment would delete live data. The mark recomputes reachability from the roots on every pass, and the two-mark grace covers writers that are about to publish keys they already uploaded. The cost is delay: space comes back hours after a delete, not at once. -- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting â†' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. +- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting �' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. 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) @@ -227,7 +229,7 @@ stateDiagram-v2 [*] --> NameHeld: exclusive name record {request, attempt} NameHeld --> Published: exclusive create snaps/name/attempt NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path - Published --> Deleting: DeleteSnapshot or retention (no live fork claim) + Published --> Deleting: DeleteSnapshot or retention (forks do not hold it) Deleting --> NameFreed: name record removed Aborted --> NameFreed: name record removed NameFreed --> [*] @@ -235,13 +237,55 @@ stateDiagram-v2 The attempt path is never removed, so a late create can never land after a delete. +Restore (target volume): + +```mermaid +stateDiagram-v2 + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD + Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys + Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Independent --> [*] + Aborted --> [*]: target deleted +``` + +Snapshots of the target are refused in `Forking` and `Restoring`. + +### Attached-volume scheduling + +Periodic HEAD capture is off by default (opt-in; when set, at least 5 +minutes), and retention runs 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`). **Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). -**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS â†' revoke â†' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation â†' blockmaster checks the detached HEAD and the matching acknowledgement â†' new epoch â†' the new host claims HEAD. +**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS �' revoke �' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation �' blockmaster checks the detached HEAD and the matching acknowledgement �' new epoch �' the new host claims HEAD. **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. @@ -333,7 +377,7 @@ Not done yet: | Chunks and segments are write-once; keys are never rebound | `chunk_remote.go` `putObject`; `gc.go` tombstones | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | yes | | Intents are durable before the first upload and removed only after the CAS outcome is known | `captureLocked` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | yes | | GC never deletes a chunk reachable from a HEAD, snapshot, attempt or intent, and deletes only after two graced marks | `gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | yes | -| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, never while a fork claim is live | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | yes | +| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, in any order with forks (no claims) | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestSnapshotDelete_DeleteDuringAForkInFlight` (`core/frontend/chunkstore/snapshot_delete_test.go`) | yes | | Volume delete commits only with no snapshot name records; past the commit point it is irreversible | `volume_delete.go` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne`, `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | Volume ids are never reused | `core/host/master/services.go`; `catalog.go` `EnsureVolume` | `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | A host serves and cuts only under a valid lease; a fenced guard never reopens | `workspace_lease.go` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | yes | diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c2299624cd..67364b1f1c 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 @@ -216,7 +218,7 @@ stateDiagram-v2 Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload Quiesce --> FinalFreeze: measured admission or explicit frozen final override FinalFreeze --> OpenWindow: admission stays closed through detached settlement - Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier + Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier; release all held admission OpenWindow --> Copy: release barrier Copy --> Upload: local entry released, intent durable first Upload --> Copy: next unsent candidate @@ -242,11 +244,11 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | -| 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 resume in FIFO order after a safe abort | `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` | -| 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 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; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | +| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-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` | @@ -283,8 +290,11 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (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 -120 rows: 101 ACTIVE, 19 STUB; 15 kept from the internal ledger, 105 new. +138 rows: 118 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 123 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`). @@ -466,18 +501,23 @@ Notes: | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | +| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `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-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply) before it reads or writes; read-only commands and modes do not run it. - `INV-WS-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,7 +527,9 @@ 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-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | 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`, `TestPrecopyQueueResumesInFIFOOrder`, `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-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | 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 | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | @@ -512,29 +554,44 @@ A guest read has a cooperative arrival budget; internal contextless readers keep Notes: +- `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. + - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). +- `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. + ### B.6 Workspace: chunk lifecycle, GC and delete | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-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-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-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | +| `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-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` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | | `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | | `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: +- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. - `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing. - `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it. -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. - `ChunkRemote.ReclaimKey` is the Collector's per-key step (`reclaimBinding`) exported, not a new admission: `INV-GC-REACHABLE-001` (reachability and the two-mark grace) stays the Collector's, and a `ReclaimKey` caller must itself know nothing references the key. The step keeps `INV-CHUNK-WRITE-ONCE-001`: the binding is tombstoned, its exact fid deleted, and the binding kept for ever, never rebound; owner-qualified keys are refused. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing @@ -618,3 +675,12 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a - `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. - The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. - Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. + + +## Part D. Wait ownership + +| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | +|---|---|---|---|---| +| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | + +Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. diff --git a/seaweed-block/docs/spec/ForkDelete.tla b/seaweed-block/docs/spec/ForkDelete.tla new file mode 100644 index 0000000000..f3014fe1c3 --- /dev/null +++ b/seaweed-block/docs/spec/ForkDelete.tla @@ -0,0 +1,305 @@ +---------------------------- MODULE ForkDelete ---------------------------- +(***************************************************************************) +(* Fork / restore versus snapshot delete with NO lock between them. *) +(* *) +(* Volume V has one published snapshot S naming the chunks 1..NC. A fork *) +(* creates a new volume T whose HEAD will name S's chunks. A delete of S *) +(* never waits for, and is never refused because of, a fork. Safety comes *) +(* from two time rules only: *) +(* (F) the fork reads S at its local time readAt and publishes T's HEAD *) +(* only if its local clock is still < readAt + D (checked right *) +(* before publishing: one atomic step, or, with PublishAtomic=FALSE, *) +(* a check step and a later publish step at most P ticks apart); *) +(* (G) the delete is stamped delAt on the catalog's local clock; GC keeps *) +(* S's chunks rooted while ITS local clock is < delAt + G. *) +(* GC is one atomic step deleting every chunk no root names. Roots: V's *) +(* HEAD (V may overwrite chunks), S while not deleted, S's deleted record *) +(* until the grace has passed, T's HEAD once published. *) +(* *) +(* Time: real time `now` ticks by 1. Actor a reads now + bias[a]; biases *) +(* are fixed at start in -E..E with pairwise difference <= E. Clocks do *) +(* not step and run at the same rate. *) +(* *) +(* Mutant switches are CONSTANTS; the design value is noted on each. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NC, \* chunks 1..NC, all named by S (and by V's HEAD at start) + D, \* operation deadline of the fork (on the fork's clock) + G, \* GC grace after a delete (delAt on the catalog clock, compared on the GC clock) + E, \* pairwise clock skew bound + P, \* max ticks between the deadline check and the publish (PublishAtomic=FALSE only) + MaxNow, \* real-time bound + MaxAttempts, \* fork attempts (1 = no retry) + MaxReads, \* reads of T after its publish (witness only) + VCanOverwrite, \* [TRUE] V may stop naming chunks (nondeterministic action) + \* ---- design switches (design value in brackets) ---- + PublishChecksDeadline, \* [TRUE] publish only if local clock < readAt + D + DeletedRecordRooted, \* [TRUE] deleted S roots its chunks until the grace has passed + PublishAtomic, \* [TRUE] check + publish in one step; FALSE: two steps <= P ticks apart + RetryAfterDelete \* [TRUE] a retry re-reads S (fails if deleted); FALSE: reuses old chunk set + +ASSUME NC \in Nat /\ D \in Nat /\ G \in Nat /\ E \in Nat /\ P \in Nat /\ MaxNow \in Nat + +Chunks == 1..NC +SChunks == Chunks +Actors == {"F", "C", "GC"} \* fork process, catalog (stamps delete), garbage collector +NoTime == -1000 +FStates == {"idle", "read", "created", "checked", "published", "failed", "crashed", "notfound"} + +VARIABLES + now, \* real time + bias, \* actor -> clock bias (fixed after Init) + vNames, \* chunks V's HEAD still names + sDeleted, \* S has been deleted + delAt, \* catalog-local time stamped on the delete (NoTime before) + exists, \* chunk -> still stored + fst, \* fork state + attempts, \* fork attempts started + readAt, \* fork-local time of the current attempt's read + readSet, \* chunk set held by the fork (from the last real read of S) + haveRead, \* some attempt has read S successfully + checkAt, \* real time of the deadline check (two-step publish only) + tPub, \* T's HEAD is published + tHead, \* chunks named by T's HEAD + nReads, \* reads of T done + \* ---- history (witnesses / trace readability) ---- + pubAfterDel, \* T's HEAD was published after S was deleted + lateReadOK, \* T read all its chunks after the grace passed, with V no longer naming them + deadlineLoss, \* a fork attempt failed cleanly on the deadline + retryNotFound, \* a retry got "snapshot not found" + lastAct \* name of the last action (for traces) + +forkVars == <> +tVars == <> +histVars == <> +vars == <> + +LC(a) == now + bias[a] \* local clock of actor a + +TypeOK == + /\ now \in 0..MaxNow + /\ bias \in [Actors -> -E..E] + /\ vNames \subseteq Chunks + /\ sDeleted \in BOOLEAN + /\ delAt \in Int + /\ exists \in [Chunks -> BOOLEAN] + /\ fst \in FStates + /\ attempts \in 0..MaxAttempts + /\ readAt \in Int + /\ readSet \subseteq Chunks + /\ haveRead \in BOOLEAN + /\ checkAt \in Int + /\ tPub \in BOOLEAN + /\ tHead \subseteq Chunks + /\ nReads \in 0..MaxReads + /\ pubAfterDel \in BOOLEAN + /\ lateReadOK \in BOOLEAN + /\ deadlineLoss \in BOOLEAN + /\ retryNotFound \in BOOLEAN + /\ lastAct \in STRING + +Init == + /\ now = 0 + /\ bias \in {b \in [Actors -> -E..E] : (\A x, y \in Actors : b[x] - b[y] <= E)} + /\ vNames = Chunks + /\ sDeleted = FALSE + /\ delAt = NoTime + /\ exists = [c \in Chunks |-> TRUE] + /\ fst = "idle" + /\ attempts = 0 + /\ readAt = NoTime + /\ readSet = {} + /\ haveRead = FALSE + /\ checkAt = NoTime + /\ tPub = FALSE + /\ tHead = {} + /\ nReads = 0 + /\ pubAfterDel = FALSE + /\ lateReadOK = FALSE + /\ deadlineLoss = FALSE + /\ retryNotFound = FALSE + /\ lastAct = "Init" + +(* ============================ time ============================ *) + +\* Real time advances. With a two-step publish, at most P ticks pass between check and publish. +Tick == + /\ now < MaxNow + /\ (PublishAtomic \/ fst # "checked" \/ now < checkAt + P) + /\ now' = now + 1 + /\ lastAct' = "Tick" + /\ UNCHANGED <> + +(* ============================ fork ============================ *) + +\* Start an attempt (first try, or retry after a clean failure or a crash). +ReadSnapshot == + /\ fst \in {"idle", "failed", "crashed"} + /\ attempts < MaxAttempts + /\ attempts' = attempts + 1 + /\ lastAct' = "ReadSnapshot" + /\ (IF ~RetryAfterDelete /\ haveRead + THEN \* mutant: reuse the chunk set of an earlier attempt, no re-read of S + /\ fst' = "read" + /\ readAt' = LC("F") + /\ UNCHANGED <> + ELSE (IF sDeleted + THEN /\ fst' = "notfound" \* "snapshot not found": T never gets a HEAD + /\ retryNotFound' = (retryNotFound \/ attempts > 0) + /\ UNCHANGED <> + ELSE /\ fst' = "read" + /\ readAt' = LC("F") + /\ readSet' = SChunks + /\ haveRead' = TRUE + /\ UNCHANGED retryNotFound)) + /\ UNCHANGED <> + +\* Create T's record (no HEAD yet, no effect on roots). +CreateTarget == + /\ fst = "read" + /\ fst' = "created" + /\ lastAct' = "CreateTarget" + /\ UNCHANGED <> + +DeadlineOK == (~PublishChecksDeadline) \/ (LC("F") < readAt + D) + +\* Publish T's HEAD = the chunk set held by the fork. +DoPublish == + /\ fst' = "published" + /\ tPub' = TRUE + /\ tHead' = readSet + /\ pubAfterDel' = (pubAfterDel \/ sDeleted) + +\* (F) atomic: deadline check and publish in one step. +PublishAtomicStep == + /\ PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ DoPublish + /\ lastAct' = "Publish" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "PublishDeadlineFail" + /\ UNCHANGED <>) + /\ UNCHANGED <> + +\* (F) two-step, step 1: the deadline check. +CheckDeadline == + /\ ~PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ fst' = "checked" + /\ checkAt' = now + /\ lastAct' = "CheckDeadlineOK" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "CheckDeadlineFail" + /\ UNCHANGED checkAt) + /\ UNCHANGED <> + +\* (F) two-step, step 2: the publish, no new check (Tick bounds it to <= P ticks after the check). +PublishAfterCheck == + /\ fst = "checked" + /\ DoPublish + /\ lastAct' = "PublishAfterCheck" + /\ UNCHANGED <> + +\* The fork crashes in the middle of an attempt; it may later retry or never continue. +Crash == + /\ fst \in {"read", "created", "checked"} + /\ fst' = "crashed" + /\ lastAct' = "Crash" + /\ UNCHANGED <> + +(* ========================== catalog / V ========================== *) + +\* (G) delete S at any time: stamped on the catalog clock; S stops being a live root. +DeleteS == + /\ ~sDeleted + /\ sDeleted' = TRUE + /\ delAt' = LC("C") + /\ lastAct' = "DeleteS" + /\ UNCHANGED <> + +\* V's HEAD stops naming chunk c (V overwrote it). +VOverwrite(c) == + /\ VCanOverwrite + /\ c \in vNames + /\ vNames' = vNames \ {c} + /\ lastAct' = "VOverwrite" + /\ UNCHANGED <> + +(* ============================== GC ============================== *) + +Rooted(c) == + \/ c \in vNames + \/ ~sDeleted + \/ (DeletedRecordRooted /\ LC("GC") < delAt + G) + \/ (tPub /\ c \in tHead) + +\* One step: delete every stored chunk no root names. +GC == + /\ (\E c \in Chunks : exists[c] /\ ~Rooted(c)) + /\ exists' = [c \in Chunks |-> exists[c] /\ Rooted(c)] + /\ lastAct' = "GC" + /\ UNCHANGED <> + +(* ============================ readers of T ============================ *) + +TRead == + /\ tPub + /\ nReads < MaxReads + /\ nReads' = nReads + 1 + /\ lateReadOK' = (lateReadOK \/ + (/\ sDeleted + /\ vNames \cap tHead = {} + /\ LC("GC") >= delAt + G + /\ (\A c \in tHead : exists[c]))) + /\ lastAct' = "TRead" + /\ UNCHANGED <> + +Next == + \/ Tick + \/ ReadSnapshot + \/ CreateTarget + \/ PublishAtomicStep + \/ CheckDeadline + \/ PublishAfterCheck + \/ Crash + \/ DeleteS + \/ (\E c \in Chunks : VOverwrite(c)) + \/ GC + \/ TRead + +Spec == Init /\ [][Next]_vars + +(* ============================ properties ============================ *) + +\* Whenever T's HEAD is published, every chunk it names exists (checked in every state). +NoGap == tPub => (\A c \in tHead : exists[c]) + +(* Witnesses: each is expected VIOLATED (= the behaviour is reachable). *) +\* Benefit: a fork that read S before the delete publishes after the delete and T reads fine +\* after the grace has passed (only T's HEAD roots the chunks then). +WitNoBenefit == ~(pubAfterDel /\ lateReadOK) +\* A fork loses cleanly because the deadline passed. +WitNoDeadlineLoss == ~deadlineLoss +\* A retry gets "snapshot not found". +WitNoRetryNotFound == ~retryNotFound +\* GC deletes some chunk at all (shows GC is not vacuous in a safe configuration). +WitNoGCDelete == \A c \in Chunks : exists[c] +============================================================================= diff --git a/seaweed-block/docs/spec/FrozenDetachBudget.tla b/seaweed-block/docs/spec/FrozenDetachBudget.tla index e8f83cb8ee..e39c3eeffb 100644 --- a/seaweed-block/docs/spec/FrozenDetachBudget.tla +++ b/seaweed-block/docs/spec/FrozenDetachBudget.tla @@ -11,13 +11,15 @@ VARIABLES phase, elapsed, estimate, known, force, authority, admitted, vars == <> Init == /\ phase = "forecast" /\ elapsed \in {0,30,60} - /\ estimate \in {5,30,60} /\ known \in BOOLEAN + /\ estimate \in {0,5,30,60} /\ known \in BOOLEAN /\ force \in BOOLEAN /\ authority \in BOOLEAN /\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE /\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0 /\ atKnown = FALSE AuthorityOK == authority \/ OmitAuthority -Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit +FrozenEstimateKnown == known /\ estimate > 0 +MaxRefreezeQuiesce == IF FrozenEstimateKnown /\ estimate < Limit THEN Limit-estimate ELSE 0 +Fits == FrozenEstimateKnown /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit Eligible == AuthorityOK /\ (force \/ Fits) Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage" /\ UNCHANGED < admitted BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit OverrideVisible == admitted /\ force => overBudget AuthorityAtPublication == published => authority +ReportSlackSound == MaxRefreezeQuiesce >= 0 /\ + (MaxRefreezeQuiesce > 0 => known /\ estimate > 0 /\ MaxRefreezeQuiesce + estimate = Limit) /\ + (~FrozenEstimateKnown => MaxRefreezeQuiesce = 0) ============================================================================= 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..5dc3e958cf 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,8 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `ForkDelete.tla` | `cfg/ForkDelete_*` | snapshot delete in any order with forks | +| `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore | Each `.cfg` names its spec on its first line. @@ -116,6 +118,8 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. Claim-era model: `ClaimUntilHead` selects the fork claim as it was before fork claims were removed (`INV-SNAP-DELETE-ANY-ORDER-001`), the strict variant keeps it until independent; the code no longer claims, and the no-claim variant ships with the restore driver. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits @@ -305,7 +309,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 +339,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 +459,61 @@ 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. + +### Frozen budget response quantities (F2) + +The additive `candidateTail` and typed refusal quantities share storage's +complete estimate, including its existing margin. Tail-known alone is not +complete-estimate-known. `FrozenDetachBudget` now includes estimate zero and +derives `FrozenEstimateKnown` and `MaxRefreezeQuiesce`; `ReportSlackSound` checks +positive slack implies a known positive estimate and slack + estimate = limit. +These durations are same-host advice, not a physical completion bound or a change +to the existing wall-origin request. Admission still rechecks at its barrier. + +TLC 2.19, tools SHA256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`, +local 2026-11-21 10:43Z: `FrozenDetachBudget.cfg` exhausted 829 generated / 535 +distinct states, depth 6, queue empty, no invariant violation. Bounds: elapsed +{0,30,60}, estimate {0,5,30,60} (then barrier growth), known/force/authority Boolean; +limit 50, no physical I/O latency. Raw quantities and JSON preservation are +checked by native Go tests; this derived arithmetic model does not model the HTTP +encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. + +#344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard. 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/ForkDelete_red_bnd_D1E1G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg new file mode 100644 index 0000000000..08a0f98ca5 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 1 + E = 1 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg new file mode 100644 index 0000000000..2461983061 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1, E=0). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 1 + E = 0 + P = 0 + MaxNow = 7 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg new file mode 100644 index 0000000000..5231a1b4ed --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg new file mode 100644 index 0000000000..ccb2842e87 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 4 + E = 2 + P = 0 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg new file mode 100644 index 0000000000..dde4eaec5e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary with 2 chunks. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg new file mode 100644 index 0000000000..350144738f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg @@ -0,0 +1,19 @@ +\* RED: a deleted snapshot stops being a root at once. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = FALSE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg new file mode 100644 index 0000000000..51d3895c09 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=0 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg new file mode 100644 index 0000000000..95f97f1fd1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=1 at the atomic grace G = D+E. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 1 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg new file mode 100644 index 0000000000..ced2c0e10d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2, E=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 4 + E = 2 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg new file mode 100644 index 0000000000..7a07ed8ad3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 2 + MaxNow = 14 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg new file mode 100644 index 0000000000..aa381427c9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg @@ -0,0 +1,19 @@ +\* RED: publish without the deadline check. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = FALSE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg new file mode 100644 index 0000000000..6460befc5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg @@ -0,0 +1,19 @@ +\* RED: a retry reuses the earlier chunk set without re-reading S. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = FALSE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg new file mode 100644 index 0000000000..73d4fdfd71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 2 + E = 1 + P = 0 + MaxNow = 9 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg new file mode 100644 index 0000000000..e696bfb904 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E, E=0; the brief's 'G <= D' case). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 0 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg new file mode 100644 index 0000000000..0aa22d44df --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg new file mode 100644 index 0000000000..8cb5038239 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+E+1). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 0 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg new file mode 100644 index 0000000000..64c5cc8045 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+2E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 6 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg new file mode 100644 index 0000000000..fbdcd1ee9a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 5 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg new file mode 100644 index 0000000000..1c85552c5c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=0 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg new file mode 100644 index 0000000000..d95d95dd61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=1 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg new file mode 100644 index 0000000000..22712e7e9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2, E=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 5 + E = 2 + P = 2 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg new file mode 100644 index 0000000000..d9ade18294 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 5 + E = 1 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg new file mode 100644 index 0000000000..d5b21cec71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary with 2 chunks, 3 attempts, 2 reads. Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg new file mode 100644 index 0000000000..96ab829d76 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): fork read before the delete, published after it, T reads fine after the grace. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg new file mode 100644 index 0000000000..c1ad118800 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg @@ -0,0 +1,20 @@ +\* WITNESS two-step P=1 at its safe grace (expected VIOLATED = reachable): benefit still reachable. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg new file mode 100644 index 0000000000..278b224e07 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a fork fails cleanly on the deadline. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoDeadlineLoss diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg new file mode 100644 index 0000000000..c8e81bc147 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): GC deletes S's chunks in a safe configuration. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoGCDelete diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg new file mode 100644 index 0000000000..ab7b41316a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a retry gets snapshot-not-found. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoRetryNotFound diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg index 7992b80dde..1fbd6505f5 100644 --- a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg @@ -5,4 +5,4 @@ CONSTANTS OmitStageGuard = FALSE OmitOverrideRecord = FALSE OmitAuthority = FALSE -INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication ReportSlackSound 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/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c2c8f5abb4..1e1f3e1d4f 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -124,7 +124,6 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles | | `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` | | `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) | -| `SWB_CHUNK_DIRTY_THRESHOLD` | `--chunk-dirty-threshold` | `512` | Bound on one cut's barrier copy, in chunks | | `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener | | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | | `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md new file mode 100644 index 0000000000..02d7a1d468 --- /dev/null +++ b/seaweed-block/docs/status-schema.md @@ -0,0 +1,402 @@ +# Status schema + +The blockvolume status listener (`--status-addr`) serves JSON on the routes below. Each table lists every field a route returns: its JSON path (`[]` marks a list, `{}` a map), its type, and its meaning as the field's Go comment states it. A field marked `—` has no comment in the code yet. + +The tables are generated from the Go types, so they list exactly the fields that exist. `go test ./core/host/volume -run TestStatusSchemaDoc` fails when the code and this page disagree; `STATUS_SCHEMA_UPDATE=1` rewrites the generated block. + +All routes take `?volume=` and answer 404 for a volume this host does not serve. + + + +### `GET /status` + +The volume's authority and health projection. Go type `volume.StatusProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the volume this host serves | +| `ReplicaID` | string | this host's replica of it | +| `Epoch` | uint64 | the authority epoch of the current assignment | +| `EndpointVersion` | uint64 | the assignment's endpoint version within the epoch | +| `Healthy` | bool | the replica may serve I/O at this epoch | +| `Memory` | object | Memory is the process's memory use at the time of the request. | +| `Memory.HeapAllocBytes` | uint64 | Go heap bytes in live objects (runtime.MemStats.HeapAlloc) | +| `Memory.HeapInuseBytes` | uint64 | Go heap bytes in in-use spans (HeapInuse) | +| `Memory.HeapSysBytes` | uint64 | Go heap bytes obtained from the OS (HeapSys) | +| `Memory.HeapReleasedBytes` | uint64 | Go heap bytes returned to the OS (HeapReleased) | +| `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) | +| `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | +| `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | +| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary and may serve guest I/O. | +| `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. | +| `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | +| `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | +| `UnhealthyReason` | string | UnhealthyReason is the slot's explicit unhealthy report (#128 rule 6), the value its heartbeat carries; empty when healthy. (omitted when empty) | +| `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) | +| `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | +| `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | +| `Warnings[]` | string | Warnings are the durable store's typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) | + +### `GET /status/peers` + +Replication peers of the served volume. Go type `volume.peersStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `PeerCount` | int | number of entries in Peers | +| `Peers[]` | object | this primary's replication peers | +| `Peers[].ReplicaID` | string | the peer replica | +| `Peers[].State` | string | the peer state (the replica peer table, M3) | +| `Peers[].Epoch` | uint64 | the epoch the peer was assigned at | +| `Peers[].EndpointVersion` | uint64 | the peer's endpoint version within the epoch | +| `Peers[].DataAddr` | string | the peer's data-path address | +| `Peers[].CtrlAddr` | string | the peer's control-path address | +| `Peers[].SessionID` | uint64 | the current recovery or shipping session; 0 when none | +| `Peers[].ProbeInFlight` | bool | a reachability probe of the peer is running | +| `Peers[].Closed` | bool | the peer handle was closed (it no longer ships) | + +### `GET /status/durable` + +Durable store state of the served volume. Go type `volume.durableStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `VolumeCount` | int | number of entries in Volumes | +| `Volumes[]` | object | the durable store state of the served volume | +| `Volumes[].VolumeID` | string | the volume | +| `Volumes[].Path` | string | its store path under --durable-root | +| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) | +| `Volumes[].ReplicaID` | string | the replica this store holds | +| `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment | +| `Volumes[].EndpointVersion` | uint64 | the endpoint version it is latched to | +| `Volumes[].Latched` | bool | an assignment latched the store (epoch and endpoint version set) | +| `Volumes[].Operational` | bool | the backend admits I/O now | +| `Volumes[].FrontierKnown` | bool | DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries | +| `Volumes[].DurableLSN` | uint64 | R: the newest LSN made durable | +| `Volumes[].RetainedLSN` | uint64 | S: the oldest LSN the WAL still retains | +| `Volumes[].HeadLSN` | uint64 | H: the newest LSN written | +| `Volumes[].Evidence` | string | why the backend is or is not operational | +| `Volumes[].Closed` | bool | the backend was closed | +| `Volumes[].WriteProfile` | object | write-path counters since start | +| `Volumes[].WriteProfile.DurabilityLatency` | object | latency distributions of writes, flushes and syncs | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend, by stage | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | end-to-end latency of writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal` | object | end-to-end latency of flushes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal` | object | end-to-end latency of forced-unit-access writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend` | object | from request receipt to the backend call | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch` | object | from backend completion to the acknowledgement sent | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal` | object | end-to-end latency of every request | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Writes` | uint64 | writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | flushes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | forced-unit-access writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | requests that completed with an error | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | latency of backend syncs | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | the WAL's own sync latency, where the store reports it (omitted when empty) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | WAL append latency | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait` | object | time a sync request waited in the group commit queue | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync` | object | physical file syncs (one sample per sync, however many waiters) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.TargetWriteOps` | uint64 | writes the protocol target handed to the volume | +| `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.TargetWriteDurationNanos` | uint64 | their total time at the target | +| `Volumes[].WriteProfile.BackendWriteRequestOps` | uint64 | write requests that entered the durable backend | +| `Volumes[].WriteProfile.BackendWriteRequestBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.BackendWriteOps` | uint64 | backend writes completed | +| `Volumes[].WriteProfile.BackendWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendStorageWriteCalls` | uint64 | single-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageWriteBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendStorageBatchCalls` | uint64 | batch-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchCalls` | uint64 | batch calls made only of whole blocks | +| `Volumes[].WriteProfile.BackendFullBlockBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchMax` | uint64 | the largest such batch, in blocks | +| `Volumes[].WriteProfile.WALCopyOps` | uint64 | WAL record payload copies | +| `Volumes[].WriteProfile.WALCopyBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALCopyDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALEncodeOps` | uint64 | WAL record encodes | +| `Volumes[].WriteProfile.WALEncodeBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALEncodeDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALChecksumOps` | uint64 | WAL record checksums | +| `Volumes[].WriteProfile.WALChecksumBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALChecksumDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendOps` | uint64 | WAL appends | +| `Volumes[].WriteProfile.WALAppendBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendLockWaitOps` | uint64 | appends that waited for the WAL append lock | +| `Volumes[].WriteProfile.WALAppendLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WriteCommitLockWaitOps` | uint64 | writes that waited for the commit lock | +| `Volumes[].WriteProfile.WriteCommitLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WALAppendWriteAtCalls` | uint64 | file WriteAt calls made by WAL appends | +| `Volumes[].WriteProfile.WALAppendWriteAtBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendWriteAtMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.WALAppendWrapCount` | uint64 | times the WAL append wrapped to the start of the log | +| `Volumes[].WriteProfile.WALAppendPaddingBytes` | uint64 | padding bytes written at those wraps | +| `Volumes[].WriteProfile.DirtyMapUpdateOps` | uint64 | dirty-map updates after writes | +| `Volumes[].WriteProfile.DirtyMapUpdateDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendSyncOps` | uint64 | backend syncs (flush, FUA, explicit sync) | +| `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | their total time | +| `Volumes[].DataSync` | object | data-file sync state, where the store has one (omitted when empty) | +| `Volumes[].DataSync.Mode` | string | the data-file sync call in use (fsync or fdatasync) | +| `Volumes[].DataSync.Reason` | string | why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) | +| `Volumes[].CheckpointPersistence` | object | checkpoint persistence state, where the store has one (omitted when empty) | +| `Volumes[].CheckpointPersistence.Successes` | uint64 | checkpoint calls that succeeded (including unchanged ones) | +| `Volumes[].CheckpointPersistence.Refusals` | uint64 | checkpoint calls refused because the map coverage was stale | +| `Volumes[].CheckpointPersistence.Failures` | uint64 | checkpoint calls that failed with an error | +| `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | the persisted checkpoint LSN | +| `Volumes[].CheckpointPersistence.Advances` | uint64 | successes that moved CheckpointLSN forward | +| `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | when the latest advance happened; zero if none in this open | +| `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | +| `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote | +| `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach | +| `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing | +| `Volumes[].Chunk.RemoteLSN` | uint64 | the LSN of the remote HEAD (what the remote holds durably) | +| `Volumes[].Chunk.Stats` | object | the layer's cut counters; zero until attached | +| `Volumes[].Chunk.Stats.Hydration` | object | lazy fetches of absent chunks from the remote | +| `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | fetch workers allowed (--chunk-hydration-workers) | +| `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | fetch queue capacity (--chunk-hydration-queue-depth) | +| `Volumes[].Chunk.Stats.Hydration.Active` | int | fetches running now | +| `Volumes[].Chunk.Stats.Hydration.Queued` | int | fetches waiting for a worker now | +| `Volumes[].Chunk.Stats.Hydration.WaitCalls` | uint64 | reads that waited for a chunk to arrive | +| `Volumes[].Chunk.Stats.Hydration.Joined` | uint64 | of those, reads that joined a fetch already running | +| `Volumes[].Chunk.Stats.Hydration.WaitRefusals` | uint64 | waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) | +| `Volumes[].Chunk.Stats.Hydration.Fetches` | uint64 | fetches started | +| `Volumes[].Chunk.Stats.Hydration.Completed` | uint64 | fetches that installed the chunk | +| `Volumes[].Chunk.Stats.Hydration.FetchErrors` | uint64 | fetches that failed | +| `Volumes[].Chunk.Stats.CutsOK` | uint64 | cuts that installed a HEAD | +| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | +| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | +| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | +| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload | +| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | +| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | +| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | +| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation) | +| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile | +| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far | +| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare | +| `Volumes[].Chunk.Stats.LastCut` | object | the last successful cut's measurements | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases` | object | the parts of SyncNs (never added to it) | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.lifecycleWaitNs` | int64 | waiting for the store's lifecycle lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion | +| `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.PayloadNs` | int64 | disjoint streaming/copy/upload wall intervals | +| `Volumes[].Chunk.Stats.LastCut.COWWALReadAttempts` | uint64 | Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWLocalReadNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSavedChunks` | int | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSaveNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWWaitNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.BarrierPauseNs` | int64 | BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.LockWaitNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.DrainNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASWriteNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.HeadReadbackNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.SyncNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CopyNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CandidateChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedBytes` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.ZeroedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UnchangedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASResult` | string | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | +| `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | +| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | +| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | +| `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | +| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | +| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | + +### `GET /status/recovery` + +The engine's replica projection (only with recovery enabled). Go type `engine.ReplicaProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `Mode` | Mode (string) | the engine mode (idle, recovering, healthy, degraded) | +| `RecoveryDecision` | RecoveryDecision (string) | the recovery class the R/S/H boundaries call for | +| `SessionKind` | SessionKind (string) | the kind of the current recovery session, if any | +| `SessionPhase` | SessionPhase (string) | its phase | +| `Epoch` | uint64 | the authority epoch | +| `EndpointVersion` | uint64 | the endpoint version within the epoch | +| `R` | uint64 | the replica's durable boundary (LSN) | +| `S` | uint64 | the primary's recoverable start boundary (WAL tail LSN) | +| `H` | uint64 | the primary's target boundary (head LSN) | +| `Reason` | string | why the engine is in this mode or decision | + +### `GET /status/chunk` + +Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint). Go type `chunkstore.VolumeUsage`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the volume | +| `chunkBytes` | uint64 | one full chunk | +| `liveChunks` | int | chunks HEAD references | +| `liveBytes` | uint64 | their bytes (the last chunk clipped) | +| `snapshots[]` | object | one entry per live snapshot | +| `snapshots[].name` | string | the snapshot name | +| `snapshots[].createdNs` | int64 | when it was created (Unix ns) | +| `snapshots[].class` | string | its retention class | +| `snapshots[].pinned` | bool | retention never deletes it | +| `snapshots[].chunks` | int | chunks its manifest references | +| `snapshots[].exclusiveBytes` | uint64 | bytes no other holder references: what deleting it makes eligible for GC | +| `manifestBindings` | int | stored chunk-key bindings some manifest references | +| `manifestBytes` | uint64 | their exact bytes | +| `storedBindings` | int | all chunk-key bindings in the filer, referenced or not | +| `storedBytes` | uint64 | their bytes; unreferenced ones counted at full chunk size | +| `storedUpperBound` | bool | StoredBytes is an upper bound (some bindings are unreferenced) | +| `policy` | object | the snapshot retention policy in force | +| `policy.keepNewest` | int | keep the newest N unpinned snapshots | +| `policy.keepYoungerNs` | int64 | keep every snapshot younger than this (ns) | +| `policy.keepHourly` | int | keep the newest snapshot of each of the last N hours | +| `policy.keepDaily` | int | keep the newest snapshot of each of the last N days | +| `policy.keepWeekly` | int | keep the newest snapshot of each of the last N weeks | +| `policySet` | bool | the volume set its own policy (else the default applies) | + +### `GET /status/nvme` + +NVMe/TCP frontend counters. Go type `volume.NVMeStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `stats` | object | the NVMe/TCP target's counters since start | +| `stats.sessions_accepted` | uint64 | TCP sessions accepted | +| `stats.admin_connects` | uint64 | admin-queue Connect commands | +| `stats.io_connects` | uint64 | I/O-queue Connect commands | +| `stats.read_commands` | uint64 | Read commands received | +| `stats.write_commands` | uint64 | Write commands received | +| `stats.flush_commands` | uint64 | Flush commands received | +| `stats.inline_write_commands` | uint64 | writes whose data came inline in the command capsule | +| `stats.inline_write_bytes` | uint64 | their data bytes | +| `stats.r2t_write_commands` | uint64 | writes whose data the target requested with R2T | +| `stats.r2t_write_bytes` | uint64 | their data bytes | +| `stats.h2c_data_pdus` | uint64 | host-to-controller data PDUs received | +| `stats.h2c_data_bytes` | uint64 | their bytes | +| `stats.c2h_data_pdus` | uint64 | controller-to-host data PDUs sent (read data) | +| `stats.c2h_data_bytes` | uint64 | their bytes | +| `stats.write_capsule_receive_parse_ops` | uint64 | Write phase attribution: for each phase, the operations timed and their total nanoseconds (overlapping phases can overlap in time). | +| `stats.write_capsule_receive_parse_ns` | uint64 | total nanoseconds of those operations | +| `stats.r2t_data_collection_ops` | uint64 | R2T data collections (R2T send to the last H2CData) | +| `stats.r2t_data_collection_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_dispatch_wait_ops` | uint64 | waits for a write handler to take the command | +| `stats.write_dispatch_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_handler_ops` | uint64 | write handler runs (the backend write) | +| `stats.write_handler_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_queue_wait_ops` | uint64 | waits of a completion for the send queue | +| `stats.write_completion_queue_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_send_ops` | uint64 | completion sends to the host | +| `stats.write_completion_send_ns` | uint64 | total nanoseconds of those operations | + +### `GET /status/ublk` + +Ublk frontend counters. Go type `volume.UblkStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `stats` | object | the ublk device's request counters since start | +| `stats.read_requests` | uint64 | read requests received | +| `stats.write_requests` | uint64 | write requests received | +| `stats.flush_requests` | uint64 | flush requests received | +| `stats.fua_writes` | uint64 | writes with forced unit access | +| `stats.other_requests` | uint64 | requests of any other operation | +| `stats.errors` | uint64 | requests completed with a negative result | + +### `GET /status/frontend-capabilities` + +The frontends this host can serve. Go type `volume.FrontendCapabilitiesStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `hostCapabilityIsProductClaim` | bool | always false: host facts, not a supported-product claim | +| `frontendTransports[]` | object | one entry per protocol and transport | +| `frontendTransports[].protocol` | string | the block protocol (iscsi, nvme, ublk) | +| `frontendTransports[].transport` | string | its transport (tcp, rdma, local) | +| `frontendTransports[].supported` | bool | this build and host can serve it | +| `frontendTransports[].listenerImplemented` | bool | a listener exists for it in this binary | +| `frontendTransports[].listenerStarted` | bool | the listener is running now | +| `frontendTransports[].startAllowed` | bool | the preflight checks allow starting it | +| `frontendTransports[].startReason` | string | why it may or may not start (omitted when empty) | +| `frontendTransports[].reason` | string | why it is or is not supported | +| `frontendTransports[].preflight[]` | object | the host facts checked for it (omitted when empty) | +| `frontendTransports[].preflight[].name` | string | the host fact checked (a module, device or privilege) | +| `frontendTransports[].preflight[].available` | bool | the fact holds on this host | +| `frontendTransports[].preflight[].reason` | string | why it holds or not | +| `frontendTransports[].preflight[].detail` | string | extra detail, such as the path probed (omitted when empty) | + + 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