Merge branch 'main' into ci/failure-bundle-ae

Conflict in the test workflow: main added the self-hosted runner NVMe
check after checkout; this branch adds the load-evidence start and its
self-test there. Both kept, the NVMe check first so a misplaced runner
stops before anything else runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 23:40:50 -08:00
commit af7ee03fe4
73 files changed
+6202 -1347

No files matched your search

+4 -1
View File
@@ -61,7 +61,10 @@ TestSnapshotLadderB1SnapshotQuery
TestSnapshotLadderC1FullRestore
TestSnapshotLadderC2IncrementalRestore
TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt
TestSnapshotLadderC3KilledHydrating
# A first write after the holder reports its frontend ready can be answered
# namespace-not-ready for longer than a host retries (#905, a v1.1 release
# gate); it runs and is reported on every job until the fix removes this.
TestSnapshotLadderC3KilledHydrating # nongating=#905
TestSnapshotLadderD1DeleteTheNewest
TestSnapshotLadderD2DeleteAMiddleOne
TestSnapshotLadderD3DeleteWhenContentRecurs
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# Tests require-nvme.sh with df and lsblk replaced by stubs on PATH.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
t=$(mktemp -d)
trap 'rm -rf "$t"' EXIT
mkdir -p "$t/bin" "$t/nvme" "$t/sata" "$t/mem" "$t/raid" "$t/share" "$t/half"
# df --output=source,fstype DIR: the stub answers by the directory's name.
cat >"$t/bin/df" <<STUB
#!/usr/bin/env bash
printf 'Filesystem Type\n'
case "\$2" in
$t/nvme*) echo '/dev/nvme0n1p1 ext4' ;;
$t/mem*) echo 'shm tmpfs' ;;
$t/raid*) echo '/dev/md0 ext4' ;;
$t/share*) echo '//nas/work cifs' ;;
$t/half*) echo '/dev/nvme1n1p1 ext4' ;;
*) echo '/dev/sda2 ext4' ;;
esac
STUB
# lsblk -nrso TYPE,TRAN SOURCE: the source and the devices under it.
cat >"$t/bin/lsblk" <<'STUB'
#!/usr/bin/env bash
case "$3" in
/dev/nvme0n1p1) printf 'part \ndisk nvme\n' ;;
/dev/sda2) printf 'part \ndisk sata\n' ;;
/dev/md0) printf 'raid1 \npart \ndisk nvme\npart \ndisk sata\n' ;;
/dev/nvme1n1p1) printf 'part \ndisk nvme\n'; echo "lsblk: read error" >&2; exit 32 ;;
*) echo "lsblk: $3: not a block device" >&2; exit 32 ;;
esac
STUB
chmod +x "$t/bin/df" "$t/bin/lsblk"
run() { PATH="$t/bin:$PATH" RUNNER_NAME=r1 bash "$here/require-nvme.sh" "$@" >"$t/out" 2>&1; }
fail() { echo "FAIL: $*"; cat "$t/out"; exit 1; }
run "$t/nvme" "$t/mem" "" || fail "nvme + tmpfs (any source name) + empty arg must pass"
run "$t/nvme/not/made/yet" || fail "a missing dir is judged by its nearest existing parent"
! run "$t/nvme" "$t/sata" || fail "a SATA dir must fail"
grep -q "runner r1" "$t/out" || fail "the failure must name the runner"
grep -q "FAIL $t/sata" "$t/out" || fail "the failure must name the directory"
! run "$t/raid" || fail "an array with a SATA member must fail"
! run "$t/share" || fail "a network share must fail"
grep -q "not a block device" "$t/out" || fail "a network share must say why"
! run "$t/half" || fail "an lsblk error after partial NVMe output must fail"
echo "require-nvme tests: ok"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Fails a self-hosted job whose workspace, temp or Go cache directory is not
# on an NVMe disk. The process-level tests write and fsync real files; on a
# box whose system disk is SATA, a default runner install puts _work there and
# the tests time out under the disk load instead of failing on a real bug.
# A tmpfs directory is accepted (memory, not a slow disk).
# Usage: require-nvme.sh DIR...
set -euo pipefail
bad=0
for p in "$@"; do
[ -n "$p" ] || continue
d=$p
while [ ! -e "$d" ]; do d=$(dirname "$d"); done
read -r src fstype < <(df --output=source,fstype "$d" | tail -n 1)
if [ "$fstype" = tmpfs ]; then
echo "ok $p: $src (tmpfs)"
continue
fi
# Every disk under the source (all members of an array) must be NVMe; an
# lsblk error voids whatever it printed.
disks=
if tree=$(lsblk -nrso TYPE,TRAN "$src" 2>/dev/null); then
disks=$(printf '%s\n' "$tree" |
awk '$1 == "disk" { print ($2 == "" ? "unknown" : $2) }' | sort -u | tr '\n' ' ')
fi
if [ "$disks" = "nvme " ]; then
echo "ok $p: $src (nvme)"
else
echo "FAIL $p: $src (disk: ${disks:-not a block device})"
bad=1
fi
done
if [ "$bad" -ne 0 ]; then
echo "runner ${RUNNER_NAME:-?}: work, temp and Go cache directories must be on NVMe; move them before this runner takes jobs" >&2
exit 1
fi
+9
View File
@@ -27,6 +27,15 @@ jobs:
with:
persist-credentials: false
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
+9
View File
@@ -55,6 +55,15 @@ jobs:
# step can see which packages the PR touches.
fetch-depth: 2
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Start whole-job load evidence
# Begins after checkout, before toolchain setup/build/tests. No host
# installation or privileged reads. A job-sized lifetime also bounds
@@ -11,11 +11,15 @@ import (
"testing"
)
// The node registry (server id -> registered host) is static after start:
// the identity checks (the registered-host refusal beside the certificate
// identity) assume no one rewrites it while blockmaster serves. Its only
// writer is the cluster-spec import at start-up. This guard fails when a
// new non-test caller of RegisterNode or RemoveNode appears anywhere.
// The node registry (server id -> registered host) only ever loses entries
// after start: the identity checks (the registered-host refusal beside the
// certificate identity) assume no one adds or rebinds a server id while
// blockmaster serves. Its only adder is the cluster-spec import at start-up.
// Its one remover after start is the operator's host retire, which takes
// only a host that holds no volume: a retired id is then unregistered, so a
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
// only get stricter. This guard fails when any other non-test caller of
// RegisterNode or RemoveNode appears anywhere.
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
@@ -64,8 +68,8 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
t.Fatal(err)
}
sort.Strings(sites)
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode"}
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
if strings.Join(sites, ",") != strings.Join(want, ",") {
t.Fatalf("node registry writers = %v, want only %v: a writer after start breaks the static-registry assumption of the identity checks", sites, want)
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
}
}
@@ -507,9 +507,10 @@ var handoffPorts struct {
}
// handoffAddress returns a free loopback address in 10000-19999: below the
// kernel's ephemeral range (32768 and up on Linux), where an outgoing
// connection can take a port while a restarted daemon waits to bind it
// again, and below the 20000-49999 range startWorkspaceWeed draws from.
// kernel's ephemeral range (32768 and up on Linux; the range is cut at the
// host's own ephemeral low end when that is lower: handoffRange), where an
// outgoing connection can take a port while a restarted daemon waits to bind
// it again, and below the 20000-49999 range startWorkspaceWeed draws from.
func handoffAddress(t *testing.T) string {
t.Helper()
handoffPorts.Lock()
@@ -517,8 +518,13 @@ func handoffAddress(t *testing.T) string {
if handoffPorts.used == nil {
handoffPorts.used = map[int]bool{}
}
eph, _ := ephemeralPorts()
rlo, rhi, ok := handoffRange(eph)
if !ok {
t.Fatalf("no handoff port range below this host's ephemeral range (from %d)", eph)
}
for i := 0; i < 500; i++ {
lo, hi := testPortSpan(10000, 20000)
lo, hi := testPortSpan(rlo, rhi)
p := lo + rand.Intn(hi-lo)
if handoffPorts.used[p] || !claimHostPort(p) {
continue
@@ -260,15 +260,77 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
// f1Up starts the blockvolume of key and waits for its volume to be primary
// and its frontend ready.
//
// A harness-chosen port can be taken between handoffAddress's free check and
// the holder's bind. When the holder exits before adopting with "address
// already in use", its four ports are drawn again and it starts once more
// (startWithBindRetry). v1's ports are the harness's own and named in the
// cluster spec, so v1 is not retried.
func f1Up(t *testing.T, env *handoffEnv, key string) *daemon {
t.Helper()
var d *daemon
start := func(attempt int) error {
b := env.hosts[key]
name := "blockvolume-" + key
if attempt > 1 {
name = fmt.Sprintf("%s-attempt%d", name, attempt) // its own log: the first attempt's stays whole
}
d = env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
return f1WaitAdopted(d, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica),
[]string{b.data, b.ctrl, b.status, b.nvme})
}
fresh := func() {
b := env.hosts[key]
b.data, b.ctrl, b.status, b.nvme = handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
env.hosts[key] = b
}
var first, err error
if key == "v1" {
err = start(1)
} else {
first, err = startWithBindRetry(start, fresh)
}
if first != nil {
t.Logf("%s: started again on new ports after its first attempt lost a drawn port: %v", key, first)
}
if err != nil {
t.Fatal(err)
}
b := env.hosts[key]
d := env.h.start(t, "blockvolume-"+key, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica))
poll(t, 60*time.Second, key+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
return d
}
// f1WaitAdopted waits until d logs s. A holder that exits first because the
// bind of one of drawn (this attempt's own addresses) found it in use
// answers errBindTaken (wrapped, naming the address and the log's end);
// any other exit or the bound answers an error naming it.
func f1WaitAdopted(d *daemon, timeout time.Duration, s string, drawn []string) error {
end := time.Now().Add(timeout)
for {
if d.line(s) != "" {
return nil
}
select {
case <-d.done:
if d.line(s) != "" {
return nil
}
if data, err := os.ReadFile(d.log); err == nil {
if addr, ok := bindTakenOn(string(data), drawn); ok {
return fmt.Errorf("%s exited (%v) before logging %q: %w (%s; log %s); its log ends:\n%s", d.name, d.err, s, errBindTaken, addr, d.log, d.tail(40))
}
}
return fmt.Errorf("%s exited (%v) before logging %q; its log ends:\n%s", d.name, d.err, s, d.tail(40))
default:
}
if time.Now().After(end) {
return fmt.Errorf("%s did not log %q within %s; its log ends:\n%s", d.name, s, timeout, d.tail(40))
}
time.Sleep(100 * time.Millisecond)
}
}
// f1StartSources starts the N source volumes.
func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume {
t.Helper()
@@ -0,0 +1,143 @@
package main_test
import (
"errors"
"regexp"
"strings"
"testing"
)
// handoffRange is the range [lo, hi) a harness-chosen daemon port is drawn
// from: [10000, 20000), cut at the host's ephemeral range when that starts
// lower, so an outgoing connection's source port cannot take a port between
// the free check and the daemon's bind. ok is false when nothing is left.
func handoffRange(ephemeralLo int) (lo, hi int, ok bool) {
lo, hi = 10000, 20000
if ephemeralLo < hi {
hi = ephemeralLo
}
return lo, hi, hi > lo
}
// errBindTaken is a start that failed because one of the addresses the
// harness drew for it was taken before the daemon bound it.
var errBindTaken = errors.New("a harness-chosen port was taken before the daemon bound it")
// bindTakenRe is Go's net error for a listener whose bind found the address
// in use, ending its log line: "listen tcp <addr>: bind: address already in
// use". A dial, a quoted copy inside other text, or anything after it on the
// line does not match.
var bindTakenRe = regexp.MustCompile(`(?:^|[\s:])listen tcp (\S+): bind: address already in use$`)
// bindTakenOn reports the drawn address whose listener bind failed with
// EADDRINUSE in log, if any: only an exact listener-bind error, and only on
// one of drawn (this attempt's own addresses). Anything else is not a taken
// port, so the caller fails as it would without a retry.
func bindTakenOn(log string, drawn []string) (string, bool) {
for _, l := range strings.Split(log, "\n") {
m := bindTakenRe.FindStringSubmatch(strings.TrimRight(l, "\r"))
if m == nil {
continue
}
for _, a := range drawn {
if m[1] == a {
return a, true
}
}
}
return "", false
}
// startWithBindRetry starts a daemon and waits for it; when the start
// reports errBindTaken, it asks for fresh ports and starts once more. first
// is the first attempt's error when it was retried (kept for the report);
// err is the answer that stands. Any other answer, and a second
// errBindTaken, is returned as it is.
func startWithBindRetry(start func(attempt int) error, freshPorts func()) (first, err error) {
err = start(1)
if !errors.Is(err, errBindTaken) {
return nil, err
}
first = err
freshPorts()
return first, start(2)
}
func TestHandoffRangeStaysBelowTheEphemeralRange(t *testing.T) {
for _, c := range []struct {
eph, lo, hi int
ok bool
}{
{32768, 10000, 20000, true}, // the Linux default: the whole range
{20000, 10000, 20000, true},
{15000, 10000, 15000, true}, // a host whose ephemeral range starts low: cut there
{10001, 10000, 10001, true},
{10000, 10000, 10000, false}, // nothing left
{1024, 10000, 1024, false},
} {
lo, hi, ok := handoffRange(c.eph)
if lo != c.lo || hi != c.hi || ok != c.ok {
t.Fatalf("ephemeral from %d: [%d, %d) ok=%v; want [%d, %d) ok=%v", c.eph, lo, hi, ok, c.lo, c.hi, c.ok)
}
}
}
func TestBindTakenOnOnlyThisAttemptsListener(t *testing.T) {
drawn := []string{"127.0.0.1:11230", "127.0.0.1:11231", "127.0.0.1:11232", "127.0.0.1:11233"}
for _, c := range []struct {
name, log string
addr string
taken bool
}{
{"a drawn listener's bind", "2026/12/02 05:01:02 blockvolume: status listener: listen tcp 127.0.0.1:11230: bind: address already in use", "127.0.0.1:11230", true},
{"the bare net error", "listen tcp 127.0.0.1:11233: bind: address already in use", "127.0.0.1:11233", true},
{"a CRLF line", "listen tcp 127.0.0.1:11231: bind: address already in use\r", "127.0.0.1:11231", true},
{"another port", "listen tcp 127.0.0.1:11299: bind: address already in use", "", false},
{"another host, same port", "listen tcp 0.0.0.0:11230: bind: address already in use", "", false},
{"a dial", "dial tcp 127.0.0.1:11230: connect: address already in use", "", false},
{"quoted inside other text", `retry: err="listen tcp 127.0.0.1:11230: bind: address already in use"`, "", false},
{"more after it", "listen tcp 127.0.0.1:11230: bind: address already in use; retrying", "", false},
{"the words alone", "address already in use", "", false},
{"udp", "listen udp 127.0.0.1:11230: bind: address already in use", "", false},
{"nothing", "blockvolume: volume v2 adopted as PRIMARY at r2@1", "", false},
} {
addr, taken := bindTakenOn("first line\n"+c.log+"\nlast line", drawn)
if addr != c.addr || taken != c.taken {
t.Fatalf("%s: (%q, %v); want (%q, %v)", c.name, addr, taken, c.addr, c.taken)
}
}
}
func TestStartWithBindRetry(t *testing.T) {
other := errors.New("exited before logging adoption")
taken := func(n int) error { return errors.Join(errBindTaken, errors.New("attempt "+string(rune('0'+n)))) }
for _, c := range []struct {
name string
answers []error
first bool
want error
attempts []int
freshCnt int
}{
{"ok at once", []error{nil}, false, nil, []int{1}, 0},
{"another failure is not retried", []error{other}, false, other, []int{1}, 0},
{"a taken port, then ok", []error{taken(1), nil}, true, nil, []int{1, 2}, 1},
{"a taken port twice: the second answer stands", []error{taken(1), taken(2)}, true, errBindTaken, []int{1, 2}, 1},
{"a taken port, then another failure", []error{taken(1), other}, true, other, []int{1, 2}, 1},
} {
var attempts []int
fresh := 0
first, err := startWithBindRetry(func(a int) error { attempts = append(attempts, a); return c.answers[a-1] }, func() { fresh++ })
if (first != nil) != c.first || (c.first && !errors.Is(first, errBindTaken)) {
t.Fatalf("%s: first=%v", c.name, first)
}
if !errors.Is(err, c.want) || (c.want == nil && err != nil) || fresh != c.freshCnt || len(attempts) != len(c.attempts) {
t.Fatalf("%s: err=%v attempts=%v fresh=%d", c.name, err, attempts, fresh)
}
for i, a := range c.attempts {
if attempts[i] != a {
t.Fatalf("%s: attempts %v, want %v", c.name, attempts, c.attempts)
}
}
}
}
@@ -0,0 +1,114 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// clusterLifecycleDial opens the master's lifecycle service; a test
// replaces it.
var clusterLifecycleDial = func(addr string) (control.LifecycleServiceClient, func() error, error) {
conn, err := link.DialMasterFromEnv(addr)
if err != nil {
return nil, nil, err
}
return control.NewLifecycleServiceClient(conn), conn.Close, nil
}
// runCluster is "sw-block cluster finalize-format|retire-host".
func runCluster(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprintln(stderr, "sw-block: expected subcommand cluster finalize-format|retire-host")
return ops.VolumeStatusExitInvalid
}
switch args[0] {
case "finalize-format":
return runClusterFinalizeFormat(args[1:], stdout, stderr)
case "retire-host":
return runClusterRetireHost(args[1:], stdout, stderr)
}
fmt.Fprintf(stderr, "sw-block: unknown subcommand cluster %q\n", args[0])
return ops.VolumeStatusExitInvalid
}
// runClusterFinalizeFormat raises the cluster's format level to 1. Going
// back to v1.0.x works only before it: afterwards a v1.0.x master or holder
// refuses the store (an expected refusal, not damage). The master refuses
// it while any registered host does not read level 1, naming each one.
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s]")
return ops.VolumeStatusExitInvalid
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", err)
return ops.VolumeStatusExitUnhealthy
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
resp, err := c.FinalizeFormat(ctx, &control.FinalizeFormatRequest{Level: 1}, grpc.WaitForReady(false))
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", status.Convert(err).Message())
return clusterExit(err)
}
if resp.GetAlready() {
fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel())
return ops.VolumeStatusExitOK
}
fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel())
return ops.VolumeStatusExitOK
}
// runClusterRetireHost removes a registered host from the node inventory.
// The master refuses it while the host holds a lease or an assignment.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
server := fs.String("server", "", "the server id to retire (required)")
confirm := fs.String("confirm", "", "the same server id again (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s]")
return ops.VolumeStatusExitInvalid
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", err)
return ops.VolumeStatusExitUnhealthy
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", status.Convert(err).Message())
return clusterExit(err)
}
fmt.Fprintf(stdout, "host %s retired\n", *server)
return ops.VolumeStatusExitOK
}
// clusterExit maps a master error to the CLI's exit codes: a malformed
// request is 2 (as a usage error); a refusal or an unreachable master is 1.
func clusterExit(err error) int {
if status.Code(err) == codes.InvalidArgument {
return ops.VolumeStatusExitInvalid
}
return ops.VolumeStatusExitUnhealthy
}
@@ -0,0 +1,94 @@
package main
import (
"bytes"
"context"
"strings"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type fakeClusterMaster struct {
control.LifecycleServiceClient
finalize func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error)
retire func(*control.RetireHostRequest) (*control.RetireHostResponse, error)
}
func (f *fakeClusterMaster) FinalizeFormat(_ context.Context, r *control.FinalizeFormatRequest, _ ...grpc.CallOption) (*control.FinalizeFormatResponse, error) {
return f.finalize(r)
}
func (f *fakeClusterMaster) RetireHost(_ context.Context, r *control.RetireHostRequest, _ ...grpc.CallOption) (*control.RetireHostResponse, error) {
return f.retire(r)
}
func withClusterMaster(t *testing.T, f *fakeClusterMaster) {
t.Helper()
saved := clusterLifecycleDial
t.Cleanup(func() { clusterLifecycleDial = saved })
clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) {
return f, func() error { return nil }, nil
}
}
// finalize-format asks level 1; a refusal names the old hosts and exits 1,
// a finalize and an already-finalized cluster exit 0, a malformed command 2.
func TestClusterFinalizeFormat(t *testing.T) {
refuse := true
f := &fakeClusterMaster{finalize: func(r *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
if r.GetLevel() != 1 {
t.Errorf("finalize asked level %d", r.GetLevel())
}
if refuse {
return nil, status.Error(codes.FailedPrecondition, "format finalize refused: registered hosts do not read format level 1: node-b (no report)")
}
return &control.FinalizeFormatResponse{FormatLevel: 1}, nil
}}
withClusterMaster(t, f)
var out, errOut bytes.Buffer
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "node-b (no report)") {
t.Fatalf("refused finalize: exit %d, stderr %q", code, errOut.String())
}
refuse = false
out.Reset()
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "format level 1 finalized") {
t.Fatalf("finalize: exit %d, stdout %q", code, out.String())
}
f.finalize = func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return &control.FinalizeFormatResponse{FormatLevel: 1, Already: true}, nil
}
out.Reset()
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "already finalized") {
t.Fatalf("already finalized: exit %d, stdout %q", code, out.String())
}
if code := run([]string{"cluster", "finalize-format"}, &out, &errOut); code != 2 {
t.Fatalf("finalize without --master: exit %d, want 2", code)
}
}
// retire-host sends the server id and its confirm; a refusal exits 1.
func TestClusterRetireHost(t *testing.T) {
var got *control.RetireHostRequest
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
got = r
if r.GetServerId() == "busy" {
return nil, status.Error(codes.FailedPrecondition, `retire refused: host "busy" holds a lease or an assignment for volumes v1; move them first`)
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
withClusterMaster(t, f)
var out, errOut bytes.Buffer
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") {
t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 2 {
t.Fatalf("retire without --confirm: exit %d, want 2", code)
}
}
+3
View File
@@ -102,6 +102,9 @@ func run(args []string, stdout, stderr io.Writer) int {
if args[0] == "shell" {
return runShell(args[1:], os.Stdin, stdout, stderr)
}
if args[0] == "cluster" {
return runCluster(args[1:], stdout, stderr)
}
if args[0] != "ops" {
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
usage(stderr)
+13
View File
@@ -185,6 +185,16 @@ type Publisher struct {
leaseMu sync.Mutex
leaseViews map[string]*leaseView
// formatLevel is the cluster's format level (workspace_lease_v100.go):
// 0 keeps v1.0's master semantics (a current lease horizon, version-1
// records), 1 is v1.1's. Written under mu and leaseMu, read under
// either.
formatLevel uint32
// Level 0's horizon extender (workspace_lease_v100.go).
leaseClosing bool // guarded by mu and leaseMu
extWG sync.WaitGroup // admitted extenders
extendFailures map[string]int // guarded by mu
// testAfterIssuePublish, when set by a test, runs under mu right after
// an issued move's lease view is published.
testAfterIssuePublish func(volume string)
@@ -259,6 +269,8 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
workspaceNow: time.Now,
workspaceTTL: 30 * time.Second,
leaseViews: map[string]*leaseView{},
formatLevel: 1,
extendFailures: map[string]int{},
}
for _, opt := range opts {
if opt != nil {
@@ -713,6 +725,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
if issuedWorkspace != nil {
record.Workspace = cloneWorkspace(issuedWorkspace)
}
record.EnvelopeVersion = p.envelopeVersionLocked()
if err := p.store.Put(record); err != nil {
// State mutation hasn't happened yet; nothing to
// unwind. Just report the failure.
@@ -39,6 +39,11 @@ import (
// lease time gates serving and forced moves; it never erases the last authored
// line. Only Publisher can mint its replacement.
type DurableRecord struct {
// EnvelopeVersion is the envelope version the store writes the record
// in (0: storeEnvelopeVersion). Not part of the body or its checksum: a
// master at format level 0 writes version 1, the one a v1.0.x master
// reads.
EnvelopeVersion int `json:"-"`
VolumeID string
ReplicaID string
Epoch uint64
@@ -150,8 +155,12 @@ func computeChecksum(r DurableRecord) string {
// encodeEnvelope serializes a record + checksum into the on-disk
// JSON envelope format.
func encodeEnvelope(r DurableRecord) ([]byte, error) {
version := r.EnvelopeVersion
if version == 0 {
version = storeEnvelopeVersion
}
env := storeEnvelope{
Version: storeEnvelopeVersion,
Version: version,
Body: r,
Checksum: computeChecksum(r),
}
+7 -1
View File
@@ -336,7 +336,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking {
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
}
if p.deadlineValidity(p.leaseDeadlineLocked(volume), s.Lease.MaxClockSkewNS, p.workspaceNow()) == 0 {
if p.ackValidityLocked(volume, s.Lease) == 0 {
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
}
s.Ack = &ack
@@ -405,6 +405,7 @@ func (p *Publisher) persistWorkspaceTimedLocked(volume string, s *WorkspaceState
i := line.info
record := DurableRecord{VolumeID: volume, ReplicaID: i.ReplicaID, Epoch: i.Epoch, EndpointVersion: i.EndpointVersion, DataAddr: i.DataAddr, CtrlAddr: i.CtrlAddr,
WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s), Incarnation: i.Incarnation}
record.EnvelopeVersion = p.envelopeVersionLocked()
start := time.Now()
err = p.store.Put(record)
write = time.Since(start)
@@ -482,6 +483,11 @@ func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease
skew := p.workspaceSkew(lease)
deadline := p.leaseDeadlineLocked(volume)
lostUntil = deadline.Add(skew).UnixNano()
if p.formatLevel == 0 {
// Level 0 keeps v1.0's barrier: the later of the persisted horizon
// and the deadline, each plus skew.
return p.forcedMoveBarrierV100Locked(lease, deadline, skew, now)
}
if now.Before(deadline.Add(skew)) {
return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
}
@@ -17,12 +17,17 @@ func TestDeletionReservationGuardSites(t *testing.T) {
"applyWithWorkspaceMove": true, "MoveWorkspace": true,
"RenewWorkspaceLease": true, "firstWorkspaceGrant": true,
"regrantWorkspaceLease": true,
// Format level 0's horizon extender rechecks the reservation.
"extendWorkspaceLease": true,
}
boundSites := map[string]bool{
"publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true,
"RenewWorkspaceLease": true, "regrantWorkspaceLease": true,
// Reply-only copies never increase published validity.
"WorkspaceLeaseReply": true,
"WorkspaceLeaseReply": true, "ackValidityLocked": true,
// Format level 0 (v1.0's semantics): the clamped grant and the
// horizon extender, which raises the persisted horizon only.
"renewV100Locked": true, "extendWorkspaceLease": true,
// Copies the persisted lease into the leaf view under mu -> leaseMu.
"deriveLeaseLocked": true,
// Positive lease construction and publication, or a plain clone.
@@ -0,0 +1,200 @@
package authority
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
// level0Publisher is a publisher at format level 0 over store, joining its
// extenders on cleanup before the store closes.
func level0Publisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher {
t.Helper()
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now), WithWorkspaceMaxClockSkew(4*time.Second), WithFormatLevel(0))
t.Cleanup(p.CloseWorkspaceExtenders)
return p
}
// awaitHorizon waits (bounded) until v's persisted horizon is want: an
// admitted extender writes it in the background.
func awaitHorizon(t *testing.T, p *Publisher, v string, want time.Time) {
t.Helper()
for end := time.Now().Add(5 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) {
if st := p.WorkspaceState(v); st != nil && st.Lease != nil && st.Lease.ExpiresAtNS == want.UnixNano() {
return
}
}
st := p.WorkspaceState(v)
t.Fatalf("the horizon of %s stayed %d, want %d", v, st.Lease.ExpiresAtNS, want.UnixNano())
}
// recordVersion is the envelope version of v's record on disk.
func recordVersion(t *testing.T, dir, v string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join(dir, v+".v3auth.json"))
if err != nil {
t.Fatal(err)
}
switch {
case bytes.HasPrefix(b, []byte(`{"v":1,`)):
return "1"
case bytes.HasPrefix(b, []byte(`{"v":2,`)):
return "2"
}
return string(b[:min(len(b), 12)])
}
// At format level 0 the master's records are v1.0's (envelope version 1);
// after the finalize they are version 2 (FormatGateMaster: the one durable
// step; a v1.0.x master reads version 1 only).
func TestRecordEnvelopeVersionFollowsTheFormatLevel(t *testing.T) {
disk, dir := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
bindAndGrant(t, p, "v", "r")
if got := recordVersion(t, dir, "v"); got != "1" {
t.Fatalf("level 0 wrote record envelope version %s, want 1", got)
}
p.FinalizeFormatLevel()
if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
if got := recordVersion(t, dir, "v"); got != "2" {
t.Fatalf("level 1 wrote record envelope version %s, want 2", got)
}
}
// At format level 0 a renewal keeps the persisted horizon current (v1.0's
// extender writes trigger + 1.5 TTL once the horizon is less than 1.25 TTL
// ahead) and a grant never passes it; at level 1 a renewal writes nothing
// (FormatGateMaster level0_no_horizon: without it a v1.0.x master started
// on the store trusts a stale horizon).
func TestALevel0RenewalKeepsTheHorizonCurrent(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
bindAndGrant(t, p, "v", "r") // t=0: horizon 45
if h := p.WorkspaceState("v").Lease.ExpiresAtNS; h != c.sec(45).UnixNano() {
t.Fatalf("first grant's horizon %d, want t=45", h)
}
c.at(10) // horizon 45 < 10 + 37.5: an extension to 10 + 45 = 55
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || l.ExpiresAtNS != c.sec(40).UnixNano() {
t.Fatalf("renewal at t=10: %+v %v, want the grant t=40", l, err)
}
awaitHorizon(t, p, "v", c.sec(55))
// Level 1: the same renewal writes nothing.
disk1, _ := newTempStore(t)
c1 := newTestClock()
p1 := newLeasePublisher(t, disk1, 30*time.Second, c1)
bindAndGrant(t, p1, "v", "r")
c1.at(10)
if _, err := p1.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
p1.CloseWorkspaceExtenders()
if h := p1.WorkspaceState("v").Lease.ExpiresAtNS; h != c1.sec(45).UnixNano() {
t.Fatalf("level 1: a renewal changed the persisted lease to t=%v", time.Unix(0, h).Sub(c1.sec(0)))
}
}
// At format level 0 a grant is clamped to the persisted horizon.
func TestALevel0GrantIsClampedToTheHorizon(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
p.CloseWorkspaceExtenders() // no extension: the horizon stays t=45
bindAndGrant(t, p, "v", "r")
c.at(20)
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || l.ExpiresAtNS != c.sec(45).UnixNano() {
t.Fatalf("renewal at t=20 with horizon t=45: %+v %v, want the grant clamped to t=45", l, err)
}
}
// At format level 0 the forced-move barrier is v1.0's (the later of the
// horizon and the deadline, plus skew); after the finalize it is the
// deadline plus skew, and the deadline covers the last level-0 grant
// (condition 3: a forced move right after the finalize still waits for it).
func TestTheForcedBarrierFollowsTheFormatLevel(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
p.CloseWorkspaceExtenders() // horizon stays t=45
bindAndGrant(t, p, "v", "r") // deadline t=30, horizon t=45, skew 4
c.at(40)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("level 0: a forced move admitted at t=40, before the horizon t=45 plus skew")
}
c.at(48.9)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("level 0: a forced move admitted at t=48.9, before t=49")
}
p.FinalizeFormatLevel()
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err != nil {
t.Fatalf("level 1 at t=48.9, past the deadline t=30 plus skew: %v", err)
}
// The last level-0 grant at t=20 (deadline t=50): right after the
// finalize a forced move still waits for t=54. The first renewal at
// t=20 is clamped to the horizon t=45 and admits an extension to t=65;
// once it is written, the renewal at t=20 grants t=50.
disk2, _ := newTempStore(t)
c2 := newTestClock()
p2 := level0Publisher(t, disk2, 30*time.Second, c2)
bindAndGrant(t, p2, "v", "r")
c2.at(20)
if l, err := p2.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil || l.ExpiresAtNS != c2.sec(45).UnixNano() {
t.Fatalf("renewal at t=20 under horizon t=45: %+v %v, want t=45", l, err)
}
awaitHorizon(t, p2, "v", c2.sec(65))
if l, err := p2.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil || l.ExpiresAtNS != c2.sec(50).UnixNano() {
t.Fatalf("renewal at t=20 under horizon t=65: %+v %v, want t=50", l, err)
}
p2.FinalizeFormatLevel()
c2.at(53.9)
if err := p2.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("after the finalize a forced move was admitted before the last level-0 grant (t=50) plus skew")
}
c2.at(54)
if err := p2.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err != nil {
t.Fatalf("after the finalize at t=54 (level 0 would wait for the horizon t=65 plus skew): %v", err)
}
}
// A clamped level-0 grant raises the deadline with this process's monotonic
// reading, so the level-1 barrier after a finalize (with no renewal after
// it) cannot be moved by a wall-clock step.
func TestAClampedLevel0GrantKeepsTheMonotonicReading(t *testing.T) {
disk, _ := newTempStore(t)
base := time.Now() // monotonic
var offset atomic.Int64
clock := func() time.Time { return base.Add(time.Duration(offset.Load())) }
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, clock), WithWorkspaceMaxClockSkew(4*time.Second), WithFormatLevel(0))
p.CloseWorkspaceExtenders() // no extension: the horizon stays first grant + 45 s
bindAndGrant(t, p, "v", "r")
offset.Store(int64(20 * time.Second))
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil {
t.Fatal(err)
}
if want := base.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
t.Fatalf("renewal at +20 s: grant %d, want the horizon %d (clamped)", l.ExpiresAtNS, want)
}
p.FinalizeFormatLevel()
p.mu.Lock()
d := p.leaseDeadlineLocked("v")
p.mu.Unlock()
if !strings.Contains(d.String(), "m=") {
t.Fatalf("the clamped deadline %s has no monotonic reading: a wall-clock step after the finalize would move the barrier", d)
}
if !d.Equal(base.Add(45 * time.Second)) {
t.Fatalf("the clamped deadline %s, want base + 45 s", d)
}
}
@@ -0,0 +1,199 @@
package authority
import (
"fmt"
"log"
"time"
)
// The cluster format level (FORMAT-GATE). Until the operator finalizes the
// v1.1 format the master keeps v1.0's semantics, so a v1.0.x master started
// on its store is safe: renewals keep the persisted lease horizon current
// (a background extender writes it ahead, and a grant is clamped to it),
// the forced-move barrier is the later of that horizon and the grant
// deadline plus skew, and records are written in envelope version 1. The
// finalize raises the level to 1, v1.1's semantics, in one step.
// WithFormatLevel sets the publisher's starting format level (0 or 1; the
// default is 1). A master sets it from its store before it serves.
func WithFormatLevel(level uint32) PublisherOption {
return func(p *Publisher) {
if level <= 1 {
p.formatLevel = level
}
}
}
// SetFormatLevelBeforeServing sets the format level a master read from its
// store. It is called before anything is served (no renewal, write or
// move has run); afterwards only FinalizeFormatLevel changes the level.
func (p *Publisher) SetFormatLevelBeforeServing(level uint32) {
if level > 1 {
return
}
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatLevel = level
}
// FormatLevel is the publisher's format level.
func (p *Publisher) FormatLevel() uint32 {
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
return p.formatLevel
}
// FinalizeFormatLevel switches the publisher to level 1. The caller has
// already made the level durable. It flips under mu and leaseMu, so forced
// moves (mu) and renewals (leaseMu, which read the level, grant and raise
// the deadline in one section) see one level. Every lease's deadline was
// raised by every grant at level 0 as well, so the level-1 barrier
// (deadline plus skew) still covers every grant made before the switch. An
// extender already admitted finds level 1 and writes nothing.
func (p *Publisher) FinalizeFormatLevel() {
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatLevel = 1
}
// envelopeVersionLocked is the record envelope version the level writes:
// v1.0's (1) at level 0. Caller holds mu.
func (p *Publisher) envelopeVersionLocked() int {
if p.formatLevel == 0 {
return storeEnvelopeVersionV100
}
return storeEnvelopeVersion
}
// ackValidityLocked is the host validity a revocation ACK is judged by: at
// level 0 v1.0's (the granted deadline, never above the persisted horizon),
// at level 1 the deadline's. Caller holds mu.
func (p *Publisher) ackValidityLocked(volume string, lease *WorkspaceLease) time.Duration {
deadline := p.leaseDeadlineLocked(volume)
if p.formatLevel == 0 {
l := *lease
l.ExpiresAtNS = min(l.ExpiresAtNS, deadline.UnixNano())
return p.WorkspaceLeaseValidity(l)
}
return p.deadlineValidity(deadline, lease.MaxClockSkewNS, p.workspaceNow())
}
// forcedMoveBarrierV100Locked is v1.0's forced-move barrier: the later of
// the persisted horizon and the grant (or restart) deadline, each plus
// skew. The audit bound is in wall time; the admission keeps both
// predicates, the deadline's monotonic reading included. Caller holds mu.
func (p *Publisher) forcedMoveBarrierV100Locked(lease *WorkspaceLease, deadline time.Time, skew time.Duration, now time.Time) (int64, time.Time, error) {
lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano()
if d := deadline.Add(skew).UnixNano(); d > lostUntil {
lostUntil = d
}
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
}
// renewV100Locked is a level-0 renewal of a live lease, v1.0's: the grant
// is min(now+TTL, horizon), it raises the deadline, and once the horizon is
// less than 1.25 TTL ahead an extender is admitted to write it ahead. It
// releases leaseMu. Caller holds leaseMu and has checked the lease.
func (p *Publisher) renewV100Locked(volume, holder string, epoch uint64, lv *leaseView, now time.Time) (WorkspaceLease, error) {
grant := now.Add(p.workspaceTTL)
if h := time.Unix(0, lv.d.horizon); grant.After(h) {
// Clamped to the horizon, as the time left to it from now: the grant
// (and the deadline it raises, which the level-1 barrier reads after
// a finalize) keeps now's monotonic reading, so a wall-clock step
// cannot move it.
grant = now.Add(h.Sub(now))
}
// A grant without positive host validity would make the host fence on an
// invalid reply; refuse with an error instead.
if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 {
horizon := lv.d.horizon
p.leaseMu.Unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
}
if grant.After(lv.deadline) {
lv.deadline = grant
}
if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing {
lv.extending = true
p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders
go p.extendWorkspaceLease(volume, holder, epoch, now)
}
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS}
p.leaseMu.Unlock()
return l, nil
}
// extendWorkspaceLease is an ordinary writer: under mu it rechecks the
// lease (and that the level is still 0) and writes horizon H = trigger +
// 1.5 TTL through persistWorkspaceLocked, so its write and its publication
// are one mu section. A write error latches uncertainty
// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write.
func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) {
defer p.extWG.Done()
p.beforeWorkspaceGrantLock("extension")
var note string
defer func() {
if note != "" {
log.Print(note)
}
}()
p.mu.Lock()
defer p.mu.Unlock()
defer func() {
p.leaseMu.Lock()
if lv := p.leaseViews[volume]; lv != nil {
lv.extending = false
}
p.leaseMu.Unlock()
}()
if p.leaseClosing || p.formatLevel != 0 || p.deleteReserved[volume] {
return
}
_, line, ok := p.workspaceLineLocked(volume)
s := cloneWorkspace(p.workspace[volume])
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking ||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) ||
p.workspaceUncertain[volume] || p.store == nil {
return
}
h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano()
old := s.Lease.ExpiresAtNS
if h <= old {
return
}
s.Lease.ExpiresAtNS = h
write, _, err := p.persistWorkspaceTimedLocked(volume, s)
took := write.Round(time.Millisecond)
if err != nil {
if p.extendFailures[volume] == 0 {
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err)
}
p.extendFailures[volume]++
return
}
if n := p.extendFailures[volume]; n > 0 {
note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano))
delete(p.extendFailures, volume)
}
}
// CloseWorkspaceExtenders stops admitting lease extensions and joins every
// admitted extender. Owners call it before closing the authority store:
// closing is set under mu and leaseMu, so an extender either finished its
// write before or sees closing and does not write.
func (p *Publisher) CloseWorkspaceExtenders() {
p.mu.Lock()
p.leaseMu.Lock()
p.leaseClosing = true
p.leaseMu.Unlock()
p.mu.Unlock()
p.extWG.Wait()
}
@@ -37,8 +37,9 @@ type leaseDerived struct {
// restart+TTL; a barrier adds the skew bound to it) is owned by the view; d
// is derived.
type leaseView struct {
d leaseDerived
deadline time.Time
d leaseDerived
deadline time.Time
extending bool // format level 0: an extender of this volume's horizon is admitted
}
// deriveLeaseLocked computes the derived lease view from published state.
@@ -125,7 +126,16 @@ func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise boo
// deadline), never a persisted value. Without a deadline (a published lease
// always has one) it reports 0, which gives the host no validity: fail
// closed.
func (lv *leaseView) replyExpiryNS() int64 {
//
// At format level 0 it is v1.0's: the granted deadline, never above the
// persisted horizon (min(horizon, deadline)).
func (lv *leaseView) replyExpiryNS(level uint32) int64 {
if level == 0 {
if lv.deadline.IsZero() {
return lv.d.horizon
}
return min(lv.deadline.UnixNano(), lv.d.horizon)
}
if lv.deadline.IsZero() {
return 0
}
@@ -152,7 +162,7 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
return WorkspaceLease{}, false
}
l := lv.d.lease
l.ExpiresAtNS = lv.replyExpiryNS()
l.ExpiresAtNS = lv.replyExpiryNS(p.formatLevel)
return l, true
}
@@ -262,11 +272,11 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
}
if lv.d.revoking { // tell the host to drain; never extend
l := lv.d.lease
l.ExpiresAtNS = lv.replyExpiryNS()
l.ExpiresAtNS = lv.replyExpiryNS(p.formatLevel)
unlock()
return l, nil
}
if !now.Before(lv.deadline) {
if !now.Before(lv.deadline) || (p.formatLevel == 0 && now.UnixNano() >= lv.d.horizon) {
unlock()
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
}
@@ -276,6 +286,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
}
if p.formatLevel == 0 {
return p.renewV100Locked(volume, holder, epoch, lv, now) // releases leaseMu
}
// The grant stays a time.Time with its monotonic reading: the deadline
// it raises is what admission compares (this process's own clock); only
// the reply carries wall nanoseconds.
@@ -284,8 +297,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// bound, leaseFact) would make the host fence on an invalid reply and lose
// its remaining validity; refuse with an error instead.
if p.deadlineValidity(grant, lv.d.maxSkewNS, now) == 0 {
skew := lv.d.maxSkewNS // the view is leaseMu's: read it before the unlock
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(lv.d.maxSkewNS))
return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(skew))
}
if grant.After(lv.deadline) {
lv.deadline = grant
@@ -376,9 +390,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
// start; it never compares clocks.
skew := p.workspaceSkew(s.Lease)
retry := max(p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0)
if p.formatLevel == 0 {
retry = max(retry, time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).Sub(now))
}
return WorkspaceLease{}, &LeaseBarrierError{Until: now.Add(retry), RetryAfter: retry, err: err}
}
lease, grant := p.newWorkspaceLease(holder, epoch, now)
if p.formatLevel == 0 {
lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) // v1.0: the horizon never drops
}
lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease))
s.Lease = lease
if err := p.persistWorkspaceLocked(volume, s); err != nil {
@@ -15,6 +15,8 @@ import (
"reflect"
"runtime"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -32,6 +34,268 @@ func (b *noFlushBackend) Write(ctx context.Context, offset int64, data []byte) (
return n, err
}
// boundedRead runs get and waits for it no later than deadline: ok is false
// when the read is still blocked then (it may be waiting for a store lock that
// a stalled checkpoint publication holds); the read then finishes on its own.
func boundedRead(get func() uint64, deadline time.Time) (uint64, bool) {
got := make(chan uint64, 1)
go func() { got <- get() }()
t := time.NewTimer(time.Until(deadline))
defer t.Stop()
select {
case v := <-got:
return v, true
case <-t.C:
return 0, false
}
}
type passiveResult struct {
cp uint64 // the last checkpoint read
lastInCycle time.Time // the last moment a flusher cycle was in progress
blocked bool // a checkpoint read was still blocked at the deadline
}
// passiveCheckpointWait waits, with getters only, for the checkpoint to pass
// cpAtBusy. The window counts from the last moment a flusher cycle was in
// progress: a cycle slower than the window (a slow disk on a loaded host) is
// waited for, up to deadline; a completed cycle that did not advance the
// checkpoint does not extend it, so a flusher that cycles without reclaiming
// still fails within the window. Every read is bounded by deadline, so a
// read blocked behind a stalled store lock ends the wait there too.
func passiveCheckpointWait(getCP func() uint64, flushing func() bool, cpAtBusy, target uint64, deadline time.Time, window time.Duration) passiveResult {
r := passiveResult{cp: cpAtBusy, lastInCycle: time.Now()}
for cpAtBusy < target && r.cp <= cpAtBusy && time.Since(r.lastInCycle) < window && time.Now().Before(deadline) {
time.Sleep(25 * time.Millisecond)
if !time.Now().Before(deadline) {
break // the deadline passed while sleeping: no read is started past it
}
v, ok := boundedRead(getCP, deadline)
if !ok {
r.blocked = true
return r
}
r.cp = v
if flushing() {
r.lastInCycle = time.Now()
}
}
return r
}
// storeView is what the no-Flush check observes, with getters only.
// checkpoint and next take the store lock (CheckpointLSN, NextLSN); flushing
// reads atomic flusher counters.
type storeView struct {
checkpoint, next func() uint64
flushing func() bool
}
// storeSnap is one bounded observation. When ok is false a read was still
// blocked at its deadline and cp and next are unavailable, never re-read.
type storeSnap struct {
cp, next uint64
ok bool
at time.Time
}
func (s storeSnap) String() string {
if !s.ok {
return fmt.Sprintf("cp=unavailable next=unavailable (a store read blocked, %v ago)", time.Since(s.at).Round(time.Millisecond))
}
return fmt.Sprintf("cp=%d next=%d", s.cp, s.next)
}
// snapshot reads the checkpoint and the next LSN, each bounded by deadline.
func (v storeView) snapshot(deadline time.Time) storeSnap {
cp, ok := boundedRead(v.checkpoint, deadline)
if !ok {
return storeSnap{at: time.Now()}
}
next, ok := boundedRead(v.next, deadline)
if !ok {
return storeSnap{at: time.Now()}
}
return storeSnap{cp: cp, next: next, ok: true, at: time.Now()}
}
// busyCheck is the outcome of the first busy write's passive check.
type busyCheck struct {
atBusy storeSnap // the checkpoint at the busy write, and the next LSN for the target
wait passiveResult
waited time.Duration
failed string // empty when the check passed
}
func (c busyCheck) String() string {
return fmt.Sprintf("wait=%v atBusy: %v cpObserved=%d, last in a cycle %v ago, read blocked=%v", c.waited, c.atBusy, c.wait.cp, time.Since(c.wait.lastInCycle), c.wait.blocked)
}
// passiveBusyCheck is the first busy write's check: with getters only, the
// checkpoint must pass its value at the busy write before the window ends.
// Every store observation, including the target, is bounded by deadline.
func passiveBusyCheck(v storeView, deadline time.Time, window time.Duration) busyCheck {
start := time.Now()
c := busyCheck{atBusy: v.snapshot(deadline)}
c.wait.lastInCycle = start
if !c.atBusy.ok {
c.waited = time.Since(start)
c.failed = "a store read at the busy write blocked past the write's retry deadline (a store lock held)"
return c
}
target := c.atBusy.next - 1
c.wait = passiveCheckpointWait(v.checkpoint, v.flushing, c.atBusy.cp, target, deadline, window)
c.waited = time.Since(start)
if c.atBusy.cp < target && c.wait.cp <= c.atBusy.cp {
c.failed = "the checkpoint did not advance without another write"
if c.wait.blocked {
c.failed = "a checkpoint read blocked past the write's retry deadline (a store lock held)"
}
}
return c
}
// lockedStore models the store's lock-taking getters: the first free reads
// answer at once, later ones take mu, which a test holds as a stalled
// checkpoint publication would.
type lockedStore struct {
mu sync.RWMutex
free int32
reads atomic.Int32
finished atomic.Int32
cp, next atomic.Uint64
}
func (s *lockedStore) get(v *atomic.Uint64) func() uint64 {
return func() uint64 {
defer s.finished.Add(1)
if s.reads.Add(1) > s.free {
s.mu.RLock()
defer s.mu.RUnlock()
}
return v.Load()
}
}
func (s *lockedStore) view() storeView {
return storeView{checkpoint: s.get(&s.cp), next: s.get(&s.next), flushing: func() bool { return true }}
}
// join waits, bounded, for every read started to return (call it after mu is
// released): a read left running would outlive the test.
func (s *lockedStore) join(t *testing.T) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for s.finished.Load() != s.reads.Load() {
if time.Now().After(deadline) {
t.Fatalf("store reads did not return after the lock was released: started=%d finished=%d", s.reads.Load(), s.finished.Load())
}
time.Sleep(time.Millisecond)
}
}
// heldUntil holds s.mu until release (nil: never), or until the test ends,
// and at the end joins every read it held.
func heldUntil(t *testing.T, s *lockedStore, release <-chan struct{}) {
s.mu.Lock()
stop, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
select {
case <-release:
case <-stop:
}
s.mu.Unlock()
}()
t.Cleanup(func() { close(stop); <-done; s.join(t) })
}
// The passive wait waits for a read held behind the store lock: one released
// before the deadline returns the advanced checkpoint, not blocked; one held
// past it ends the wait at the deadline, not before. A flusher reported in a
// cycle the whole time does not extend the wait past the deadline.
func TestPassiveCheckpointWaitIsBoundedByItsDeadline(t *testing.T) {
const bound = 300 * time.Millisecond
const early = bound - 50*time.Millisecond // tolerant lower bound
const late = bound + 200*time.Millisecond
inCycle := func() bool { return true }
t.Run("released before the deadline", func(t *testing.T) {
s := &lockedStore{}
s.cp.Store(5)
release := make(chan struct{})
heldUntil(t, s, release)
start := time.Now()
time.AfterFunc(bound/3, func() { s.cp.Store(7); close(release) })
r := passiveCheckpointWait(s.get(&s.cp), inCycle, 5, 9, start.Add(bound), 10*time.Second)
if took := time.Since(start); r.blocked || r.cp != 7 || took < bound/3-20*time.Millisecond || took >= bound {
t.Fatalf("a read released at %v: blocked=%v cp=%d after %v, want cp=7 not blocked before the %v deadline", bound/3, r.blocked, r.cp, took, bound)
}
})
t.Run("held past the deadline", func(t *testing.T) {
s := &lockedStore{free: 1} // the first read answers; later ones wait for the lock
s.cp.Store(5)
heldUntil(t, s, nil)
start := time.Now()
r := passiveCheckpointWait(s.get(&s.cp), inCycle, 5, 9, start.Add(bound), 10*time.Second)
if took := time.Since(start); !r.blocked || r.cp != 5 || took < early || took > late {
t.Fatalf("a read held behind the lock: blocked=%v cp=%d after %v, want blocked at the %v deadline", r.blocked, r.cp, took, bound)
}
})
t.Run("never advances", func(t *testing.T) {
start := time.Now()
r := passiveCheckpointWait(func() uint64 { return 5 }, inCycle, 5, 9, start.Add(bound), 10*time.Second)
if took := time.Since(start); r.blocked || r.cp != 5 || took < early || took > late {
t.Fatalf("a checkpoint that never advances with a flusher always in a cycle: blocked=%v cp=%d after %v, want the %v deadline", r.blocked, r.cp, took, bound)
}
})
}
// The busy path itself, with the store lock held across the deadline at each
// of its observations (the checkpoint at the busy write, the target, a read in
// the wait), fails at the deadline and formats its report without a store
// read; released early, it passes with the advanced checkpoint.
func TestPassiveBusyCheckWithTheStoreLockHeld(t *testing.T) {
const bound = 300 * time.Millisecond
for _, tc := range []struct {
name string
free int32
}{{"at the busy checkpoint read", 0}, {"at the target read", 1}, {"in the wait", 2}} {
t.Run(tc.name, func(t *testing.T) {
s := &lockedStore{free: tc.free}
s.cp.Store(5)
s.next.Store(10)
heldUntil(t, s, nil)
start := time.Now()
c := passiveBusyCheck(s.view(), start.Add(bound), 10*time.Second)
report := c.String()
took := time.Since(start)
if c.failed == "" || took < bound-50*time.Millisecond || took > bound+200*time.Millisecond {
t.Fatalf("lock held %s: failed=%q after %v (%s), want a failure at the %v deadline", tc.name, c.failed, took, report, bound)
}
if tc.free < 2 && (c.atBusy.ok || !bytes.Contains([]byte(report), []byte("cp=unavailable"))) {
t.Fatalf("lock held %s: the report must say unavailable: %s", tc.name, report)
}
if tc.free == 2 && (!c.wait.blocked || c.atBusy.cp != 5 || c.atBusy.next != 10) {
t.Fatalf("lock held %s: %s", tc.name, report)
}
})
}
t.Run("released before the deadline", func(t *testing.T) {
s := &lockedStore{free: 2}
s.cp.Store(5)
s.next.Store(10)
release := make(chan struct{})
heldUntil(t, s, release)
start := time.Now()
time.AfterFunc(bound/3, func() { s.cp.Store(7); close(release) })
c := passiveBusyCheck(s.view(), start.Add(bound), 10*time.Second)
if c.failed != "" || c.wait.blocked || c.wait.cp != 7 || time.Since(start) >= bound {
t.Fatalf("lock released at %v: failed=%q %s", bound/3, c.failed, c)
}
})
}
// Public provider + actual NVMe handler, file-backed v3 with the default
// 64 MiB WAL. No injected I/O failures, private selector, or flusher control.
func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) {
@@ -79,6 +343,13 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
if err := ws.SetWMode(mode); err != nil {
t.Fatal(err)
}
// Getters only: no Write, Sync, NotifyUrgent or Close may drive progress
// before the first retry. Inside the write loop the store is observed only
// through bounded reads, so a held store lock cannot outlast a deadline.
view := storeView{checkpoint: ws.CheckpointLSN, next: ws.NextLSN, flushing: func() bool {
fi := ws.FlusherInstrumentation()
return fi.CyclesStarted > fi.CyclesSucceeded+fi.CyclesFailed
}}
syncsBefore := ws.WALSyncCount()
var durations []time.Duration
busyCount := 0
@@ -94,7 +365,8 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
}
}
retryDeadline := time.Now().Add(30 * time.Second)
cpBefore := ws.CheckpointLSN()
snapBefore := view.snapshot(retryDeadline)
last := snapBefore // diagnostics use the last observation, never a fresh read
retried := false
for {
writeStart := time.Now()
@@ -105,11 +377,11 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
dump := make([]byte, 2<<20)
n := runtime.Stack(dump, true)
t.Logf("TIMEOUT STACKS\n%s", dump[:n])
t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v cp=%d next=%d", off, elapsed, time.Since(start), busyCount, r, ws.CheckpointLSN(), ws.NextLSN())
t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v last observed %v", off, elapsed, time.Since(start), busyCount, r, last)
}
if r.AsError() == nil {
if retried {
t.Logf("NO FLUSH resumed bytes=%d cp=%d->%d next=%d syncs=%d busy=%d", off, cpBefore, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount(), busyCount)
t.Logf("NO FLUSH resumed bytes=%d before: %v now: %v syncs=%d busy=%d", off, snapBefore, view.snapshot(retryDeadline), ws.WALSyncCount(), busyCount)
}
break
}
@@ -118,28 +390,21 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
}
busyCount++
retried = true
t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v cp=%d next=%d syncs=%d", off, busyCount, elapsed, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount())
last = view.snapshot(retryDeadline)
t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v %v syncs=%d", off, busyCount, elapsed, last, ws.WALSyncCount())
if busyCount == 1 {
passiveStart := time.Now()
cpAtBusy := ws.CheckpointLSN()
target := ws.NextLSN() - 1
cpObserved := cpAtBusy
// Getters only: no Write, Sync, NotifyUrgent or Close may
// drive progress before the first retry.
for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second {
time.Sleep(25 * time.Millisecond)
cpObserved = ws.CheckpointLSN()
}
t.Logf("NO FLUSH passive bytes=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d", off, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target)
if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) {
t.Fatalf("NO FLUSH passive checkpoint did not advance without another write: bytes=%d cp=%d busy=%d", off, cpObserved, busyCount)
c := passiveBusyCheck(view, retryDeadline, 10*time.Second)
fi := ws.FlusherInstrumentation()
t.Logf("NO FLUSH passive bytes=%d before: %v %v flusher: cycles started=%d succeeded=%d failed=%d max=%v", off, snapBefore, c, fi.CyclesStarted, fi.CyclesSucceeded, fi.CyclesFailed, time.Duration(fi.CycleMaxDurationNanos))
if c.failed != "" {
t.Fatalf("NO FLUSH passive check: %s: bytes=%d busy=%d %v", c.failed, off, busyCount, c)
}
}
// Retry the identical command; no caller Flush drives reclamation.
time.Sleep(25 * time.Millisecond)
}
if (off+transfer)%(16*1024*1024) == 0 {
t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN())
t.Logf("NO FLUSH progress bytes=%d elapsed=%v %v", off+transfer, time.Since(start), view.snapshot(time.Now().Add(5*time.Second)))
}
}
// The expected bytes come from the submitted pattern, not another reader.
@@ -620,6 +620,10 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
})
s.recordWriteHandler(time.Since(handlerStart))
if res.AsError() != nil {
if s.logger != nil && res.SCT == SCTGeneric && res.SC == SCNamespaceNotReady &&
(s.target == nil || s.target.allowWriteFailureLog(time.Now())) {
s.logger.Printf("nvme: Write failed qid=%d nsid=%d lba=%d blocks=%d sct=%#x sc=%#x elapsed=%s reason=%q", s.qid, req.capsule.NSID, req.capsule.Lba(), req.capsule.LbaLength(), res.SCT, res.SC, time.Since(arrival), res.Reason)
}
req.resp.Status = res.completionStatus()
}
s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()})
@@ -13,6 +13,7 @@ import (
"log"
"net"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
@@ -81,6 +82,8 @@ type Target struct {
sessions sync.WaitGroup
logger Logger
closed chan struct{}
// Shared by all connections of this volume; guarded by mu.
nextWriteFailureLog time.Time
// Admin controller registry — populated on admin-queue
// Connect (§3.1 A10.5 + R3), looked up on IO-queue Connect
@@ -92,6 +95,18 @@ type Target struct {
stats targetStats
}
// Retryable failures can arrive on many connections at once. Keep the first
// cause immediately, then emit at most one diagnostic per second per target.
func (t *Target) allowWriteFailureLog(now time.Time) bool {
t.mu.Lock()
defer t.mu.Unlock()
if now.Before(t.nextWriteFailureLog) {
return false
}
t.nextWriteFailureLog = now.Add(time.Second)
return true
}
// NewTarget builds a Target. Provider must be non-nil.
func NewTarget(cfg TargetConfig) *Target {
if cfg.Provider == nil {
@@ -0,0 +1,88 @@
package nvme
import (
"bytes"
"context"
"errors"
"log"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
func TestSessionRetryableWriteLogsReason(t *testing.T) {
for _, tc := range []struct {
name string
err error
expired bool
}{
{"busy", frontend.ErrBackendBusy, false},
{"not-ready", frontend.ErrNotReady, false},
{"deadline", context.DeadlineExceeded, true},
} {
t.Run(tc.name, func(t *testing.T) {
var logs bytes.Buffer
backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err}
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: &Target{}, logger: log.New(&logs, "", 0), qid: 7, respCh: make(chan *response, 1), done: make(chan struct{})}
req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1, D10: 23}}
if tc.expired {
req.receivedAt = time.Now().Add(-5 * time.Second)
}
s.handleWrite(context.Background(), req)
if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) {
t.Fatalf("completion=%#x", got)
}
for _, want := range []string{"nvme: Write failed", "qid=7", "nsid=1", "lba=23", "sc=0x82", "backend temporarily unavailable on write", tc.err.Error()} {
if !strings.Contains(logs.String(), want) {
t.Fatalf("missing %q in log %q", want, logs.String())
}
}
if strings.Count(logs.String(), "\n") != 1 {
t.Fatalf("want one failure line: %q", logs.String())
}
})
}
}
func TestSessionRetryableWriteLogBoundAcrossConnections(t *testing.T) {
var logs bytes.Buffer
logger := log.New(&logs, "", 0)
target := &Target{}
write := func(target *Target, cause error) {
backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: cause}
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: target, logger: logger, respCh: make(chan *response, 1), done: make(chan struct{})}
req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1}}
s.handleWrite(context.Background(), req)
<-s.respCh
}
// Neither a successful write nor an unrelated error consumes the first
// transient diagnostic or creates a new log stream.
write(target, nil)
write(target, errors.New("permanent failure"))
if logs.Len() != 0 {
t.Fatalf("unrelated writes logged: %q", logs.String())
}
var wg sync.WaitGroup
for range 16 {
wg.Add(1)
go func() { defer wg.Done(); write(target, frontend.ErrBackendBusy) }()
}
wg.Wait()
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 1 {
t.Fatalf("burst across connections logged %d lines, want 1", got)
}
// A different volume must retain its first diagnostic.
write(&Target{}, frontend.ErrNotReady)
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 2 {
t.Fatalf("second target did not log independently: %d lines", got)
}
time.Sleep(1100 * time.Millisecond)
write(target, frontend.ErrBackendBusy)
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 3 {
t.Fatalf("diagnostics did not resume after the rate window: %d lines", got)
}
}
+2
View File
@@ -19,6 +19,8 @@ var masterRules = map[string]auth.Rule{
control.LifecycleService_GetVolume_FullMethodName: {Min: auth.RoleViewer},
control.LifecycleService_ReserveVolumeDeletion_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName: {Min: auth.RoleViewer},
control.LifecycleService_FinalizeFormat_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.LifecycleService_RetireHost_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.ObservationService_ReportHeartbeat_FullMethodName: {Node: true},
control.ObservationService_ReportClusterEvent_FullMethodName: {Min: auth.RoleOperator},
+4 -4
View File
@@ -42,8 +42,8 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) {
}
// SubscribeProbeRounds and AnswerProbe (the promotion probe round) are
// node-only, each for the caller's own server id.
if len(registered) != 29 {
t.Fatalf("%d registered methods; the table was written for 29: review the new ones", len(registered))
if len(registered) != 31 {
t.Fatalf("%d registered methods; the table was written for 31 (FinalizeFormat and RetireHost added, admin and strict): review the new ones", len(registered))
}
}
@@ -77,7 +77,7 @@ func TestMasterOperatorMethodsAreStrict(t *testing.T) {
t.Errorf("%s is named in notStrict but is not a non-strict operator method: drop the entry", m)
}
}
if strict != 11 {
t.Errorf("%d strict methods; the phase 0 set is 11 (update this count with the change that adds one)", strict)
if strict != 13 {
t.Errorf("%d strict methods; the phase 0 set is 11, plus FinalizeFormat and RetireHost: 13 (update this count with the change that adds one)", strict)
}
}
@@ -0,0 +1,298 @@
package master
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// readsLevels holds the format read level each of a server's processes
// reported (its latest heartbeat's reads_level), in memory only, one entry
// per volume: a server runs one process per volume, so a later report for
// the same volume is that volume's process (restarted or replaced) and
// supersedes the earlier one. A server reads the lowest level of its
// entries. Silence is not proof that a process is gone: an entry whose
// volume the server still serves (a placement, a live line) stays, however
// long its process has been silent; only a silent entry of a volume the
// server no longer serves leaves after the freshness window. A registered
// server with no entry reads level 0: unknown counts as old.
type readsLevels struct {
mu sync.Mutex
window time.Duration
now func() time.Time
procs map[string]map[string]procLevel // server -> volume -> report
}
type procLevel struct {
level uint32
process string
seen time.Time
}
func newReadsLevels(window time.Duration) *readsLevels {
return &readsLevels{window: window, now: time.Now, procs: map[string]map[string]procLevel{}}
}
// note records the level the process holding volume (on server) reported.
func (r *readsLevels) note(server, volume, process string, level uint32) {
r.mu.Lock()
defer r.mu.Unlock()
if r.procs[server] == nil {
r.procs[server] = map[string]procLevel{}
}
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now()}
}
// forget drops every entry of server (a retired host).
func (r *readsLevels) forget(server string) {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.procs, server)
}
// liveLocked returns server's entries that still count: every entry of a
// served volume, and the others reported within the window (a silent
// entry of an unserved volume is dropped).
func (r *readsLevels) liveLocked(server string, served map[string]bool) map[string]procLevel {
cutoff := r.now().Add(-r.window)
for v, e := range r.procs[server] {
if e.seen.Before(cutoff) && !served[v] {
delete(r.procs[server], v)
}
}
return r.procs[server]
}
// of is the lowest level of server's live entries, and whether it has any.
func (r *readsLevels) of(server string, served map[string]bool) (uint32, bool) {
r.mu.Lock()
defer r.mu.Unlock()
var low uint32
found := false
for _, e := range r.liveLocked(server, served) {
if !found || e.level < low {
low, found = e.level, true
}
}
return low, found
}
// below names server's live entries below level, sorted, each as
// "process of volume (reads level N)".
func (r *readsLevels) below(server string, level uint32, served map[string]bool) []string {
r.mu.Lock()
defer r.mu.Unlock()
var out []string
for v, e := range r.liveLocked(server, served) {
if e.level < level {
out = append(out, fmt.Sprintf("%s of %s (reads level %d)", e.process, v, e.level))
}
}
sort.Strings(out)
return out
}
// noteHeartbeat records reads for every volume a heartbeat reports (each
// slot), naming the reporting process by the slot's incarnation (new on
// every process start), else its data address. A heartbeat with no slot
// is recorded under no volume.
func (r *readsLevels) noteHeartbeat(server string, slots []*control.HeartbeatSlot, reads uint32) {
if len(slots) == 0 {
r.note(server, "", "", reads)
return
}
for _, s := range slots {
process := s.GetIncarnation()
if process == "" {
process = s.GetDataAddr()
}
r.note(server, s.GetVolumeId(), process, reads)
}
}
// servedBy is the set of volumes server holds work for (volumesServedBy).
func (h *Host) servedBy(server string) map[string]bool {
out := map[string]bool{}
for _, v := range h.volumesServedBy(server) {
out[v] = true
}
return out
}
// formatLevelState is the cluster's format level in memory: 0 until the
// operator finalizes the v1.1 format.
type formatLevelState struct{ v atomic.Uint32 }
// formatLevel is the cluster's format level: 0 until the operator
// finalizes the v1.1 format.
func (h *Host) formatLevel() uint32 { return h.format.v.Load() }
// formatEligible reports whether server may be given new work (placement, a
// move, a failover) at the cluster's format level: its binary reads that
// level. At level 0 every server is.
func (h *Host) formatEligible(server string) bool {
level := h.formatLevel()
if level == 0 {
return true
}
reads, ok := h.reads.of(server, h.servedBy(server))
return ok && reads >= level
}
// formatTooOld names why server is not format-eligible, or "" when it is.
func (h *Host) formatTooOld(server string) string {
if h.formatEligible(server) {
return ""
}
reads, ok := h.reads.of(server, h.servedBy(server))
if !ok {
return fmt.Sprintf("node %q has not reported its format read level; the cluster's format level is %d", server, h.formatLevel())
}
return fmt.Sprintf("node %q reads format level %d (the lowest of its processes); the cluster's format level is %d (binary_too_old)", server, reads, h.formatLevel())
}
// belowLevel lists the given servers whose reported read level is below
// level, or that have not reported, sorted, each with what it reported.
func (h *Host) belowLevel(servers []string, level uint32) []string {
var out []string
for _, s := range servers {
served := h.servedBy(s)
reads, ok := h.reads.of(s, served)
switch {
case !ok:
out = append(out, fmt.Sprintf("%s (no report)", s))
case reads < level:
out = append(out, fmt.Sprintf("%s (process %s)", s, strings.Join(h.reads.below(s, level, served), ", ")))
}
}
sort.Strings(out)
return out
}
// errFormatHostsTooOld is a finalize refused for registered hosts that do
// not read the new level; errHostHoldsWork a retire refused for a host that
// holds work. Both name what refused them.
type errFormatHostsTooOld struct{ hosts []string }
func (e errFormatHostsTooOld) Error() string {
return fmt.Sprintf("format finalize refused: registered hosts do not read format level 1: %s; upgrade each one, or retire it (sw-block cluster retire-host)", strings.Join(e.hosts, ", "))
}
type errHostHoldsWork struct {
server string
volumes []string
}
func (e errHostHoldsWork) Error() string {
return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", "))
}
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
// Finalize; FormatGateMaster: the one durable step). It is refused while any
// registered host has not reported reads_level >= 1 since this master
// started. Otherwise, in order: the attestation envelope is written durably
// (the level, and the fence against v1.0.x masters, in one write); the
// publisher switches to level 1 under its locks; then the answer. At level
// 1 it writes nothing (already).
func (h *Host) FinalizeFormat(level uint32) (already bool, err error) {
if level != 1 {
return false, fmt.Errorf("format finalize: level %d; the only level to finalize is 1", level)
}
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
if h.formatLevel() >= 1 {
return true, nil
}
var registered []string
if h.lifecycle != nil {
for _, n := range h.lifecycle.Nodes.ListNodes() {
registered = append(registered, n.ServerID)
}
}
if below := h.belowLevel(registered, 1); len(below) > 0 {
return false, errFormatHostsTooOld{hosts: below}
}
if _, err := h.attest.finalize(); err != nil {
return false, fmt.Errorf("format finalize: %w", err)
}
h.Publisher().FinalizeFormatLevel()
h.format.v.Store(1)
h.log.Printf("blockmaster: cluster format level finalized at 1 (%d registered hosts read it)", len(registered))
return false, nil
}
// RetireHost removes server from the node inventory, so it no longer counts
// for the format finalize or for placement. It is refused while server
// holds a lease or an assignment for any volume (FormatGate r2: a retire
// of a holding host breaks OneServer). A retired host that returns
// registers again (the spec import) and is judged at its reported level.
func (h *Host) RetireHost(server, confirm string) error {
if server == "" || confirm != server {
return fmt.Errorf("retire refused: confirm must repeat the server id %q", server)
}
if h.lifecycle == nil {
return fmt.Errorf("retire refused: this master keeps no node inventory")
}
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
if _, ok := h.lifecycle.Nodes.GetNode(server); !ok {
return fmt.Errorf("retire refused: host %q is not registered", server)
}
if vols := h.volumesServedBy(server); len(vols) > 0 {
return errHostHoldsWork{server: server, volumes: vols}
}
if err := h.lifecycle.Nodes.RemoveNode(server); err != nil {
return fmt.Errorf("retire: %w", err)
}
h.reads.forget(server)
h.log.Printf("blockmaster: host %s retired from the node inventory", server)
return nil
}
// FinalizeFormat is the RPC of Host.FinalizeFormat.
func (s *services) FinalizeFormat(ctx context.Context, req *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
already, err := s.host.FinalizeFormat(req.GetLevel())
var old errFormatHostsTooOld
switch {
case errors.As(err, &old):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonFormatHostsTooOld).Err()
case err != nil && req.GetLevel() != 1:
return nil, status.Error(codes.InvalidArgument, err.Error())
case err != nil:
return nil, status.Error(codes.Unavailable, err.Error())
}
return &control.FinalizeFormatResponse{FormatLevel: s.host.formatLevel(), Already: already}, nil
}
// RetireHost is the RPC of Host.RetireHost. It holds the workspace lock, as
// a placement does, so no placement onto the host lands between its check
// and the removal.
func (s *services) RetireHost(ctx context.Context, req *control.RetireHostRequest) (*control.RetireHostResponse, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.host.workspaceMu.Lock()
defer s.host.workspaceMu.Unlock()
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
var holds errHostHoldsWork
switch {
case errors.As(err, &holds):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork).Err()
case err != nil:
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
return &control.RetireHostResponse{ServerId: req.GetServerId()}, nil
}
@@ -0,0 +1,561 @@
package master
import (
"bytes"
"context"
"errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// fgHeartbeat sends server's heartbeat reporting reads (its binary's format
// read level).
func (r *isolationRig) fgHeartbeat(server string, reads uint32) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: reads,
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
return err
}
func binaryTooOld(err error) bool {
st := status.Convert(err)
if st.Code() != codes.FailedPrecondition {
return false
}
for _, d := range st.Details() {
if info, ok := d.(*errdetails.ErrorInfo); ok && info.Reason == lifecycleclient.ReasonBinaryTooOld {
return true
}
}
return false
}
// At level 0 every binary's heartbeat is taken; at level 1 one that reads
// only level 0 (or reports nothing: a v1.0.x binary) is refused, typed
// binary_too_old, and one that reads level 1 is taken (FormatGate: Join,
// Eligible).
func TestFormatGateRefusesAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if err := r.fgHeartbeat("node-a", 0); err != nil {
t.Fatalf("level 0: an old binary's heartbeat was refused: %v", err)
}
r.m.format.v.Store(1)
if err := r.fgHeartbeat("node-a", 0); !binaryTooOld(err) || !strings.Contains(status.Convert(err).Message(), "reads format level 0") {
t.Fatalf("level 1: an old binary's heartbeat: %v, want FailedPrecondition with reason %s", err, lifecycleclient.ReasonBinaryTooOld)
}
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatalf("level 1: a binary that reads level 1 was refused: %v", err)
}
}
// At level 1 no new work goes to a host that does not read it: a workspace
// placement and a move onto an old host (or one that never reported) are
// refused; at level 0 they are not refused for the format (FormatGate:
// Assign, NoStrand).
func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
for _, level := range []uint32{1, 0} {
for _, reported := range []bool{true, false} {
name := map[uint32]string{1: "level1", 0: "level0"}[level] + map[bool]string{true: "-old", false: "-silent"}[reported]
t.Run(name, func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if reported {
if err := r.fgHeartbeat("node-b", 0); err != nil {
t.Fatal(err)
}
}
r.m.format.v.Store(level)
r.createVolume(t, "placed")
r.place(t, "placed", "node-a")
r.createVolume(t, "fresh")
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
t.Fatal(err)
}
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
why := map[bool]string{true: "reads format level 0", false: "has not reported its format read level"}[reported]
if level == 0 {
if placeErr != nil {
t.Fatalf("level 0: placement refused: %v", placeErr)
}
if moveErr != nil && strings.Contains(moveErr.Error(), "format") {
t.Fatalf("level 0: move refused for the format: %v", moveErr)
}
return
}
if status.Code(placeErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(placeErr).Message(), why) {
t.Fatalf("level 1: PlaceWorkspace onto node-b: %v, want %q", placeErr, why)
}
if _, ok := r.m.Lifecycle().Placements.GetPlacement("fresh"); ok {
t.Fatal("a refused placement was recorded")
}
if status.Code(moveErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(moveErr).Message(), "move target node \"node-b\" "+why) {
t.Fatalf("level 1: MoveWorkspace onto node-b: %v, want %q", moveErr, why)
}
})
}
}
}
// At level 1 the product loop never places a new volume on a host that does
// not read it, and does on one that does.
func TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel(t *testing.T) {
for _, reads := range []uint32{0, 1} {
t.Run(map[uint32]string{0: "old", 1: "new"}[reads], func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502",
Pools: []lifecycle.StoragePool{{PoolID: "p1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096}}}); err != nil {
t.Fatal(err)
}
if err := r.fgHeartbeat("node-c", reads); err != nil {
t.Fatal(err)
}
r.m.format.v.Store(1)
r.createVolume(t, "auto")
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
p, ok := r.m.Lifecycle().Placements.GetPlacement("auto")
if reads == 0 && ok {
t.Fatalf("level 1: the product loop placed a new volume on a host that reads level 0: %+v", p)
}
if reads == 1 && (!ok || p.Slots[0].ServerID != "node-c") {
t.Fatalf("level 1: the product loop did not place on node-c, which reads level 1: %+v ok=%v", p, ok)
}
})
}
}
// Every assignment carries the cluster's format level.
func TestAssignmentFactCarriesTheFormatLevel(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
svc := &services{host: r.m}
for _, level := range []uint32{0, 1} {
r.m.format.v.Store(level)
if got := svc.assignmentFact(adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 1}).GetFormatLevel(); got != level {
t.Fatalf("level %d: AssignmentFact.format_level = %d", level, got)
}
}
}
func reasonOf(err error) string {
for _, d := range status.Convert(err).Details() {
if info, ok := d.(*errdetails.ErrorInfo); ok {
return info.Reason
}
}
return ""
}
// The finalize is refused, naming each one, while a registered host has not
// reported or reads level 0, and leaves the attestation file in v1.0.x's
// form (level 0). Once every registered host reads level 1 it writes the
// envelope (format_level 1), switches the publisher, and a second finalize
// writes nothing. A restarted master is still at level 1 (FormatGate:
// Finalize, FinalizeKeepsHosts, OneWay).
func TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable(t *testing.T) {
authDir, lcDir := t.TempDir(), t.TempDir()
r := newIsolationRig(t, false, authDir, lcDir)
file := filepath.Join(authDir, storeAttestationFile)
finalize := func() (*control.FinalizeFormatResponse, error) {
return r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
}
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
for _, step := range []struct {
reads *uint32
want string
}{{nil, "node-b (no report)"}, {ptr(uint32(0)), "node-b (process 127.0.0.1:19311 of hb-node-b (reads level 0))"}} {
if step.reads != nil {
if err := r.fgHeartbeat("node-b", *step.reads); err != nil {
t.Fatal(err)
}
}
_, err := finalize()
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), step.want) {
t.Fatalf("finalize with %s: %v (reason %q)", step.want, err, reasonOf(err))
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatal("a refused finalize changed the level")
}
if b, err := os.ReadFile(file); err == nil && bytes.Contains(b, []byte(`"format"`)) {
t.Fatalf("a refused finalize wrote the envelope: %s", b)
}
}
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatal(err)
}
resp, err := finalize()
if err != nil || resp.GetFormatLevel() != 1 || resp.GetAlready() {
t.Fatalf("finalize with every host at level 1: %+v %v", resp, err)
}
if r.m.formatLevel() != 1 || r.m.Publisher().FormatLevel() != 1 {
t.Fatal("the finalize did not switch the master and the publisher to level 1")
}
b, err := os.ReadFile(file)
if err != nil || !bytes.Contains(b, []byte(`"format":2`)) || !bytes.Contains(b, []byte(`"format_level":1`)) {
t.Fatalf("the attestation file after the finalize: %s %v", b, err)
}
if resp, err := finalize(); err != nil || !resp.GetAlready() {
t.Fatalf("a second finalize: %+v %v, want already", resp, err)
}
r.close(t)
r2 := newIsolationRig(t, false, authDir, lcDir)
if r2.m.formatLevel() != 1 || r2.m.Publisher().FormatLevel() != 1 {
t.Fatal("a restarted master is not at level 1")
}
}
func ptr[T any](v T) *T { return &v }
// An envelope that says a level below 1 is refused at start: the level
// never drops.
func TestAnAttestationEnvelopeBelowLevel1IsRefused(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":2,"format_level":0,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := loadStoreAttestations(dir); err == nil {
t.Fatal("an envelope at format_level 0 was read")
}
}
// A retire is refused, naming the volume, while the host holds an
// assignment, and when confirm does not repeat the server id. A host
// holding nothing is retired, and the finalize no longer counts it.
func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "held")
r.place(t, "held", "node-b")
_, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-b", Confirm: "node-b"})
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonHostHoldsWork || !strings.Contains(status.Convert(err).Message(), "held") {
t.Fatalf("retire of a host holding a placement: %v (reason %q)", err, reasonOf(err))
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("retire with a confirm that does not match: %v", err)
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil {
t.Fatalf("retire of a host holding nothing: %v", err)
}
if _, ok := r.m.Lifecycle().Nodes.GetNode("node-a"); ok {
t.Fatal("the retired host is still registered")
}
// node-b (holding "held") reports level 1; node-a, retired, never
// reported: the finalize goes through.
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatal(err)
}
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil {
t.Fatalf("finalize after the silent host was retired: %v", err)
}
}
// A finalize whose durable write fails changes no level: the publisher and
// the master stay at 0 (the switch follows the write; FormatGateMaster
// finalize_not_atomic).
func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
for _, s := range []string{"node-a", "node-b"} {
if err := r.fgHeartbeat(s, 1); err != nil {
t.Fatal(err)
}
}
saved := syncAttestationDir
t.Cleanup(func() { syncAttestationDir = saved })
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err == nil {
t.Fatal("a finalize whose envelope write failed succeeded")
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
}
}
// fgProcessHeartbeat sends a heartbeat of one of server's processes (its
// incarnation) for vol, reporting reads.
func (r *isolationRig) fgProcessHeartbeat(server, incarnation, vol string, reads uint32) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: reads,
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r-" + incarnation, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1], Incarnation: incarnation}}})
return err
}
// One server id is shared by its per-volume processes, which may run
// different binaries: an old process's level 0 is not hidden by a new
// process's later level 1. The finalize is refused naming the old process;
// at level 1 the server takes no new work while the old process is live,
// and the new process's own heartbeat is taken (FormatGate: a host is a
// process).
func TestAServerReadsTheLowestLevelOfItsProcesses(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of va (reads level 0)") {
t.Fatalf("finalize with an old process beside a new one on node-b: %v", err)
}
r.m.format.v.Store(1)
if r.m.formatEligible("node-b") {
t.Fatal("level 1: node-b is eligible while its old process is live")
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatalf("level 1: the new process's own heartbeat was refused: %v", err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); !binaryTooOld(err) {
t.Fatalf("level 1: the old process's heartbeat: %v", err)
}
}
// Silence is not proof that a process is gone: an entry of a volume its
// server still serves stays, however long its process is silent; an
// unserved volume's silent entry leaves after the window; a later report
// for the same volume (its restarted or replaced process) supersedes it.
func TestAServerKeepsASilentProcessThatStillHoldsItsVolume(t *testing.T) {
rl := newReadsLevels(time.Minute)
now := time.Unix(1000, 0)
rl.now = func() time.Time { return now }
rl.note("s", "va", "old", 0)
rl.note("s", "vb", "new", 1)
now = now.Add(2 * time.Minute)
rl.note("s", "vb", "new", 1)
if l, ok := rl.of("s", map[string]bool{"va": true}); !ok || l != 0 {
t.Fatalf("va still served, its process silent past the window: level %d %v, want 0", l, ok)
}
if l, ok := rl.of("s", map[string]bool{}); !ok || l != 1 {
t.Fatalf("va no longer served and silent: level %d %v, want 1", l, ok)
}
rl.note("s", "va", "old", 0)
rl.note("s", "va", "restarted", 1)
if l, ok := rl.of("s", map[string]bool{"va": true}); !ok || l != 1 {
t.Fatalf("va's process replaced by one reading 1: level %d %v, want 1", l, ok)
}
}
// An old process holds a placed volume, a new sibling
// keeps reporting, the old one falls silent past the freshness window. The
// finalize stays refused naming the old process, and at level 1 a placement
// onto the server stays refused by the format check.
func TestASilentOldHolderKeepsTheFinalizeAndNewWorkRefused(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
now := time.Now()
r.m.reads.now = func() time.Time { return now }
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
r.createVolume(t, "va")
r.place(t, "va", "node-b")
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); err != nil {
t.Fatal(err)
}
now = now.Add(time.Hour) // past any freshness window: the old process is silent
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of va (reads level 0)") {
t.Fatalf("finalize with a silent old holder of va: %v", err)
}
r.m.format.v.Store(1)
if why := r.m.formatTooOld("node-b"); why == "" {
t.Fatal("level 1: node-b takes new work while its silent old process still holds va")
}
r.createVolume(t, "fresh")
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
t.Fatal(err)
}
if _, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}); status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "binary_too_old") {
t.Fatalf("level 1: a placement onto node-b: %v, want the format refusal", err)
}
}
// The publication boundary judges the server's level when the ask is
// published: an ask whose server reads below the cluster's level is refused
// there and its publish never runs; the control publishes (the admission
// itself, called with a recording publish).
func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
for _, old := range []bool{true, false} {
t.Run(map[bool]string{true: "old-process", false: "control"}[old], func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
level := uint32(1)
if old {
level = 0
}
if err := r.fgProcessHeartbeat("node-b", "proc", "v", level); err != nil {
t.Fatal(err)
}
r.m.format.v.Store(1)
published := false
err := r.m.admitWorkspacePublication(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302", Intent: authority.IntentBind},
func() error { published = true; return nil })
if old && (err == nil || published || !strings.Contains(err.Error(), "binary_too_old")) {
t.Fatalf("level 1, node-b's process reads 0: err %v, published %v; want refused before the publish", err, published)
}
if !old && (err != nil || !published) {
t.Fatalf("control: err %v, published %v; want published", err, published)
}
})
}
}
// A heartbeat that reports several volumes records the level for each: an
// old process reporting [va, vb] is kept for vb, still placed on its
// server, after va stops being served and the report ages past the
// window.
func TestEveryVolumeOfAHeartbeatKeepsItsLevel(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
now := time.Now()
r.m.reads.now = func() time.Time { return now }
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
r.createVolume(t, "vb")
r.place(t, "vb", "node-b")
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 0,
Slots: []*control.HeartbeatSlot{
{VolumeId: "va", ReplicaId: "r-a", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-proc"},
{VolumeId: "vb", ReplicaId: "r-b", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-proc"},
}}); err != nil {
t.Fatal(err)
}
now = now.Add(time.Hour)
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vc", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of vb (reads level 0)") {
t.Fatalf("finalize with the old process still holding vb (its second slot): %v", err)
}
}
// The queued-ask schedule: a bind is
// decided and reaches its publication admission while node-b's only process
// reads level 1; it is held there; another node-b process then reports level
// 0; released, the same ask is refused by the format check (binary_too_old)
// and no line is published. The control, with no downgrade, publishes.
func TestAHeldAskIsRefusedAfterItsServerTurnsOutOld(t *testing.T) {
for _, downgrade := range []bool{true, false} {
t.Run(map[bool]string{true: "downgrade", false: "control"}[downgrade], func(t *testing.T) {
authDir, lcDir := t.TempDir(), t.TempDir()
logs := &syncBuffer{}
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: lcDir, WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume,
Logger: log.New(logs, "", 0),
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{}, nil
}})
if err != nil {
t.Fatal(err)
}
entered, release, hookDone := make(chan struct{}), make(chan struct{}), make(chan struct{})
result := make(chan error, 1)
var once, releaseOnce sync.Once
releaseHold := func() { releaseOnce.Do(func() { close(release) }) }
m.testPublicationAdmission = func(ask authority.AssignmentAsk, next func() error) error {
if ask.VolumeID != "v" {
return next()
}
held := false
once.Do(func() { held = true })
if !held {
return next()
}
defer close(hookDone)
close(entered)
<-release
err := next()
result <- err
return err
}
m.format.v.Store(1)
m.Start()
t.Cleanup(func() { closeTestMaster(t, m) })
// Runs before the master's close (cleanups run last-in first): a
// failure before the release frees the held admission, and its
// return is joined (bounded) so Publisher.Run is never stranded.
t.Cleanup(func() {
releaseHold()
select {
case <-entered:
select {
case <-hookDone:
case <-time.After(10 * time.Second):
t.Error("the held publication admission did not return after its release")
}
default: // the hold was never reached
}
})
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
r := &isolationRig{m: m, logs: logs, ws: control.NewWorkspaceServiceClient(conn), lc: control.NewLifecycleServiceClient(conn), obs: control.NewObservationServiceClient(conn), ctx: ctx}
if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
t.Fatal(err)
}
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if _, err := r.obs.ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 1,
Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302", Incarnation: "new-proc", Reachable: true, Eligible: true}}}); err != nil {
t.Fatal(err)
}
if _, err := m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
select {
case <-entered:
case <-time.After(20 * time.Second):
t.Fatal("the bind never reached its publication admission")
}
if downgrade {
_ = r.fgProcessHeartbeat("node-b", "old-proc", "other", 0) // refused at level 1, but its level is recorded
}
releaseHold()
var got error
select {
case got = <-result:
case <-time.After(20 * time.Second):
t.Fatal("the held admission never finished")
}
_, bound := m.Publisher().VolumeAuthorityLine("v")
if downgrade && (got == nil || !strings.Contains(got.Error(), "binary_too_old") || bound) {
t.Fatalf("downgrade: admission %v, bound %v; want refused binary_too_old and no line", got, bound)
}
if !downgrade && (got != nil || !bound) {
t.Fatalf("control: admission %v, bound %v; want published", got, bound)
}
})
}
}
@@ -79,29 +79,45 @@ func TestAttestationGoldenFileIsTheV100File(t *testing.T) {
}
}
// Today's store writes the v1.0.0 file's volumes for the same steps, inside
// this version's envelope: {"format":2,"volumes":<the v1.0.0 bytes>}. The
// one change since v1.0.0, by the format path: a v1.0.x master refuses the
// envelope at start (TestAV100MasterRefusesTheAttestationEnvelope).
func TestAttestationsWriteTheV100FileInTheEnvelope(t *testing.T) {
// Until the format finalize (level 0) today's store writes the v1.0.0 file
// itself, byte for byte. The finalize writes this version's envelope around
// the same volumes, {"format":2,"format_level":1,"volumes":<the v1.0.0
// bytes>}: the one change since v1.0.0, by the format path, and a v1.0.x
// master refuses it at start (TestAV100MasterRefusesTheAttestationEnvelope).
func TestAttestationsWriteTheV100FileUntilTheFinalize(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
got, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
want := append(append([]byte(`{"format":2,"volumes":`), readGoldenAttestations(t)...), '}')
if want := readGoldenAttestations(t); !bytes.Equal(got, want) {
t.Fatalf("level 0: %s\n got %s\n want %s", goldenAttestationFix, got, want)
}
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
got, err = os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
want := append(append([]byte(`{"format":2,"format_level":1,"volumes":`), readGoldenAttestations(t)...), '}')
if !bytes.Equal(got, want) {
t.Fatalf("%s\n got %s\n want %s", goldenAttestationFix, got, want)
t.Fatalf("after the finalize: %s\n got %s\n want %s", goldenAttestationFix, got, want)
}
}
// A v1.0.x master decodes store-attestations.json as a bare map of volume
// records (json.Unmarshal into map[string]attestedStores, its
// loadStoreAttestations), and its New returns that error before it listens
// or publishes. The envelope fails that decode; today's master reads both
// forms, and a master started on a v1.0.x store rewrites it as the envelope
// before it serves.
// or publishes. Until the finalize the file is that map, so a v1.0.x master
// starts (going back works); the finalize's envelope fails that decode.
// Today's master reads both forms, and a start (ensureEnvelope) leaves a
// v1.0.x store in its form.
func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
@@ -110,39 +126,38 @@ func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) {
t.Fatal(err)
}
var v100 map[string]attestedStores // v1.0.x's decode, verbatim
if err := json.Unmarshal(b, &v100); err == nil {
t.Fatalf("a v1.0.x master's decode accepted the file written now: %v", v100)
if err := json.Unmarshal(b, &v100); err != nil {
t.Fatalf("level 0: a v1.0.x master's decode refused the file written now: %v", err)
}
if bad := readAttestations(dir); len(bad) != 0 {
t.Fatalf("today's master does not read its own envelope: %v", bad)
}
// A v1.0.x store (the bare map) is read, and ensureEnvelope rewrites it.
old := t.TempDir()
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
t.Fatal(err)
}
s, err := loadStoreAttestations(old)
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if bad := readAttestations(old); len(bad) != 0 {
t.Fatalf("today's master does not read the v1.0.x form: %v", bad)
}
if err := s.ensureEnvelope(); err != nil {
t.Fatal(err)
}
b, err = os.ReadFile(filepath.Join(old, storeAttestationFile))
if after, _ := os.ReadFile(filepath.Join(dir, storeAttestationFile)); !bytes.Equal(after, b) {
t.Fatalf("a level-0 start rewrote the v1.0.x file: %s", after)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
b, err = os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
v100 = nil
if err := json.Unmarshal(b, &v100); err == nil {
t.Fatal("after ensureEnvelope, a v1.0.x master's decode still accepts the store")
t.Fatalf("after the finalize, a v1.0.x master's decode accepted the file: %v", v100)
}
if bad := readAttestations(dir); len(bad) != 0 {
t.Fatalf("today's master does not read its own envelope: %v", bad)
}
// An envelope of a later format is refused by this master too.
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := loadStoreAttestations(old); err == nil {
if _, err := loadStoreAttestations(dir); err == nil {
t.Fatal("this master accepted attestation format 3")
}
}
@@ -243,10 +258,11 @@ func TestAttestationEnvelopeNeedsItsVolumesObject(t *testing.T) {
}
}
// An envelope already on disk is fsynced again (file and directory) on every
// start: a start that renamed it in and then failed its directory fsync must
// not leave the next start serving on an envelope that may not survive a
// crash.
// The finalize's envelope write fails when its directory fsync fails, and
// an envelope already on disk is fsynced again (file and directory) on every
// start: a finalize (or start) that renamed it in and then failed its
// directory fsync must not leave the next start serving on an envelope that
// may not survive a crash.
func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
@@ -260,8 +276,8 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := s.ensureEnvelope(); err == nil {
t.Fatal("a failed directory fsync of the first envelope write was not an error (the master would serve)")
if _, err := s.finalize(); err == nil || s.level() != 0 {
t.Fatalf("a failed directory fsync of the finalize's envelope: err=%v level=%d (want an error, level 0)", err, s.level())
}
// The process restarts: the envelope is on disk (the rename happened).
s, err = loadStoreAttestations(dir)
@@ -284,11 +300,18 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
func TestAttestationEnvelopeRoundTrips(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
first, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
s, err := loadStoreAttestations(dir)
s, err = loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
@@ -304,14 +327,19 @@ func TestAttestationEnvelopeRoundTrips(t *testing.T) {
}
}
// master.New refuses to serve when the attestation envelope cannot be made
// durable: it returns the error before it listens.
// master.New at level 1 refuses to serve when the attestation envelope
// cannot be made durable: it returns the error before it listens.
func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":2,"format_level":1,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
saved := syncAttestationDir
t.Cleanup(func() { syncAttestationDir = saved })
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
h, err := New(Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"})
h, err := New(Config{AuthorityStoreDir: dir, Listen: "127.0.0.1:0"})
if err == nil {
h.Start()
closeTestMaster(t, h)
t.Fatal("master.New served with a failed attestation envelope fsync")
}
@@ -320,8 +348,9 @@ func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) {
}
}
// A v1.0.x file that is null holds no attestations (as v1.0.x read it): it
// migrates to an envelope with an explicit {} that the next start reads.
// A v1.0.x file that is null holds no attestations (as v1.0.x read it); a
// level-0 start leaves it as it is, and the finalize writes an envelope
// with an explicit {} that the next start reads.
func TestAV100NullAttestationFileMigrates(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte("null"), 0o644); err != nil {
@@ -334,11 +363,17 @@ func TestAV100NullAttestationFileMigrates(t *testing.T) {
if err := s.ensureEnvelope(); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(dir, storeAttestationFile)); string(b) != "null" {
t.Fatalf("a level-0 start rewrote the null file: %s", b)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil || string(b) != `{"format":2,"volumes":{}}` {
t.Fatalf("migrated to %s (%v)", b, err)
if err != nil || string(b) != `{"format":2,"format_level":1,"volumes":{}}` {
t.Fatalf("finalized to %s (%v)", b, err)
}
if _, err := loadStoreAttestations(dir); err != nil {
t.Fatalf("the next start refuses the migrated file: %v", err)
t.Fatalf("the next start refuses the finalized file: %v", err)
}
}
+18 -5
View File
@@ -152,9 +152,15 @@ type Host struct {
statusLn net.Listener
statusHTTP *http.Server
journal *journalIsolation
grpc *grpc.Server
topo authority.AcceptedTopology
lifecycle *LifecycleStores
reads *readsLevels // each server's reported format read level (format_gate.go)
format formatLevelState // the cluster's format level (format_gate.go)
finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go)
// testPublicationAdmission, when a test sets it before Start, wraps each
// publication admission: next runs the admission itself.
testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error
grpc *grpc.Server
topo authority.AcceptedTopology
lifecycle *LifecycleStores
// RPC registration/place/move/ACK/delete and product ticks serialize here.
// Order: workspaceMu -> publisher or lifecycle store locks (not reversed).
workspaceMu sync.Mutex
@@ -267,6 +273,7 @@ func New(cfg Config) (*Host, error) {
topo: cfg.Topology,
events: newEventRing(1024),
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()),
}
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
@@ -287,12 +294,16 @@ func New(cfg Config) (*Host, error) {
return nil, fmt.Errorf("master.New: %w", err)
}
// Under the authority store's lock and before anything is served: the
// attestation file in this version's envelope, which a v1.0.x master
// refuses at start (store_attestation.go).
// cluster's format level is the attestation file's form (the envelope
// is level 1, re-fsynced here; v1.0.x's form is level 0, where this
// master keeps v1.0's semantics: store_attestation.go, format_gate.go).
if err := h.attest.ensureEnvelope(); err != nil {
_ = boot.Close()
return nil, fmt.Errorf("master.New: %w", err)
}
level := h.attest.level()
boot.Publisher.SetFormatLevelBeforeServing(level)
h.format.v.Store(level)
var sink authority.ControllerSink = ctrl
if len(cfg.Topology.Volumes) == 0 {
@@ -638,6 +649,8 @@ func (h *Host) Close(ctx context.Context) error {
}
h.wg.Wait()
// Level 0's horizon extenders write through the store: join them first.
h.boot.Publisher.CloseWorkspaceExtenders()
return errors.Join(statusErr, h.boot.Close())
}
@@ -1,6 +1,7 @@
package master
import (
"sort"
"encoding/json"
"fmt"
"net"
@@ -73,19 +74,25 @@ func (j *journalIsolation) setSelf(id storeident.Identity) {
// takes neither workspaceMu nor the publisher lock (held across authority
// store writes), only the published authority lines and the lifecycle
// stores, whose locks cover only their own file I/O.
func (h *Host) nodeServesVolumes(server string) bool {
func (h *Host) nodeServesVolumes(server string) bool { return len(h.volumesServedBy(server)) > 0 }
// volumesServedBy names, sorted and once each, every volume server holds
// work for: a placement slot (also every line it sources), a live line a
// move issued to it, or a static topology line on it.
func (h *Host) volumesServedBy(server string) []string {
seen := map[string]bool{}
lines := h.Publisher().PublishedAuthorityLines()
if h.lifecycle != nil {
for _, p := range h.lifecycle.Placements.ListPlacements() {
for _, slot := range p.Slots {
if slot.ServerID == server {
return true // also every line a placement slot sources
seen[p.VolumeID] = true
}
}
}
for volume, line := range lines {
if _, live := h.lifecycle.Volumes.GetVolumeSnapshot(volume); live && line.IssuedHost == server {
return true
seen[volume] = true
}
}
}
@@ -96,11 +103,16 @@ func (h *Host) nodeServesVolumes(server string) bool {
}
for _, slot := range v.Slots {
if slot.ServerID == server && slot.ReplicaID == line.ReplicaID {
return true
seen[v.VolumeID] = true
}
}
}
return false
out := make([]string, 0, len(seen))
for v := range seen {
out = append(out, v)
}
sort.Strings(out)
return out
}
// refuseColocatedHeartbeat is the strict heartbeat rule: a co-located node
@@ -122,13 +134,21 @@ func (h *Host) colocatedTargetRefused(server string) bool {
return h.cfg.StrictJournalIsolation && h.journal.isColocated(server)
}
// reconcilePlacements runs the product loop's placement reconcile. Under
// strict isolation each volume plans against the nodes without co-located
// ones, except the nodes its existing placement already names: a placement
// on a co-located node is kept (re-planning it away would move a serving
// volume), and no new placement chooses a co-located node.
// newWorkRefused reports whether server may not be given new work: strict
// isolation refuses a co-located node, and the format gate a node whose
// binary does not read the cluster's format level.
func (h *Host) newWorkRefused(server string) bool {
return h.colocatedTargetRefused(server) || !h.formatEligible(server)
}
// reconcilePlacements runs the product loop's placement reconcile. Each
// volume plans against the nodes new work may go to (newWorkRefused: not
// co-located under strict isolation, reading the cluster's format level),
// plus the nodes its existing placement already names: such a placement is
// kept (re-planning it away would move a serving volume), and no new
// placement chooses a refused node.
func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.NodeRegistration) []lifecycle.ReconcileResult {
if !h.cfg.StrictJournalIsolation {
if !h.cfg.StrictJournalIsolation && h.formatLevel() == 0 {
return lifecycle.ReconcilePlacement(h.readyVolumeRecords(stores.liveVolumes()), nodes, stores.Placements)
}
var out []lifecycle.ReconcileResult
@@ -141,7 +161,7 @@ func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.No
}
allowed := make([]lifecycle.NodeRegistration, 0, len(nodes))
for _, n := range nodes {
if placed[n.ServerID] || !h.journal.isColocated(n.ServerID) {
if placed[n.ServerID] || !h.newWorkRefused(n.ServerID) {
allowed = append(allowed, n)
}
}
@@ -30,7 +30,7 @@ func TestLayoutStoreReadyDecisionSites(t *testing.T) {
"product_loop.go submitPlacementSnapshots readyPlacements": 1,
"workspace_binding.go PlaceWorkspace workspaceVolume": 1,
"workspace_binding.go RegisterWorkspaceBinding workspaceVolume": 1,
"workspace_binding.go admitWorkspacePublication layoutStoreReady": 1,
"workspace_binding.go admitWorkspacePublicationNow layoutStoreReady": 1,
"workspace_service.go AckWorkspaceRevoked workspaceVolume": 1,
"workspace_service.go MoveWorkspace MoveWorkspace": 1,
"workspace_service.go MoveWorkspace workspaceVolume": 2,
@@ -304,7 +304,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
h.holdCreating(vol, why)
continue
}
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex)
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) && h.formatEligible(vol.Slots[currentIdx].ServerID)
// A fencing round fenced survivors above this line and nothing was
// published: they refuse the primary at its epoch (and may no longer
// look ready), so heal before anything else while it is acceptable.
@@ -319,7 +319,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
for _, slot := range vol.Slots {
if slot.ReplicaID != vol.Authority.ReplicaID {
candidates = append(candidates, slot)
if candidateAcceptableForPromotionGate(slot, serverIndex) {
if candidateAcceptableForPromotionGate(slot, serverIndex) && h.formatEligible(slot.ServerID) {
readyCandidate = true
}
}
@@ -537,6 +537,15 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.refuseServerIDFromOtherHost(r); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
// The format gate: the reporting process's read level, recorded before
// it is judged (its server then reads at most that level for new work);
// a process whose binary cannot read the cluster's format level is
// refused, so it is never observed as a candidate.
s.host.reads.noteHeartbeat(r.GetServerId(), r.GetSlots(), r.GetReadsLevel())
if level := s.host.formatLevel(); r.GetReadsLevel() < level {
why := fmt.Sprintf("node %q process reads format level %d; the cluster's format level is %d (binary_too_old)", r.GetServerId(), r.GetReadsLevel(), level)
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "heartbeat refused: "+why), lifecycleclient.ReasonBinaryTooOld).Err()
}
msg := heartbeatFromWire(r)
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
@@ -1266,6 +1275,7 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme
EvidenceFirstLsn: info.Primary.DataFirstLSN,
LineIncarnation: info.Incarnation,
AckProfile: s.host.lineAckProfile(),
FormatLevel: s.host.formatLevel(),
}
if info.Primary.StoreID != ([16]byte{}) {
id := info.Primary.StoreID
@@ -1,6 +1,7 @@
package master
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
@@ -19,17 +20,19 @@ import (
// write (temp file, fsync, rename, directory fsync).
const storeAttestationFile = "store-attestations.json"
// storeAttestationFormat is the envelope this master writes:
// {"format": 2, "volumes": {...}}. A v1.0.x master decodes the file as a
// bare map of volume records, so the number under "format" fails its whole
// start (before any listener or authority publication): the downgrade guard
// for what this version stops keeping current (the lease horizon). The
// bare map (v1.0.x's form) is still read.
// storeAttestationFormat is the envelope the format finalize writes:
// {"format": 2, "format_level": 1, "volumes": {...}}. The file's form IS the
// cluster's format level: v1.0.x's bare map is level 0, the envelope level
// 1. A v1.0.x master decodes the file as a bare map of volume records, so
// the number under "format" fails its whole start (before any listener or
// authority publication): the finalize's one durable write raises the level
// and fences v1.0.x masters together.
const storeAttestationFormat = 2
type storeAttestationEnvelope struct {
Format int `json:"format"`
Volumes map[string]attestedStores `json:"volumes"`
Format int `json:"format"`
FormatLevel int `json:"format_level"`
Volumes map[string]attestedStores `json:"volumes"`
}
// attestedStores is one volume's last attestation: the primary line that
@@ -68,8 +71,8 @@ type storeAttestations struct {
mu sync.Mutex
path string // "" = memory only
vols map[string]attestedStores
// enveloped: the file on disk is this version's envelope (persist always
// writes it; ensureEnvelope writes it at start).
// enveloped: the file on disk is the envelope, so the cluster's format
// level is 1 (persist then keeps that form; finalize writes it first).
enveloped bool
// changed[vol] is closed (and dropped) when vol's record changes.
changed map[string]chan struct{}
@@ -119,6 +122,12 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error)
if env.Volumes == nil {
return nil, false, fmt.Errorf("format %d without a volumes object", format)
}
// format_level is 1 (an envelope written before the level was
// recorded in it says nothing, and is level 1 too); anything else
// is refused: the level never drops.
if lv, ok := probe["format_level"]; ok && string(bytes.TrimSpace(lv)) != "1" {
return nil, false, fmt.Errorf("format %d with format_level %s, this master reads level 1", format, bytes.TrimSpace(lv))
}
return env.Volumes, true, nil
}
}
@@ -134,23 +143,44 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error)
return vols, false, nil
}
// ensureEnvelope makes the file in this version's envelope durable before
// the master serves anything, so a v1.0.x master started on this store
// afterwards refuses its whole start: it writes the envelope when the file is
// absent or in v1.0.x's form, and fsyncs an envelope already there (file and
// directory) on every start, since an earlier start may have renamed it in
// and then failed its directory fsync.
// level is the cluster's format level the file holds: 1 with the envelope,
// 0 with v1.0.x's form (or no file).
func (s *storeAttestations) level() uint32 {
s.mu.Lock()
defer s.mu.Unlock()
if s.enveloped {
return 1
}
return 0
}
// finalize writes the envelope durably (file and directory fsync): the one
// write that raises the cluster's format level to 1 and makes a v1.0.x
// master refuse this store. At level 1 it writes nothing (already true).
// On a failed write the level stays 0 in memory; the file may hold either
// form, and the next start reads whichever it holds.
func (s *storeAttestations) finalize() (already bool, err error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.enveloped {
return true, nil
}
s.enveloped = true
if err := s.persist(s.vols); err != nil {
s.enveloped = false
return false, err
}
return false, nil
}
// ensureEnvelope, at level 1, fsyncs the envelope (file and directory) at
// every start before the master serves anything, since an earlier start (or
// the finalize) may have renamed it in and then failed its directory fsync.
// At level 0 it does nothing: the file stays v1.0.x's form.
func (s *storeAttestations) ensureEnvelope() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.path == "" {
return nil
}
if !s.enveloped {
if err := s.persist(s.vols); err != nil {
return err
}
s.enveloped = true
if s.path == "" || !s.enveloped {
return nil
}
f, err := os.OpenFile(s.path, os.O_RDWR, 0)
@@ -437,7 +467,16 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
if s.path == "" {
return nil
}
payload, err := json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, Volumes: vols})
if vols == nil {
vols = map[string]attestedStores{}
}
var payload []byte
var err error
if s.enveloped {
payload, err = json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, FormatLevel: 1, Volumes: vols})
} else {
payload, err = json.Marshal(vols) // level 0: v1.0.x's form
}
if err != nil {
return err
}
@@ -220,6 +220,11 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) && s.host.colocatedTargetRefused(binding.ServerID) {
return nil, workspaceError(fmt.Errorf("workspace placement: node %q shares the authority store's file system (strict journal isolation)", binding.ServerID))
}
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) {
if why := s.host.formatTooOld(binding.ServerID); why != "" {
return nil, workspaceError(fmt.Errorf("workspace placement: %s", why))
}
}
err = s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error {
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok {
if identical(p) {
@@ -244,6 +249,14 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
// admitWorkspacePublication owns the last local boundary before an ordinary
// Publisher mint. Guarded Move already owns workspaceMu in its RPC path.
func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish func() error) error {
if hook := h.testPublicationAdmission; hook != nil {
return hook(ask, func() error { return h.admitWorkspacePublicationNow(ask, publish) })
}
return h.admitWorkspacePublicationNow(ask, publish)
}
// admitWorkspacePublicationNow is the publication admission itself.
func (h *Host) admitWorkspacePublicationNow(ask authority.AssignmentAsk, publish func() error) error {
// A volume's first bind records its initial replicas before the line
// exists, so its primary is never served without the wait.
if err := h.openStoreRecord(ask.VolumeID); err != nil {
@@ -272,6 +285,11 @@ func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish fu
epoch = line.Epoch
}
server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch)
// The format gate at the last boundary: an ask decided on observations
// taken before its server reported a lower read level is not published.
if why := h.formatTooOld(server); why != "" {
return fmt.Errorf("workspace publication: %s", why)
}
b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}
if bound {
matched := false
@@ -86,15 +86,16 @@ func TestLeaseRefusalKinds(t *testing.T) {
t.Fatal("first grant:", err)
}
// BARRIER: past the grant (TTL, 30 s) but before it plus the default
// skew (2/3 TTL), i.e. 50 s after the grant.
// BARRIER: past the grant (TTL, 30 s) but before the barrier. A fresh
// master is at format level 0, whose barrier is v1.0's: the persisted
// horizon (1.5 TTL) plus the default skew (2/3 TTL), 65 s after the grant.
nowNS.Add(int64(40 * time.Second))
text, r := refusalOf(t, "expired re-grant before the barrier", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }())
if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_BARRIER {
t.Fatalf("re-grant before the barrier: detail %v; want BARRIER", r)
}
if left := time.Duration(r.GetRetryAfterNs()); left < 9*time.Second || left > 11*time.Second {
t.Fatalf("BARRIER retry_after %v; want 10 s (the barrier 50 s after the grant, now +40 s)", left)
if left := time.Duration(r.GetRetryAfterNs()); left < 24*time.Second || left > 26*time.Second {
t.Fatalf("BARRIER retry_after %v; want 25 s (level 0: the barrier 65 s after the grant, now +40 s)", left)
}
if !strings.HasPrefix(text, "workspace forced move lease expiry plus clock-skew margin has not elapsed") || !strings.Contains(text, "re-grant refused until") {
t.Fatalf("BARRIER text %q: want the barrier text with its time", text)
@@ -455,6 +455,8 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho
// after these endpoint and binding checks, also for a same-host target.
case !replay && s.host.colocatedTargetRefused(target.ServerID):
refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
case !replay && s.host.formatTooOld(target.ServerID) != "":
refusal = "move target " + s.host.formatTooOld(target.ServerID)
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))
}
@@ -35,7 +35,8 @@ func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChun
// then) and is granted on the predecessor's unchanged HEAD. A late claim by
// the dead grantee never displaces the new owner's higher epoch.
func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
// The real lease (the 30 s TTL) plus skew takes ~50 s.
// The real lease horizon (1.5 x the 30 s TTL, format level 0) plus skew
// takes ~65 s.
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
@@ -114,8 +115,10 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking {
t.Fatalf("the issued move must start node-b's lease: %+v", st)
}
granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a") // the issue's deadline, not the record's
barrier := time.Unix(0, granted.ExpiresAtNS).Add(skew)
// The barrier at either format level: the later of the granted deadline
// and (level 0, v1.0's rule) the persisted horizon, plus skew.
granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a")
barrier := time.Unix(0, max(granted.ExpiresAtNS, st.Lease.ExpiresAtNS)).Add(skew)
if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee {
t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err)
}
+28 -14
View File
@@ -61,13 +61,16 @@ type ChunkCutResponse struct {
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
// step); every duration is in nanoseconds.
type ChunkCutStatsBody struct {
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
CandidateNs int64 `json:"candidateNs"`
WindowSetupNs int64 `json:"windowSetupNs"`
PublishPrepareNs int64 `json:"publishPrepareNs"`
ManifestNs int64 `json:"manifestNs"`
CommitStateNs int64 `json:"commitStateNs"`
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched
PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause
PauseCandidateOps int64 `json:"pauseCandidateOps"` // per-candidate operations done while the guest was paused
CandidateNs int64 `json:"candidateNs"`
WindowSetupNs int64 `json:"windowSetupNs"`
PublishPrepareNs int64 `json:"publishPrepareNs"`
ManifestNs int64 `json:"manifestNs"`
CommitStateNs int64 `json:"commitStateNs"`
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
PayloadNs int64 `json:"payloadNs"`
COWWALReadAttempts uint64 `json:"cowWALReadAttempts"`
@@ -111,13 +114,16 @@ type ChunkCutStatsBody struct {
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
return ChunkCutStatsBody{
SyncPhases: s.SyncPhases,
CandidateNs: s.CandidateNs,
WindowSetupNs: s.WindowSetupNs,
PublishPrepareNs: s.PublishPrepareNs,
ManifestNs: s.ManifestNs,
CommitStateNs: s.CommitStateNs,
NonPayloadCopyNs: s.NonPayloadCopyNs,
SyncPhases: s.SyncPhases,
CandidateVisits: s.CandidateVisits,
PreSyncNs: s.PreSyncNs,
PauseCandidateOps: s.PauseCandidateOps,
CandidateNs: s.CandidateNs,
WindowSetupNs: s.WindowSetupNs,
PublishPrepareNs: s.PublishPrepareNs,
ManifestNs: s.ManifestNs,
CommitStateNs: s.CommitStateNs,
NonPayloadCopyNs: s.NonPayloadCopyNs,
PayloadNs: s.PayloadNs,
COWWALReadAttempts: s.COWWALReadAttempts,
@@ -268,6 +274,11 @@ func (s *StatusServer) chunkMux() http.Handler {
// cut slot is held (retryable).
const codeHostSlotBusy = "host_slot_busy"
// codeInProgress: the upgrade compare pass after a v1.0 store's upgrade has
// not ended; the request is repeated later (the message carries the pass's
// progress; status reports it as Chunk.Stats.UpgradePass).
const codeInProgress = "in_progress"
func writeChunkJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
@@ -302,7 +313,10 @@ func writeChunkFailure(w http.ResponseWriter, err error) {
// a refused capture reports why it was refused.
func chunkErrorCode(err error) (int, string, bool) {
var ce *chunkstore.CatalogError
var pass *storage.ErrUpgradePassInProgress
switch {
case errors.As(err, &pass):
return http.StatusConflict, codeInProgress, true
case errors.Is(err, durable.ErrPlainDetachBusy):
return http.StatusConflict, "plain_detach_busy", true
case errors.Is(err, storage.ErrPrecopyUnknown):
@@ -338,3 +338,15 @@ func TestStatusServer_ChunkBodyIsOneJSONObject(t *testing.T) {
t.Fatalf("one object and a newline: %d %s", w.Code, w.Body)
}
}
// A request refused while the upgrade compare pass runs answers its own
// code, in_progress, retryable, also when wrapped.
func TestChunkErrorCodeUpgradePassInProgress(t *testing.T) {
refusal := &storage.ErrUpgradePassInProgress{Compared: 3, Total: 16, Cursor: 2}
for _, err := range []error{refusal, fmt.Errorf("cut: %w", refusal)} {
status, code, retryable := chunkErrorCode(err)
if status != http.StatusConflict || code != "in_progress" || !retryable {
t.Fatalf("%v: %d %q %v, want 409 in_progress retryable", err, status, code, retryable)
}
}
}
+6
View File
@@ -810,6 +810,11 @@ func (h *Host) runHeartbeat(ctx context.Context) {
}
}
// ReadsFormatLevel is the highest cluster format level this binary reads
// (the v1.1 format is level 1), reported on every heartbeat as reads_level:
// the master finalizes the format only when every registered host reads it.
const ReadsFormatLevel = 1
// buildReport collects local slot facts into a wire HeartbeatReport.
// T0 single-volume-per-process simplicity: one replica slot.
func (h *Host) buildReport() *control.HeartbeatReport {
@@ -825,6 +830,7 @@ func (h *Host) buildReport() *control.HeartbeatReport {
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
StoreAttestation: h.storeAttestation(),
ReadsLevel: ReadsFormatLevel,
Slots: []*control.HeartbeatSlot{
{
VolumeId: h.cfg.VolumeID,
+23 -9
View File
@@ -3,6 +3,7 @@ package hostlimit
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
@@ -468,6 +469,7 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) {
defer stalled.Close()
const skip, cut, poll = 500 * time.Millisecond, 50 * time.Millisecond, 20 * time.Millisecond
type admission struct {
worker int
due int64
at, done time.Time
}
@@ -518,7 +520,7 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) {
time.Sleep(cut)
l.Release(id)
mu.Lock()
log = append(log, admission{tk.Due(), at, time.Now()})
log = append(log, admission{i, tk.Due(), at, time.Now()})
mu.Unlock()
if tk, err = l.TakeTicket(HostNow()); err != nil { // the next cycle's cut
t.Error(err)
@@ -541,21 +543,33 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) {
if len(log) < 6 {
t.Fatalf("only %d admissions in 10 s", len(log))
}
// A hand-off that paid the stalled ticket's skip idles at least the skip
// window after the release; scheduling and the workers' poll idle far less,
// even on a loaded host. So the bound is the skip window itself, not a
// fixed fraction of it.
gaps := make([]time.Duration, 0, len(log))
// Each worker is its own limiter (its own process): it judges the stalled
// ticket on its own clock, which runs only while the slot is free, so a
// worker's FIRST admission may pay up to one skip window (a loaded host
// can start its clock late). The property is that no worker pays the skip
// again: a hand-off to a worker's later admission idles less than the skip
// window. The gaps are printed with the worker that took each slot.
gaps := make([]string, 0, len(log))
for i := 1; i < len(log); i++ {
gaps = append(gaps, log[i].at.Sub(log[i-1].done).Round(time.Millisecond))
gaps = append(gaps, fmt.Sprintf("w%d:%s", log[i].worker, log[i].at.Sub(log[i-1].done).Round(time.Millisecond)))
}
admitted := map[int]bool{log[0].worker: true}
later := 0 // hand-offs to a worker's later admission: the ones the bound checks
for i := 1; i < len(log); i++ {
if log[i].due <= log[i-1].due {
t.Fatalf("admissions out of due order at %d", i)
}
if gap := log[i].at.Sub(log[i-1].done); gap >= skip {
t.Fatalf("hand-off %d idled %s after the release, at least the skip window (%s): one stalled ticket must not cost every hand-off a skip (hand-off gaps %v)", i, gap.Round(time.Millisecond), skip, gaps)
first := !admitted[log[i].worker]
admitted[log[i].worker] = true
if !first {
later++
}
if gap := log[i].at.Sub(log[i-1].done); gap >= skip && !first {
t.Fatalf("hand-off %d to worker %d's later admission idled %s after the release, at least the skip window (%s): one stalled ticket must cost each worker one skip at most (hand-off gaps %v)", i, log[i].worker, gap.Round(time.Millisecond), skip, gaps)
}
}
if later == 0 {
t.Fatalf("no hand-off went to a worker's later admission, so the bound checked nothing (hand-off gaps %v)", gaps)
}
}
File diff suppressed because it is too large. Load diff
@@ -790,6 +790,8 @@ const (
LifecycleService_CommitVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/CommitVolumeDeleting"
LifecycleService_ReserveVolumeDeletion_FullMethodName = "/seaweedfs.block.control.LifecycleService/ReserveVolumeDeletion"
LifecycleService_CheckVolumeNoLiveLease_FullMethodName = "/seaweedfs.block.control.LifecycleService/CheckVolumeNoLiveLease"
LifecycleService_FinalizeFormat_FullMethodName = "/seaweedfs.block.control.LifecycleService/FinalizeFormat"
LifecycleService_RetireHost_FullMethodName = "/seaweedfs.block.control.LifecycleService/RetireHost"
)
// LifecycleServiceClient is the client API for LifecycleService service.
@@ -821,6 +823,20 @@ type LifecycleServiceClient interface {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
CheckVolumeNoLiveLease(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error)
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
FinalizeFormat(ctx context.Context, in *FinalizeFormatRequest, opts ...grpc.CallOption) (*FinalizeFormatResponse, error)
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
RetireHost(ctx context.Context, in *RetireHostRequest, opts ...grpc.CallOption) (*RetireHostResponse, error)
}
type lifecycleServiceClient struct {
@@ -903,6 +919,24 @@ func (c *lifecycleServiceClient) CheckVolumeNoLiveLease(ctx context.Context, in
return out, nil
}
func (c *lifecycleServiceClient) FinalizeFormat(ctx context.Context, in *FinalizeFormatRequest, opts ...grpc.CallOption) (*FinalizeFormatResponse, error) {
out := new(FinalizeFormatResponse)
err := c.cc.Invoke(ctx, LifecycleService_FinalizeFormat_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *lifecycleServiceClient) RetireHost(ctx context.Context, in *RetireHostRequest, opts ...grpc.CallOption) (*RetireHostResponse, error) {
out := new(RetireHostResponse)
err := c.cc.Invoke(ctx, LifecycleService_RetireHost_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LifecycleServiceServer is the server API for LifecycleService service.
// All implementations must embed UnimplementedLifecycleServiceServer
// for forward compatibility
@@ -932,6 +966,20 @@ type LifecycleServiceServer interface {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error)
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
FinalizeFormat(context.Context, *FinalizeFormatRequest) (*FinalizeFormatResponse, error)
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
RetireHost(context.Context, *RetireHostRequest) (*RetireHostResponse, error)
mustEmbedUnimplementedLifecycleServiceServer()
}
@@ -963,6 +1011,12 @@ func (UnimplementedLifecycleServiceServer) ReserveVolumeDeletion(context.Context
func (UnimplementedLifecycleServiceServer) CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CheckVolumeNoLiveLease not implemented")
}
func (UnimplementedLifecycleServiceServer) FinalizeFormat(context.Context, *FinalizeFormatRequest) (*FinalizeFormatResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method FinalizeFormat not implemented")
}
func (UnimplementedLifecycleServiceServer) RetireHost(context.Context, *RetireHostRequest) (*RetireHostResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RetireHost not implemented")
}
func (UnimplementedLifecycleServiceServer) mustEmbedUnimplementedLifecycleServiceServer() {}
// UnsafeLifecycleServiceServer may be embedded to opt out of forward compatibility for this service.
@@ -1120,6 +1174,42 @@ func _LifecycleService_CheckVolumeNoLiveLease_Handler(srv interface{}, ctx conte
return interceptor(ctx, in, info, handler)
}
func _LifecycleService_FinalizeFormat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FinalizeFormatRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LifecycleServiceServer).FinalizeFormat(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: LifecycleService_FinalizeFormat_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LifecycleServiceServer).FinalizeFormat(ctx, req.(*FinalizeFormatRequest))
}
return interceptor(ctx, in, info, handler)
}
func _LifecycleService_RetireHost_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetireHostRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LifecycleServiceServer).RetireHost(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: LifecycleService_RetireHost_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LifecycleServiceServer).RetireHost(ctx, req.(*RetireHostRequest))
}
return interceptor(ctx, in, info, handler)
}
// LifecycleService_ServiceDesc is the grpc.ServiceDesc for LifecycleService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1159,6 +1249,14 @@ var LifecycleService_ServiceDesc = grpc.ServiceDesc{
MethodName: "CheckVolumeNoLiveLease",
Handler: _LifecycleService_CheckVolumeNoLiveLease_Handler,
},
{
MethodName: "FinalizeFormat",
Handler: _LifecycleService_FinalizeFormat_Handler,
},
{
MethodName: "RetireHost",
Handler: _LifecycleService_RetireHost_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "control.proto",
@@ -16,6 +16,16 @@ const (
// names chunks of a volume other than its source (a restore target's
// snapshot cannot be restored again).
ReasonRestoreSourceNotOwn = "RESTORE_SOURCE_NOT_OWN"
// ReasonBinaryTooOld: the caller's binary does not read the cluster's
// format level (its heartbeat's reads_level is below it), so the master
// refuses it and gives it no work.
ReasonBinaryTooOld = "BINARY_TOO_OLD"
// ReasonFormatHostsTooOld: the format finalize was refused because a
// registered host has not reported that it reads the new level.
ReasonFormatHostsTooOld = "FORMAT_HOSTS_TOO_OLD"
// ReasonHostHoldsWork: a host retire was refused because the host still
// holds a lease or an assignment for a volume.
ReasonHostHoldsWork = "HOST_HOLDS_WORK"
)
// WithReason returns st with an ErrorInfo detail carrying reason in
@@ -119,6 +119,38 @@ service LifecycleService {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
rpc CheckVolumeNoLiveLease(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse);
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
rpc FinalizeFormat(FinalizeFormatRequest) returns (FinalizeFormatResponse);
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
rpc RetireHost(RetireHostRequest) returns (RetireHostResponse);
}
message FinalizeFormatRequest {
uint32 level = 1; // the level to finalize: 1
}
message FinalizeFormatResponse {
uint32 format_level = 1;
bool already = 2; // the cluster was already at this level: nothing written
}
message RetireHostRequest {
string server_id = 1;
string confirm = 2; // must equal server_id
}
message RetireHostResponse {
string server_id = 1;
}
// FailbackService — disabled-by-default authority failback endpoint.
@@ -156,6 +188,12 @@ message HeartbeatReport {
// the server that holds the volume's current primary line at that
// epoch. A replica's own report of its store never sets it.
StoreAttestation store_attestation = 9;
// reads_level is the highest cluster format level the reporting
// binary reads: 1 for a binary that reads the v1.1 format. A v1.0.x
// binary sends none (0). The master finalizes the cluster's format only
// when every registered host reports at least the new level, and places,
// moves and fails volumes over only to hosts that read the current one.
uint32 reads_level = 10;
}
// StoreAttestation is a primary's attestation of its write-ACK set at one
@@ -329,6 +367,11 @@ message AssignmentFact {
// is another one does not serve: a later failover reads its
// acknowledged writes by this profile's rules.
string ack_profile = 18;
// The cluster's format level (0 until the operator finalizes the v1.1
// format, then 1). A holder upgrades a store and writes the v1.1 format
// only at level 1; absent (an older master, or no assignment yet) means
// level 0.
uint32 format_level = 19;
}
// PrimaryKind is how a line made its primary the primary.
@@ -656,6 +656,9 @@ func (s *WALStore) markMapUnknownV3(lba uint64) {
}
e.LSN = max(e.LSN, birth)
v.mapEntries.set(index, e)
if h := s.chunk.Load(); h != nil {
h.sink.OnMapEntryChange(uint64(index))
}
}
// InstalledBaseLSN reports a completed local BASE obligation, not a normal
@@ -0,0 +1,372 @@
package storage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"path/filepath"
"testing"
"time"
)
// The guest pause does O(1) work: a cut's first barrier after writes to many
// chunks does no per-candidate operation between the barrier's lock and its
// release (counted, not timed), at 32 blocks and at the 1 TiB shape with
// 256 changed chunks. The candidates are judged, versioned and based after
// the pause, under the copy window.
func TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause(t *testing.T) {
t.Run("small", func(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks == 0 || r.Stats.PauseCandidateOps != 0 {
t.Fatalf("first cut over %d candidates: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, r.Stats.PauseCandidateOps)
}
})
t.Run("one-TiB-shape", func(t *testing.T) {
const n, changed = 262144, 256
s, l := freshShape(t, n)
for i := 0; i < changed; i++ {
if _, err := s.Write(uint32(i*997%n), []byte(fmt.Sprintf("%-512d", i))); err != nil {
t.Fatal(err)
}
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks < changed || r.Stats.PauseCandidateOps != 0 {
t.Fatalf("first cut over %d candidates of %d chunks: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, n, r.Stats.PauseCandidateOps)
}
})
}
// A layer's first cut finds its touched sets ready: the barrier only swaps
// them; no set is allocated in the pause (size-dependent work).
func TestAColdFirstCutAllocatesNoSetInThePause(t *testing.T) {
const n = 262144
s, l := freshShape(t, n)
if _, err := s.Write(3, []byte(fmt.Sprintf("%-512s", "cold"))); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("a layer's first cut over %d chunks did %d size-dependent operations in the pause, want 0", n, r.Stats.PauseCandidateOps)
}
}
// A recovery that lands between a cut's pre-barrier work and its barrier
// moves every clean fill's version: the cut still judges those fills (their
// proofs are gone), after the pause, and the pause does no per-fill work.
func TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause(t *testing.T) {
_, l, _ := filledFreshVolume(t)
l.stMu.Lock()
fills := len(l.filledClean)
l.stMu.Unlock()
if fills == 0 {
t.Fatal("setup: no clean fills")
}
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() }
r, err := l.Cut(ctTimeout(t))
l.testBeforeBarrierLockHook = nil
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("a recovery just before the barrier cost %d per-fill operations in the pause, want 0", r.Stats.PauseCandidateOps)
}
if r.Stats.CandidateChunks < fills {
t.Fatalf("the cut after the recovery judged %d candidates, want all %d clean fills (their proofs are gone)", r.Stats.CandidateChunks, fills)
}
}
// A reader of the candidates (status, pre-copy, the shadow) running beside
// cuts and recoveries never charges its work to a cut's pause nor touches the
// capture's pause accounting: run with -race, the schedule (a reader that
// can consume a recovery's request while a cut enters its barrier) has no
// race, and every cut's pause does no per-candidate work.
func TestAReaderBesideCutsAndRecoveriesIsNotChargedToThePause(t *testing.T) {
_, l, _ := filledFreshVolume(t)
stop := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-stop:
return
default:
}
_ = l.captureCandidates() // the readers' path: peekTouched, resolveTouchFilled
}
}()
defer func() {
close(stop)
select {
case <-done:
case <-time.After(ctLocalBound):
t.Error("the reader did not stop")
}
}()
for i := 0; i < 20; i++ {
l.noteAllMutated() // a recovery the reader may consume first
if i%2 == 1 {
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } // or one just before the barrier
}
r, err := l.Cut(ctTimeout(t))
l.testBeforeBarrierLockHook = nil
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("cut %d: %d per-candidate operations charged to the pause beside a reader", i, r.Stats.PauseCandidateOps)
}
}
}
// A fill whose fetch outlives a same-open recovery installs HEAD's bytes but
// no clean mark (the recovery moved the chunk's version), so the chunk is a
// candidate again, as the full scan says; the absent-to-present install
// touches it. (The package's candidate oracle checks the cut's barrier too.)
func TestAFillThatOutlivesARecoveryMakesItsChunkACandidate(t *testing.T) {
s, l, remote, _ := hydrationFixture(t, 2, 64)
// The engine's predicate is what is checked here. The chunk record names
// such a chunk HashPublished (the fill verified HEAD's hash), so the
// engine's conservative candidate is an extra to the record's shadow, as
// it was with the full scan: the shadow is off for this schedule.
l.shadow = nil
entered, release := holdGets(t, remote)
defer release()
read := make(chan error, 1)
go func() {
_, err := s.Read(0)
read <- err
}()
select {
case <-entered:
case <-time.After(ctLocalBound):
t.Fatal("the read miss never reached the remote")
}
if l.captureCandidates()[0] {
t.Fatal("setup: the absent chunk is already a candidate")
}
l.noteAllMutated() // a same-open recovery, while the fetch is held
release()
select {
case err := <-read:
if err != nil {
t.Fatal(err)
}
case <-time.After(ctLocalBound):
t.Fatal("the read did not complete")
}
l.stMu.Lock()
absent, marked := l.absent[0], l.filledClean[0] != (filledMark{})
l.stMu.Unlock()
if absent || marked {
t.Fatalf("setup: after the fill, absent=%v clean-marked=%v; want present without a mark", absent, marked)
}
if !l.captureCandidates()[0] {
t.Fatal("a chunk filled across a recovery, present without a clean mark, is not a candidate")
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
}
// freshShape attaches a lazy fresh-from-HEAD layer over n one-block chunks
// (512-byte blocks), every chunk named by HEAD and absent locally, as the
// SPACE test builds the 1 TiB shape (n = 262,144).
func freshShape(t *testing.T, n int) (*WALStore, *chunkLayerImpl) {
t.Helper()
const bs = 512
f := newFakeChunkRemote()
head := chunkHead{Epoch: 1, Holder: "seed", RemoteLSN: 10, Chunks: make(map[uint64]chunkRef, n)}
for i := 0; i < n; i++ {
data := make([]byte, bs)
binary.LittleEndian.PutUint64(data, uint64(i)+1)
key := fmt.Sprintf("seed/%d", i)
f.objs[key] = data
f.everStored[key] = true
head.Chunks[uint64(i)] = chunkRef{Key: key, SHA256: sha256.Sum256(data), Encoding: "full"}
}
f.mu.Lock()
f.installLocked(head)
f.mu.Unlock()
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), uint32(n), bs, WALStoreOptions{ChunkBlocks: 1})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { closeBounded(t, s) })
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "host-a", Bitmap: newFakeBitmap(), ReadMissTimeout: ctLocalBound, FreshFromHead: true}
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
// Publishing a write to an absent chunk of a fresh-from-HEAD layer makes
// the chunk record refuse its Commit (U/Commit), with or without the
// candidate set; that record question is apart from what these tests
// count, so the shadow is off for this shape.
l.shadow = nil
return s, l
}
// visitBound is the candidate step's allowance for a cut with changed chunks
// at n chunks: the changed chunks plus one summary word per 4,096 chunks,
// and a small constant.
func visitBound(changed, n int) int64 { return int64(changed + n/4096 + 16) }
// An idle cut's candidate step does work flat in S: at the 1 TiB shape it
// visits no more chunk indices than at 4,096 chunks (counted, not timed).
func TestIdleCutCandidateWorkIsFlatInS(t *testing.T) {
for _, n := range []int{4096, 262144} {
t.Run(fmt.Sprintf("chunks-%d", n), func(t *testing.T) {
s, l := freshShape(t, n)
if _, err := s.Write(0, make([]byte, 512)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if got, max := r.Stats.CandidateVisits, visitBound(0, n); got > max {
t.Fatalf("an idle cut over %d chunks visited %d chunk indices in its candidate step, want <= %d", n, got, max)
}
})
}
}
// A cut with one changed chunk at the 1 TiB shape scans no chunk map: its
// candidate step visits the changed chunk and the summary words only.
func TestOneChangedChunkCutVisitsNoFullScan(t *testing.T) {
const n = 262144
s, l := freshShape(t, n)
if _, err := s.Write(0, make([]byte, 512)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if _, err := s.Write(7*1, []byte(fmt.Sprintf("%-512s", "changed"))); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if got, max := r.Stats.CandidateVisits, visitBound(1, n); got > max {
t.Fatalf("a one-chunk cut over %d chunks visited %d chunk indices, want <= %d", n, got, max)
}
}
// The cut syncs the store before its barrier, outside the guest pause, so
// the pause's own sync has only what came after; the pre-sync's time is
// reported apart from the pause.
func TestCutSyncsBeforeItsBarrier(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
before := s.syncs.Load()
var atLock uint64
l.testBeforeBarrierLockHook = func() { atLock = s.syncs.Load() }
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if after := s.syncs.Load(); after <= atLock {
t.Fatalf("the counter missed the pause's own sync (%d then %d): the measure is wrong", atLock, after)
}
if atLock <= before {
t.Fatalf("no store sync between the cut's start and its barrier (sync count %d then %d): the pause syncs the whole fill", before, atLock)
}
}
// A cut whose commit outcome is unknown (and did not land) loses no chunk:
// its captured chunks, and a write made after it, are all published by the
// next cut, and no other chunk changes.
func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
base := f.imageOf(t, f.stats().head) // the remote's full image, any format
w.write(t, s, 0*ctChunkBlocks, 0xa0) // chunk 0
w.write(t, s, 2*ctChunkBlocks, 0xa2) // chunk 2
f.mu.Lock()
f.casModes = []fakeCASMode{casUnknownNotApplied}
f.mu.Unlock()
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("the injected cut answered %v, want its outcome unknown", err)
}
w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
var err error
var last chunkCutResult
for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish
if last, err = l.Cut(ctTimeout(t)); err == nil && !last.Noop {
break
}
}
if err != nil {
t.Fatal(err)
}
img := f.imageOf(t, f.stats().head)
chunkBytes := ctChunkBlocks * ctBlockSize
for idx := 0; idx < ctNumBlocks/ctChunkBlocks; idx++ {
at := idx * chunkBytes
changed := !bytes.Equal(img[at:at+chunkBytes], base[at:at+chunkBytes])
want := idx == 0 || idx == 2 || idx == 5
if changed != want {
t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want)
}
}
}
// The candidate set's OR keeps the summary, so a set ORed back is listed in
// full; each lists exactly the set bits.
func TestCandidateSetOrBackKeepsTheSummary(t *testing.T) {
const n = 64 * 64 * 3
taken, live := newCandidateSet(n), newCandidateSet(n)
want := []uint64{1, 64*64 + 5, n - 1}
for _, c := range want {
taken.set(c)
}
live.set(7)
live.or(taken)
var got []uint64
live.each(func(c uint64) { got = append(got, c) })
exp := []uint64{1, 7, 64*64 + 5, n - 1}
if fmt.Sprint(got) != fmt.Sprint(exp) || live.Len() != len(exp) {
t.Fatalf("after OR-back the set lists %v (len %d), want %v", got, live.Len(), exp)
}
live.clear()
got = nil
live.each(func(c uint64) { got = append(got, c) })
if len(got) != 0 || live.Len() != 0 {
t.Fatalf("a cleared set lists %v", got)
}
}
+102 -29
View File
@@ -106,6 +106,10 @@ type cutCOWEntry struct {
// were captured: their image at H is HEAD's, filled by the copier from the
// cut's base HEAD after it released the entry (never under a guest write).
missing []uint64
// version is the chunk's mutation version when a guest write's save
// claimed the entry: the version of the bytes it saves (the write's own
// version move comes after its mutation).
version uint64
}
type cutCOWWindow struct {
layer *chunkLayerImpl
@@ -137,6 +141,19 @@ type cutCOWWindow struct {
saveNs atomic.Int64
waitNs atomic.Int64
// Scheduling/fault controls are nil in production and set before installation.
// entries (above) are made on a chunk's first touch (a guest write's
// save, or the copier), never at the barrier: the window covers cand, the
// cut's candidate set (immutable once installed), and staged marks the
// ones a pre-copy already holds. nextSlot hands out side-file slots in
// touch order. The barrier's work is O(1), not one entry per candidate.
cand map[uint64]bool
staged map[uint64]bool
nextSlot int64
// covers is the window's reach from the barrier until narrow sets cand:
// the sets the barrier took (O(1) a lookup), a superset of the
// candidates, judged after the pause.
covers func(uint64) bool
}
func (s *WALStore) beforeChunkMutation(first, count uint64) {
@@ -200,12 +217,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() {
}
// The caller owns captureMu exclusive, so no writer can miss this publication.
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) {
func (l *chunkLayerImpl) installCOWWindow(covers func(uint64) bool, spill cowSpillCap) (*cutCOWWindow, error) {
size := uint64(l.blockSize) * l.chunkBlocks
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
if size == 0 || size > math.MaxInt64 || l.numChunks > math.MaxInt64/size {
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), covers: covers, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
w.ctx, w.cancel = context.WithCancel(context.Background())
_, reserved, limit := l.cutPayloadWorkers()
savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size))))
@@ -214,15 +231,6 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he
reserved += int64(2*savers) * int64(size)
w.memory, w.memoryLimit = reserved, limit
w.saverSlots = make(chan struct{}, savers)
var slot int64
for _, idx := range sortedKeys(candidates) {
state := cowPending
if staged[idx] {
state = cowDone
}
w.entries[idx] = &cutCOWEntry{state: state, ready: make(chan struct{}), slot: slot}
slot++
}
l.cowMu.Lock()
defer l.cowMu.Unlock()
if l.cowClosed || l.cowTransitions != 0 {
@@ -266,7 +274,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
if w.terminal {
return nil, cowDone, nil
}
e := w.entries[idx]
e := w.entryLocked(idx)
if e == nil {
return nil, cowDone, nil
}
@@ -277,6 +285,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
case cowPending:
if saving {
e.state = cowSaving
e.version = w.layer.chunkVersion(idx) // before the write's own move
} else {
e.state = cowCopying
}
@@ -302,6 +311,57 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
return nil, cowDone, nil
}
}
// entryLocked is idx's entry, made on its first touch: nil when the window
// does not cover idx, done when a pre-copy holds it. Caller holds w.mu.
func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry {
if e := w.entries[idx]; e != nil {
return e
}
if w.cand != nil {
if !w.cand[idx] {
return nil
}
} else if w.covers == nil || !w.covers(idx) {
return nil
}
state := cowPending
if w.staged[idx] {
state = cowDone
}
e := &cutCOWEntry{state: state, ready: make(chan struct{}), slot: w.nextSlot}
w.nextSlot++
w.entries[idx] = e
return e
}
// versionAt is chunk idx's version at the barrier, read atomically with the
// write path: the version a guest write's save recorded with the bytes it
// saved, else the live version, read under w.mu so no writer can claim the
// entry (and move the version) in between.
func (w *cutCOWWindow) versionAt(idx uint64) uint64 {
w.mu.Lock()
defer w.mu.Unlock()
if e := w.entries[idx]; e != nil {
e.mu.Lock()
state, v := e.state, e.version
e.mu.Unlock()
if state == cowSaving || state == cowSaved {
return v
}
}
return w.layer.chunkVersion(idx)
}
// narrow sets the window's final reach after the candidates are judged (and
// versioned): the candidates, the staged ones a pre-copy holds, and the cut's
// base HEAD for missing blocks. Entries already made stay as they are.
func (w *cutCOWWindow) narrow(cand, staged map[uint64]bool, head map[uint64]chunkRef) {
w.mu.Lock()
w.cand, w.staged, w.head, w.covers = cand, staged, head, nil
w.mu.Unlock()
}
func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool {
w.mu.Lock()
defer w.mu.Unlock()
@@ -613,6 +673,18 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
// Each worker owns one immutable image from local read through remote Put.
// Once copied, its entry is done: guest writes need not wait for remote I/O.
// The window remains installed for candidates not yet read by a worker.
// endCOWWindow ends a window: abort, join its savers, and unpublish it.
func (l *chunkLayerImpl) endCOWWindow(w *cutCOWWindow) {
w.abort(errCutCOWAborted)
w.join()
l.cowMu.Lock()
if l.cow == w {
l.cow = nil
l.cowActive.Store(nil)
}
l.cowMu.Unlock()
}
func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, error) {
parent := ctx
abortStop := context.AfterFunc(parent, func() { w.abort(parent.Err()) })
@@ -621,25 +693,26 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec
stop := context.AfterFunc(w.ctx, cancel)
defer stop()
defer cancel()
defer func() {
w.abort(errCutCOWAborted)
w.join()
l.cowMu.Lock()
if l.cow == w {
l.cow = nil
l.cowActive.Store(nil)
defer l.endCOWWindow(w)
// The copier's work: every covered chunk a pre-copy does not hold and no
// touch has finished. Outside the pause (writers are back), O(candidates).
indices := make(map[uint64]bool, len(w.cand))
w.mu.Lock()
for idx := range w.cand {
if w.staged[idx] {
continue
}
l.cowMu.Unlock()
}()
indices := make(map[uint64]bool, len(w.entries))
for idx, e := range w.entries {
e.mu.Lock()
done := e.state == cowDone
e.mu.Unlock()
if !done {
indices[idx] = true
if e := w.entries[idx]; e != nil {
e.mu.Lock()
done := e.state == cowDone
e.mu.Unlock()
if done {
continue
}
}
indices[idx] = true
}
w.mu.Unlock()
order := hotChunkKeys(indices, recent)
out, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) {
c, ok, err := l.copyCOWEntry(w, idx)
@@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) {
for i := 0; i < candidates; i++ {
pending[uint64(i)] = true
}
w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit())
w, err := l.installCOWWindow(func(i uint64) bool { return pending[i] }, l.cowSpillLimit())
if err != nil {
t.Fatal(err)
}
@@ -1130,6 +1130,33 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) {
}
time.Sleep(time.Millisecond)
}
// An attach after an unclean v1.0 upgrade runs the compare pass, and
// cuts are refused until it ends; contract tests start after it, unless
// the test acts while it runs (withoutPassWait).
if skipPassWaitForTest {
return
}
// The pass reads every unknown chunk: a large test volume (262,144
// chunks) takes seconds, so its bound is its own.
passDeadline := time.Now().Add(2 * time.Minute)
for layer.Stats().UpgradePass.State == "running" {
if time.Now().After(passDeadline) {
t.Fatalf("upgrade compare pass still running after 2m: %+v", layer.Stats().UpgradePass)
}
time.Sleep(time.Millisecond)
}
}
// skipPassWaitForTest: the test attaches and acts while the upgrade compare
// pass runs (withoutPassWait).
var skipPassWaitForTest bool
// withoutPassWait makes the attach helpers return without waiting for the
// upgrade compare pass, for a test that acts while it runs.
func withoutPassWait(t *testing.T) {
t.Helper()
skipPassWaitForTest = true
t.Cleanup(func() { skipPassWaitForTest = false })
}
// crashOwnedMap closes the owned-map file of a crashed store without
+513 -91
View File
@@ -182,6 +182,29 @@ type chunkLayerImpl struct {
// own names the chunks OwnBatch re-uploads under this layer's own keys in
// the cut it runs (set and cleared under capMu, read under stMu).
own map[uint64]bool
// paused is set from a capture's barrier lock to its release, and
// pauseOps counts per-candidate operations done meanwhile (pauseOp);
// both are touched only by the capturing goroutine.
paused bool
pauseOps int64
// touched holds the chunks whose candidacy may have changed since a
// capture last took them: a map entry change (OnMapEntryChange), a HEAD
// ref change of a clean fill, and, once per layer, every entry UNKNOWN
// or above remoteLSN (seedTouched). The candidate step judges only these
// members against the same predicate the map scan used, so it never
// walks the map; the barrier takes the set whole. unkMu is a leaf lock.
// The set is a chunk bitmap with a per-word summary (candidateSet: 1 bit
// a chunk, 32 KiB at 1 TiB), and touchedSpare is its cleared twin, so
// the barrier's take is a pointer swap.
unkMu sync.Mutex
touched *candidateSet
touchedSpare *candidateSet
touchedSeed sync.Once // the once-per-layer seed (seedTouched)
// touchFilled asks the next set user to touch every clean fill: a
// recovery moved every chunk's version (noteAllMutated), ending their
// knownEqual proofs, at a point that may hold the layer's locks.
touchFilled atomic.Bool
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkMut counts the mutations of each chunk: every dirty-map insert
@@ -232,6 +255,16 @@ type chunkLayerImpl struct {
// shadow is the chunk record driven beside the maps above (set at
// attach, before the hooks publish; nil only in a layer built by hand).
shadow *chunkRecordShadow
// pass is the upgrade compare pass when the store needs one (nil: none);
// passStatus is the state reported without one; passErr latches a pass
// that stopped on an error; passHurry hurries it once a request waits.
// pass, passStatus and passErr are guarded by stMu.
pass *upgradePass
passStatus UpgradePassStatus
passErr error
passHurry sync.Once
// passSuperseded counts chunks written during their own compare.
passSuperseded atomic.Uint64
// testShadowCheck receives each barrier's misses and extra record
// candidates; set, it also makes the barrier collect the extras.
testShadowCheck func(miss, extra []uint64)
@@ -378,7 +411,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.cancel()
return nil, err
}
upgradedNow := false
if chunkV11Format {
marked, _ := s.ChunkStateMarker()
upgradedNow = !marked
l.shadow, err = l.openChunkRecordV11()
} else {
l.shadow, err = newChunkRecordShadow(l)
@@ -387,6 +423,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.cancel()
return nil, err
}
if err := l.prepareUpgradePass(upgradedNow); err != nil {
l.cancel()
return nil, fmt.Errorf("storage: chunk layer attach: upgrade compare pass: %w", err)
}
hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated}
hooks.baseTransitionV3 = l.holdBaseTransitionV3
@@ -403,9 +443,13 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
return nil, err
}
if sh := l.shadow; sh != nil && sh.v11 {
if h := dueLoopStartTestHook; h != nil {
h()
}
l.wg.Add(1)
go l.writeDueLoop(l.ctx, sh)
}
l.runUpgradePass()
// Every later drain reaches OnExtentWrite: release a held drain.
s.drainHeld.Store(false)
if s.flusher != nil {
@@ -464,6 +508,7 @@ func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) {
func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
if !chunkV11Format {
l.head, l.refs = h, nil
l.touchRefChangedLocked()
return
}
if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks {
@@ -472,6 +517,162 @@ func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
l.refs.fillAll(h.Chunks)
h.Chunks = nil
l.head = h
l.touchRefChangedLocked()
}
// touchRefChangedLocked adds to the touched set every clean fill whose HEAD
// ref no longer matches its mark (a whole HEAD install): its knownEqual
// proof is gone, so the next candidate step must judge it. Caller holds stMu.
func (l *chunkLayerImpl) touchRefChangedLocked() {
var gone []uint64
for idx, m := range l.filledClean {
if l.headChunk(idx) != m.ref {
gone = append(gone, idx)
}
}
l.touch(gone...)
}
// resolveTouchFilled touches every clean fill if a recovery asked for it.
// The caller holds neither stMu nor WALStore.mu. byCapture is true only on
// the capturing goroutine: the pause accounting (paused, pauseOps) is its
// own, so a reader's work (status, pre-copy, the shadow) is never charged to
// a cut nor touches those fields.
func (l *chunkLayerImpl) resolveTouchFilled(byCapture bool) {
if !l.touchFilled.Swap(false) {
return
}
l.stMu.Lock()
filled := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
filled = append(filled, idx)
}
l.stMu.Unlock()
if byCapture {
l.pauseOp(len(filled))
}
l.touch(filled...)
}
// newTouchedSet allocates a touched set (its words and summary: size
// dependent, counted as pause work when the capturing goroutine allocates it
// while the guest is paused).
func (l *chunkLayerImpl) newTouchedSet(byCapture bool) *candidateSet {
if byCapture {
l.pauseOp(int(l.numChunks/64) + 1)
}
return newCandidateSet(l.numChunks)
}
// candidateOracle, when set (by this package's tests), receives every chunk
// the full predicate scan finds that a barrier's touched-set candidate step
// missed. Production leaves it nil: the scan is O(chunks).
var candidateOracle func(string)
// candidateOracleScan is the oracle's half at the barrier (tests only, nil
// in production, never counted as pause work): the full scan of the old
// candidate step, the chunks it would make candidates now.
func (l *chunkLayerImpl) candidateOracleScan() map[uint64]bool {
if candidateOracle == nil {
return nil
}
l.stMu.Lock()
base := l.remoteLSN
l.stMu.Unlock()
want := map[uint64]bool{}
l.s.mu.RLock()
defer l.s.mu.RUnlock()
l.stMu.Lock()
defer l.stMu.Unlock()
pendingFilled := l.touchFilled.Load()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
i := uint64(idx)
if l.absent[i] && !l.chunkHasLocalLocked(i) {
continue
}
e := l.s.v3.mapEntries.at(idx)
if (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
if pendingFilled && l.filledClean[i] != (filledMark{}) {
continue // a recovery's touches are pending: the next cut's
}
want[i] = true
}
}
return want
}
// candidateOracleCompare is the oracle's half after the judgement: a chunk
// the barrier's full scan makes a candidate that the judged candidates miss
// is a finding.
func candidateOracleCompare(want, got map[uint64]bool) {
report := candidateOracle
if report == nil {
return
}
for i := range want {
if !got[i] {
report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan at the barrier but not by the judged touched set", i))
return
}
}
}
// requeueTaken returns a cut's taken sets when it ends before judging them
// (a refusal in or right after the pause): the touched members are touched
// again, the dirty set rejoins l.dirty, and a BASE write's allDirty stays.
func (l *chunkLayerImpl) requeueTaken(taken *candidateSet, dirty map[uint64]bool, all bool) {
var back []uint64
taken.each(func(c uint64) { back = append(back, c) })
l.touch(back...)
l.returnTouched(taken)
l.stMu.Lock()
for idx := range dirty {
l.dirty[idx] = true
}
if all {
l.allDirty = true
}
l.dirtyVer++
l.stMu.Unlock()
}
// writtenSinceTake reports whether chunk idx was touched since the barrier
// took the set: a write after the barrier (the live set holds it).
func (l *chunkLayerImpl) writtenSinceTake(idx uint64) bool {
l.unkMu.Lock()
defer l.unkMu.Unlock()
return l.touched != nil && idx < l.numChunks && l.touched.has(idx)
}
// pauseOp counts n per-candidate operations if the guest is paused.
func (l *chunkLayerImpl) pauseOp(n int) {
if l.paused {
l.pauseOps += int64(n)
}
}
// touch adds chunks to the touched set (leaf lock).
func (l *chunkLayerImpl) touch(chunks ...uint64) {
if len(chunks) == 0 {
return
}
l.unkMu.Lock()
set := l.touchedLocked(false) // any goroutine
for _, c := range chunks {
if c < l.numChunks {
set.set(c)
}
}
l.unkMu.Unlock()
}
// touchedLocked is the live touched set, made on first use. Caller holds
// unkMu; byCapture as in resolveTouchFilled.
func (l *chunkLayerImpl) touchedLocked(byCapture bool) *candidateSet {
if l.touched == nil {
l.touched = l.newTouchedSet(byCapture)
}
return l.touched
}
// readAttachHead reads HEAD at attach and installs it. On the v1.1 format,
@@ -570,6 +771,92 @@ func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool {
// ---- sink callbacks ----
// OnMapEntryChange is O(1): it only marks memory, under the leaf unkMu.
func (l *chunkLayerImpl) OnMapEntryChange(chunk uint64) { l.touch(chunk) }
// seedTouched adds, once per layer, every chunk whose map entry is UNKNOWN
// or above remoteLSN now (writes a restart left behind, which no
// OnExtentWrite of this layer saw). It runs on the set's first use: before
// the first capture's barrier (outside the guest pause), or at an earlier
// reader. An entry that turns UNKNOWN later arrives through OnMapEntryChange,
// which may already have run (the set is a union). The caller holds neither
// stMu nor WALStore.mu.
func (l *chunkLayerImpl) seedTouched() {
l.stMu.Lock()
base := l.remoteLSN
l.stMu.Unlock()
var seed []uint64
l.s.mu.RLock()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
if e := l.s.v3.mapEntries.at(idx); e.Unknown || e.LSN > base {
seed = append(seed, uint64(idx))
}
}
l.s.mu.RUnlock()
// An absent chunk with no local write is HEAD's content: it is left out
// here, outside the pause (a fresh attach makes nearly every chunk so),
// as the candidate step would drop it.
kept := seed[:0]
l.stMu.Lock()
for _, idx := range seed {
if !l.absent[idx] || l.chunkHasLocalLocked(idx) {
kept = append(kept, idx)
}
}
l.stMu.Unlock()
l.touch(kept...)
}
// peekTouched lists the touched set's members, for a reader.
func (l *chunkLayerImpl) peekTouched() []uint64 {
l.touchedSeed.Do(l.seedTouched)
l.resolveTouchFilled(false)
l.unkMu.Lock()
defer l.unkMu.Unlock()
set := l.touchedLocked(false)
out := make([]uint64, 0, set.Len())
set.each(func(c uint64) { out = append(out, c) })
return out
}
// takeTouched hands the touched set to a capture's barrier and puts the
// cleared spare in its place, a pointer swap: a chunk marked after the take
// is the next cut's. The caller gives the set back (returnTouched).
func (l *chunkLayerImpl) takeTouched() *candidateSet {
l.unkMu.Lock()
defer l.unkMu.Unlock()
taken := l.touchedLocked(true)
if l.touchedSpare == nil {
l.touchedSpare = l.newTouchedSet(true) // only if prepareTouched was skipped
}
l.touched, l.touchedSpare = l.touchedSpare, nil
return taken
}
// prepareTouched readies the touched sets before a barrier, outside the
// pause: the once-per-layer seed, a pending recovery's clean-fill touches,
// and the cleared spare the barrier swaps in. The barrier then only swaps.
func (l *chunkLayerImpl) prepareTouched() {
l.touchedSeed.Do(l.seedTouched)
l.resolveTouchFilled(true)
l.unkMu.Lock()
l.touchedLocked(true)
if l.touchedSpare == nil {
l.touchedSpare = l.newTouchedSet(true)
}
l.unkMu.Unlock()
}
// returnTouched clears a taken set (O(members)) and keeps it as the spare.
func (l *chunkLayerImpl) returnTouched(set *candidateSet) {
set.clear()
l.unkMu.Lock()
if l.touchedSpare == nil {
l.touchedSpare = set
}
l.unkMu.Unlock()
}
// OnExtentWrite is O(1): it only marks memory. It runs under extent or
// publication locks.
func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) {
@@ -610,9 +897,11 @@ func (l *chunkLayerImpl) noteMutation(lba, lsn uint64) {
cov = func() string { return localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local) }
}
sh.write(idx, lsn, func() { l.chunkMut[idx].Add(1) }, cov)
l.touch(idx)
return
}
l.chunkMut[idx].Add(1)
l.touch(idx) // its version moved: a clean fill's proof ends
}
}
@@ -623,6 +912,7 @@ func (l *chunkLayerImpl) noteAllMutated() {
for i := range l.chunkMut {
l.chunkMut[i].Add(1)
}
l.touchFilled.Store(true)
if sh := l.shadow; sh != nil {
l.recoveredLocked(sh)
}
@@ -705,6 +995,52 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) {
// UNKNOWN never certifies clean; a max LSN beyond HEAD must be captured even
// after the WAL entry has checkpointed and the legacy bitmap says clean.
func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
members := l.peekTouched()
out, _ := l.candidatesFrom(func(f func(uint64)) {
for _, c := range members {
f(c)
}
}, math.MaxUint64)
return out
}
// The candidate predicate, per chunk i (INV-WAL-V3-CAPTURE-CANDIDATES-001):
//
// (entry.Unknown && !knownEqualToHead(i)) || entry.LSN > remoteLSN,
// unless absent(i) && !chunkHasLocal(i)
//
// The touched set must hold every chunk whose answer can turn true between
// two barriers. Each input that moves, and what touches the chunk:
//
// input mover touch
// entry.LSN up recordMapWriteV3 (write, replay) OnMapEntryChange
// entry.Unknown on markMapUnknownV3, recordMapWriteV3 OnMapEntryChange
// (reused LSN); map creation, open seedTouched
// entry.Unknown off capture's clear, known-zero clear none: true to false only
// (persistCapturedMapV3)
// remoteLSN up finishCut none: true to false only
// version (proof) noteMutation touch(i)
// noteAllMutated (Recover, BASE resume touchFilled, resolved at
// under WALStore.mu; BASE transition the next take or peek
// under capMu)
// HEAD ref (proof) setHeadLocked, applyCommitLocked touchRefChangedLocked,
// touch(changed)
// clean mark added a fill none: true to false only
// clean marks gone BASE install (allDirty: every chunk) none: allDirty
// own (proof) OwnBatch addOwnCandidatesLocked
// absent off a fill's install touch(i)
// a local write; BASE install noteMutation; allDirty
// absent on an evict none: true to false only
//
// A recovery that lands after a barrier's take is the next cut's, as a write
// after the barrier is. Under tests, every barrier also runs the full scan as
// an oracle (candidateOracle) and reports any chunk the set missed.
//
// candidatesFrom is the candidate step over a touched set (peeked by a
// reader, taken by the barrier). Its work is O(changed): the WAL's dirty
// entries, the own batch, and the set's members, each judged on its own; no
// map of every chunk is walked. visits counts every chunk index it touched.
func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64)), upTo uint64) (map[uint64]bool, int64) {
out := map[uint64]bool{}
var base uint64
@@ -712,42 +1048,40 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
base = l.remoteLSN
l.stMu.Unlock()
visits := int64(0)
for _, e := range l.s.dm.snapshot() {
visits++
// Retention in the local WAL is not dirt since HEAD. Lower-LSN
// BASE/direct changes remain conservative through UNKNOWN below.
if e.LSN > base {
if e.LSN > base && e.LSN <= upTo {
out[l.chunkOf(e.LBA)] = true
}
}
{
l.stMu.Lock()
absent := map[uint64]bool{}
for idx := range l.absent {
if !l.chunkHasLocalLocked(idx) {
absent[idx] = true
}
l.s.mu.RLock() // before stMu, the established order
defer l.s.mu.RUnlock()
l.stMu.Lock()
visits += int64(len(l.own))
l.addOwnCandidatesLocked(out)
// The map is not scanned. An entry above remoteLSN is a write that is
// either still in the WAL (the dirty map above), flushed above the last
// cut (l.dirty, OnExtentWrite) or captured by a cut that did not land
// (requeued into l.dirty); the first use seeds every entry above
// remoteLSN at that time (a restart's earlier writes) with the UNKNOWN
// ones. An absent chunk with no local write is HEAD's content and leaves
// the set: it becomes present only by a fill (known equal to HEAD) or by
// local writes (l.dirty). A clean fill still equal to HEAD is not
// compared again.
members(func(i uint64) {
visits++
if i >= uint64(l.s.v3.mapEntries.len()) || (l.absent[i] && !l.chunkHasLocalLocked(i)) {
return
}
filled := map[uint64]bool{}
for idx := range l.filledClean {
if l.knownEqualToHeadLocked(idx) {
filled[idx] = true
}
if e := l.s.v3.mapEntries.at(int(i)); (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
out[i] = true
}
l.addOwnCandidatesLocked(out)
l.stMu.Unlock()
l.s.mu.RLock()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
e := l.s.v3.mapEntries.at(idx)
i := uint64(idx)
if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) {
out[i] = true
}
}
l.s.mu.RUnlock()
}
return out
})
l.stMu.Unlock()
return out, visits
}
// filledMark is a clean fill: the chunk's version and the HEAD ref it was
@@ -877,6 +1211,10 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat
sh.fill(idx, ref.SHA256)
}
delete(l.absent, idx)
// Absent to present: the predicate's exclusion ends. Without a fresh
// clean mark (a version moved during the fetch, e.g. by a recovery) the
// chunk may now be a candidate, so the next candidate step judges it.
l.touch(idx)
for i := uint64(0); i < l.chunkBlocks; i++ {
delete(l.localBlocks, first+i)
}
@@ -1128,6 +1466,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{}, err
}
defer done()
// A cut seals and publishes: refused while the upgrade compare pass has
// not ended (every chunk's hash must be known), typed, with its progress.
if err := l.admitUpgradePass(); err != nil {
return chunkCutResult{}, err
}
l.startCutStatus()
defer l.clearCutStatus()
start := time.Now()
@@ -1282,6 +1625,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{}, cause
}
// Before the pause: the once-per-layer UNKNOWN seed, and one sync so the
// pause's own sync flushes only what came after it (the first cut after a
// fill pays its write-back here). The in-pause sync still fixes H.
l.prepareTouched()
preSync := time.Now()
if _, err := l.s.syncWithPhases(nil); err != nil {
st.PreSyncNs = time.Since(preSync).Nanoseconds()
return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err)
}
st.PreSyncNs = time.Since(preSync).Nanoseconds()
// Quiesced cut. The guest pause starts at the Lock REQUEST: a pending
// writer blocks new readers of captureMu, so a write arriving while the cut
// waits for writers already holding it (e.g. parked in WAL admission) is
@@ -1308,6 +1662,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
// Resume rejected tentative admission before any ordinary COW upload.
unlockCapture := func() {
l.paused = false
l.s.captureMu.Unlock()
if !detach && releasePrecopy != nil {
releasePrecopy()
@@ -1318,6 +1673,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
hook()
}
l.s.captureMu.Lock()
l.paused, l.pauseOps = true, 0
defer func() { st.PauseCandidateOps = l.pauseOps }()
barrier := time.Now()
st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds()
h, err := l.s.syncWithPhases(&st.SyncPhases)
@@ -1332,17 +1689,89 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
l.cutPhase("candidates")
candidateStart := time.Now()
candidates := map[uint64]bool{}
for idx := range l.captureCandidates() {
// The pause does O(1) work: the touched set and the dirty set are taken
// by pointer swaps and the copy window opens over what they name (a
// superset of the candidates). Every per-candidate step runs after the
// pause, under the window: the judgement, the versions (atomic with the
// write path), staged reuse, the base refs and the copy-order hint.
taken := l.takeTouched()
// A recovery that landed after prepareTouched moved every clean fill's
// version: its request is taken here as a flag (O(1)); the window covers
// every chunk until it narrows, and the fills are judged after the pause.
filledTaken := l.touchFilled.Swap(false)
oracleWant := l.candidateOracleScan() // tests only (nil in production)
l.stMu.Lock()
dirtyTaken, all := l.dirty, l.allDirty
l.dirty, l.allDirty = map[uint64]bool{}, false
l.cutLSN = h
l.stMu.Unlock()
own := l.own // stable for the cut (set and cleared under capMu)
covers := func(idx uint64) bool { return all || filledTaken || taken.has(idx) || dirtyTaken[idx] || own[idx] }
windowStart := time.Now()
w, installErr := l.installCOWWindow(covers, spill)
if installErr == nil {
w.budget = budget
}
// The barrier ends here. A pre-copy attempt's drained frontend stays
// drained until its freeze decision below, made on the judged tail: its
// guest pause runs to that release, as before. An ordinary cut's guest
// is back now, and its pause did O(1) work.
drained := releasePrecopy != nil
l.s.captureMu.Unlock()
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
if !drained {
l.paused = false
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
}
releaseDrain := func() {
if drained {
if releasePrecopy != nil && !detach {
releasePrecopy()
releasePrecopy = nil
}
l.paused = false
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
drained = false
}
}
if installErr != nil {
releaseDrain()
if filledTaken {
l.touchFilled.Store(true)
}
l.requeueTaken(taken, dirtyTaken, all)
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr)
}
// After the pause. The judgement: the touched set's members with the
// map scan's predicate, the WAL entries up to H, the own batch, the
// taken dirty set, and every chunk after a BASE write.
members := taken.each
if filledTaken {
l.stMu.Lock()
filled := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
filled = append(filled, idx)
}
l.stMu.Unlock()
members = func(f func(uint64)) {
taken.each(f)
for _, idx := range filled {
f(idx)
}
}
}
candidates, visits := l.candidatesFrom(members, h)
visits += int64(len(taken.summary)) // the summary words the walk read
l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause
for idx := range dirtyTaken {
visits++
candidates[idx] = true
}
l.stMu.Lock()
all := l.allDirty
for idx := range l.dirty {
candidates[idx] = true
}
if all {
for i := uint64(0); i < l.numChunks; i++ {
visits++
// An absent chunk with no local write is HEAD's content by
// definition: comparing it would only fetch it back.
if l.absent[i] && !l.chunkHasLocalLocked(i) {
@@ -1351,72 +1780,79 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
candidates[i] = true
}
}
l.stMu.Unlock()
candidateOracleCompare(oracleWant, candidates) // tests only
// A chunk known to hold HEAD's bytes at its current version (a clean
// fill, or a compare by a cut that did not publish) is not compared
// again, whatever returned it to the dirty set: any write since raises
// its version, and a newer HEAD changes its ref. A chunk an own batch
// re-uploads under this layer's key stays: equal bytes are its point.
l.stMu.Lock()
l.pauseOp(len(candidates))
for idx := range candidates {
if l.knownEqualToHeadLocked(idx) {
delete(candidates, idx)
}
}
if sh := l.shadow; sh != nil {
// Extras are judged only for a cut that can proceed: a store behind
// HEAD (H below its RemoteLSN) is refused before any upload, and its
// writes are not dirt above HEAD to the engine.
proceeds := h >= l.head.RemoteLSN
miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != nil && proceeds, proceeds)
if hook := l.testShadowCheck; hook != nil {
hook(miss, extra)
}
}
// A staged chunk stands for the barrier copy while no write reached
// it since staging (its version is unchanged) and HEAD is the one it
// was compared against.
l.stMu.Unlock()
// Each candidate's version at the barrier: the version a guest write's
// save recorded with its bytes, else the live one, read atomically with
// the write path; the window closes on a chunk only after this and its
// upload. A staged chunk stands for the barrier copy while its version
// is the barrier's and HEAD is the one it was compared against.
var captured []capturedChunk
var capturedVersions map[uint64]uint64
capturedVersions = make(map[uint64]uint64, len(candidates))
useStaged := map[uint64]bool{}
capturedVersions := make(map[uint64]uint64, len(candidates))
l.pauseOp(2 * len(candidates)) // versions, staged reuse
for idx := range candidates {
if capturedVersions != nil {
capturedVersions[idx] = l.chunkVersion(idx)
}
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen {
capturedVersions[idx] = w.versionAt(idx)
}
useStaged := map[uint64]bool{}
l.stMu.Lock()
for idx := range candidates {
if sc, ok := staged[idx]; ok && sc.ver == capturedVersions[idx] && sc.headGen == l.head.Gen {
useStaged[idx] = true
captured = append(captured, sc.capturedChunk)
}
}
if sh := l.shadow; sh != nil {
// Extras are judged only for a cut that can proceed: a store behind
// HEAD (H below its RemoteLSN) is refused before any upload, and its
// writes are not dirt above HEAD to the engine. A chunk written since
// the barrier is in the live touched set: the record counts its write.
proceeds := h >= l.head.RemoteLSN
after := l.writtenSinceTake
skip := func(idx uint64) bool { return l.shadowExemptLocked(idx) || after(idx) }
miss, extra := sh.checkAfter(candidates, skip, after, l.testShadowCheck != nil && proceeds, proceeds)
if hook := l.testShadowCheck; hook != nil {
hook(miss, extra)
}
}
st.CandidateVisits = visits
l.inflight = candidates
l.dirty = map[uint64]bool{}
l.allDirty = false
l.cutLSN = h
l.pauseOp(2 * len(candidates)) // the shadow check, the base refs
baseHead := l.cutBaseLocked(candidates)
l.stMu.Unlock()
w.narrow(candidates, useStaged, baseHead.Chunks)
l.returnTouched(taken)
l.cutPhase("compare")
// Candidates, mutation versions and the copy-order hint belong to the same barrier.
// Do not sample the owned map after COW writers are admitted again.
l.pauseOp(len(candidates))
recent := l.chunkRecency(candidates, h)
st.CandidateNs += time.Since(candidateStart).Nanoseconds()
// The authoritative candidate set is fixed with mutation admission closed.
// The owner callback is nonblocking and may stop only an already drained
// frontend; rejected attempts remain ordinary COW cuts.
if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil {
tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
detach = freeze(tail, pauseStart, st)
}
releaseDrain()
if guestFrozen && !detach {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.endCOWWindow(w)
l.requeueCut(all)
return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit())
}
if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.endCOWWindow(w)
// HEAD holds the image of a later LSN than this host's log has
// reached: publishing would move remote_lsn backwards. Refused
// before any upload. (A HEAD of a newer holder fences below.)
@@ -1425,35 +1861,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
st.CandidateChunks = max(st.CandidateChunks, len(candidates))
var copyErr error
copyStart := time.Now()
bytesBeforeCopy := st.UploadedBytes
{
var w *cutCOWWindow
windowStart := time.Now()
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill)
if copyErr == nil {
w.budget = budget
}
unlockCapture()
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
copyStart = time.Now()
if copyErr == nil {
var copied []capturedChunk
copied, copyErr = l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
for _, c := range copied {
if c.key != "" {
st.UploadedChunks++
st.UploadedBytes += int64(c.size)
}
}
captured = append(captured, copied...)
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
st.COWSavedChunks = int(w.saved.Load())
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
copied, copyErr := l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
for _, c := range copied {
if c.key != "" {
st.UploadedChunks++
st.UploadedBytes += int64(c.size)
}
}
captured = append(captured, copied...)
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
st.COWSavedChunks = int(w.saved.Load())
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
st.CopyNs = time.Since(copyStart).Nanoseconds()
if st.UploadedBytes > bytesBeforeCopy {
@@ -2119,6 +2539,7 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) {
d := *id.DetachedBy
h.DetachedBy = &d
}
l.touch(changed...) // their refs changed: the next candidate step judges them
for _, idx := range changed {
r, ok := id.Chunks[idx]
switch {
@@ -2390,6 +2811,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
current := *l.currentCut
out.CurrentCut = &current
}
out.UpgradePass = l.upgradePassStatusLocked()
out.Hydration.WorkerLimit = l.cfg.HydrationWorkers
out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth
for _, f := range l.hydration {
@@ -0,0 +1,67 @@
package storage
import "math/bits"
// candidateSet is the record's chunk candidate set of one cut interval:
// one bit per chunk, and a summary of one bit per 64-chunk word
// that has any bit set. Setting a bit is O(1); walking the set is O(C + S/4096)
// (the summary's words, then only the words it names); clearing it is O(C).
// It is a superset: a bit stays set when the chunk later leaves the candidate
// kinds (committed, evicted), and the reader keeps only the chunks whose kind
// is still a candidate.
type candidateSet struct {
words []uint64
summary []uint64
n int // bits set (a chunk counted once)
}
func newCandidateSet(chunks uint64) *candidateSet {
w := (chunks + 63) / 64
return &candidateSet{words: make([]uint64, w), summary: make([]uint64, (w+63)/64)}
}
func (s *candidateSet) set(chunk uint64) {
w, b := chunk/64, uint64(1)<<(chunk%64)
if s.words[w]&b != 0 {
return
}
s.words[w] |= b
s.summary[w/64] |= 1 << (w % 64)
s.n++
}
func (s *candidateSet) has(chunk uint64) bool { return s.words[chunk/64]&(1<<(chunk%64)) != 0 }
// each calls f for every chunk in the set, in chunk order.
func (s *candidateSet) each(f func(chunk uint64)) {
for si, sw := range s.summary {
for sw != 0 {
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
sw &= sw - 1
for word := s.words[w]; word != 0; word &= word - 1 {
f(w*64 + uint64(bits.TrailingZeros64(word)))
}
}
}
}
// or adds every chunk of o (same shape).
func (s *candidateSet) or(o *candidateSet) {
o.each(s.set)
}
// clear empties the set, touching only the words it names.
func (s *candidateSet) clear() {
for si, sw := range s.summary {
for sw != 0 {
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
sw &= sw - 1
s.words[w] = 0
}
s.summary[si] = 0
}
s.n = 0
}
// Len is the number of chunks in the set.
func (s *candidateSet) Len() int { return s.n }
@@ -173,6 +173,11 @@ func (l *chunkLayerImpl) loadChunkRecordV11(dir string, epoch uint64) (*chunkRec
valid[seg] = 0
}
sh := &chunkRecordShadow{zeroSum: l.zeroChunkSum(), version: l.chunkVersion, v11: true}
for seg := range rebuilt {
if first := seg * chunkRecordSegment; !sh.rebuilt || first < sh.cursorBack {
sh.cursorBack, sh.rebuilt = first, true
}
}
sh.applied.Store(storePos)
rec, err := newChunkRecordRuntime(dir, l.numChunks, epoch, sh.applied.Load, kinds, hashes, valid, ld.Header.G, changedAtOpen)
if err != nil {
@@ -139,6 +139,13 @@ type chunkRecordRuntime struct {
changes []int // changes since the page was last written
firstDirty []time.Time // when the page went dirty
headerG uint64 // the G last written
// cand is the candidate set of the current cut interval: every
// applied event whose result is a candidate kind (P, U, HU) sets its
// chunk, a write that leaves U as U included (new dirt since the last
// take). A cut takes it whole and leaves the empty spare in its place;
// candTaken counts the takes (the barrier's O(1) work, for its counters).
cand, spare *candidateSet
candTaken uint64
}
// newChunkRecordRuntime builds the runtime from the record as the open left
@@ -157,12 +164,16 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u
valid: append([]uint64(nil), valid...),
dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs), since: make([]uint64, segs),
changes: make([]int, segs), firstDirty: make([]time.Time, segs), headerG: headerG}
r.cand, r.spare = newCandidateSet(chunks), newCandidateSet(chunks)
for c, k := range kinds {
code, err := chunkRecordStateCode(k)
if err != nil {
return nil, err
}
r.kinds[c] = code
if isRecordCandidate(k) { // at open: the persisted kinds are the source of truth
r.cand.set(uint64(c))
}
}
now := time.Now()
for seg, changed := range changedAtOpen {
@@ -250,6 +261,9 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
delete(r.unmarked, chunk) // an evict: nothing local is claimed
}
}
if isRecordCandidate(res.State.Kind) {
r.cand.set(chunk)
}
if res.State.Kind != cur || newHash != r.hashes[chunk] {
code, err := chunkRecordStateCode(res.State.Kind)
if err != nil {
@@ -274,6 +288,46 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
return eff, nil
}
// TakeCandidates hands the current interval's candidate set to a cut and
// starts an empty one, in O(1): the record keeps setting chunks into the new
// set, so a write after the take is the next cut's. The cut gives the set
// back with ReturnCandidates (its candidates OR'd back if the cut did not
// commit them), never keeps it.
func (r *chunkRecordRuntime) TakeCandidates() *candidateSet {
r.mu.Lock()
defer r.mu.Unlock()
taken := r.cand
if r.spare == nil { // a second take before the first set came back
r.spare = newCandidateSet(r.chunks)
}
r.cand, r.spare = r.spare, nil
r.candTaken++
return taken
}
// ReturnCandidates gives a taken set back. With keep (a refused, unknown or
// aborted cut) its chunks join the current interval's set again, so no
// candidate is lost; the set is then cleared (O(C)) and becomes the spare.
func (r *chunkRecordRuntime) ReturnCandidates(taken *candidateSet, keep bool) {
r.mu.Lock()
defer r.mu.Unlock()
if keep {
r.cand.or(taken)
}
taken.clear()
if r.spare == nil {
r.spare = taken
}
}
// IsCandidate reports whether a chunk's kind is a candidate now (a taken
// set is a superset: the cut keeps only these).
func (r *chunkRecordRuntime) IsCandidate(chunk uint64) bool {
r.mu.Lock()
defer r.mu.Unlock()
return isRecordCandidate(kindByCode[r.kinds[chunk]])
}
// PersistSegmentOf writes the page holding chunk if it is dirty (no-op if
// its last written content is current): the durable receipt an evict needs
// before the store's bits may clear, also when the in-memory state was
@@ -30,6 +30,11 @@ import (
type chunkRecordShadow struct {
rec *chunkRecordRuntime
zeroSum [32]byte
// cursorBack is the first chunk of the earliest page rebuilt at open
// (rebuilt says one was): the kernel's Rebuilt rows move the upgrade
// pass's cursor back there (cursor_back). Set once at open.
cursorBack uint64
rebuilt bool
mu sync.Mutex
defects int // kernel refusals and evidence refusals of shell events
@@ -252,13 +257,19 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head
}
// commit is E5 and E6: a HEAD names the chunk's captured hash. Skipped when
// the chunk was written since its capture.
// the chunk was written since its capture, and when the record does not hold
// a hash for it (HU or HP): a cut that captured the chunk while its absence
// stood sent no Hash, and on v1.0 its local bits can complete since (landed,
// P to U, with no version change); the chunk stays a candidate.
func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) bool {
if c.idx >= s.rec.chunks {
return false
}
same := capturedAt(c.version, current)
_, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same)
hashedAt := func(k chunkkernel.Kind) bool {
return (k == chunkkernel.HashUnpublished || k == chunkkernel.HashPublished) && same(k)
}
_, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, hashedAt)
if err != nil {
s.defect(c.idx, chunkkernel.Commit, err)
}
@@ -365,6 +376,13 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat
// the misses and, when withExtra (tests: a full scan of the record, too
// slow for a barrier), the record's extra candidates. Caller holds stMu.
func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
return s.checkAfter(engine, skip, nil, withExtra, proceeds)
}
// checkAfter is check for candidates judged after the guest pause: after,
// when set, names the chunks written since the barrier (the record already
// counts those writes), which are no record extra of this cut.
func (s *chunkRecordShadow) checkAfter(engine map[uint64]bool, skip, after func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
s.rec.mu.Lock()
for idx := range engine {
if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) {
@@ -376,7 +394,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool
s.fullScans++
for idx, code := range s.rec.kinds {
k := kindByCode[code]
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) {
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) && (after == nil || !after(uint64(idx))) {
extra = append(extra, uint64(idx))
}
}
@@ -18,6 +18,12 @@ func TestMain(m *testing.M) {
found = append(found, msg)
mu.Unlock()
}
// Every barrier also checks its touched-set candidates against the full
// scan; a chunk the set missed is a finding too.
candidateOracle = func(msg string) {
fmt.Fprintln(os.Stderr, msg) // in place, next to the test that ran it
shadowFindings(msg)
}
// CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store
// format (the lab build's mode); it selects a format, it turns no check
// off.
@@ -28,7 +34,7 @@ func TestMain(m *testing.M) {
mu.Lock()
defer mu.Unlock()
if len(found) > 0 {
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0])
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow or candidate oracle findings; first: %s\n", len(found), found[0])
if code == 0 {
code = 1
}
@@ -42,8 +48,13 @@ func TestMain(m *testing.M) {
func forgetMarksAsARestart(t *testing.T, l *chunkLayerImpl) {
t.Helper()
l.stMu.Lock()
forgotten := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
forgotten = append(forgotten, idx)
}
l.filledClean = map[uint64]filledMark{}
l.stMu.Unlock()
l.touch(forgotten...) // a restarted layer's seed judges them again
sh, err := newChunkRecordShadow(l)
if err != nil {
t.Fatal(err)
@@ -204,6 +204,7 @@ func TestShadowCutOfAPartialChunkKeepsItPartial(t *testing.T) {
// E8: with no HEAD, a write checkpointed out of the WAL before attach stays
// a candidate (the map's dirt), so the record starts it U, never HP.
func TestShadowAttachKeepsACheckpointedWriteACandidate(t *testing.T) {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
s, _ := newMappedCheckpointStoreV3(t)
writeSynced(t, s, 5, 5)
if err := s.flusher.flushOnce(); err != nil {
@@ -619,3 +620,75 @@ func TestShadowScratchExemptionIsBoundToItsCapturedVersion(t *testing.T) {
})
}
}
// E6 on a v1.0 shadow: a cut captured a written absent chunk while its
// absence stood (P: Hash skipped), and the flusher then completed the
// chunk's local bits (landed, P to U, with no write and so no version
// change) before the cut published. The publish's Commit at the captured
// version meets U: it is skipped, not sent (the kernel refuses U/Commit),
// and the chunk stays U, a candidate for the next cut.
func TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped(t *testing.T) {
s, l, _ := lazyFreshVolume(t)
const idx = 3
if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD3)); err != nil {
t.Fatal(err)
}
if k := shadowKind(l, idx); k != chunkkernel.Partial {
t.Fatalf("setup: the written absent chunk is %s, want P", k)
}
current := func() uint64 { return l.chunkVersion(idx) }
c := capturedChunk{idx: idx, version: current(), sum: [32]byte{1}}
l.shadow.hashed(c, current, chunkHead{}) // the cut's compare: skipped on P (a scratch capture)
l.stMu.Lock()
l.shadow.landed(idx) // the flusher completes the chunk's local bits
l.stMu.Unlock()
if k := shadowKind(l, idx); k != chunkkernel.Unknown || current() != c.version {
t.Fatalf("setup: after landing %s at version %d, want U at the captured version %d", k, current(), c.version)
}
l.shadowCommit([]capturedChunk{c}, map[uint64]uint64{idx: c.version}) // the publish
if n := shadowDefects(l); n != 0 {
t.Fatalf("%d shell events refused: Commit was sent for a chunk the record holds U", n)
}
if k := shadowKind(l, idx); k != chunkkernel.Unknown {
t.Fatalf("after the publish: %s, want U (a candidate for the next cut)", k)
}
}
// The model's premise "every record state change moves the chunk version"
// holds on v1.1 only: there an extent write never lands an absent chunk
// (the write's own event carries the store's bits), so completing a written
// chunk's local bits through the flusher leaves its kind and version as they
// were. On v1.0 the same extent writes land it (P to U) with no version
// change: the case the Commit guard covers.
func TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10(t *testing.T) {
for _, v11 := range []bool{true, false} {
t.Run(map[bool]string{true: "v1.1", false: "v1.0"}[v11], func(t *testing.T) {
if v11 {
withV11Format(t)
}
s, l, _ := lazyFreshVolume(t)
const idx = 3
lsn, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD4))
if err != nil {
t.Fatal(err)
}
kind, version := shadowKind(l, idx), l.chunkVersion(idx)
if kind != chunkkernel.Partial {
t.Fatalf("setup: the written absent chunk is %s, want P", kind)
}
for b := uint64(0); b < ctChunkBlocks; b++ {
l.OnExtentWrite(idx*ctChunkBlocks+b, lsn) // the flusher's extent writes complete the local bits
}
after, v := shadowKind(l, idx), l.chunkVersion(idx)
switch {
case v11 && (after != kind || v != version):
t.Fatalf("v1.1: extent writes moved the record %s->%s (version %d->%d): an extent write must not land a chunk", kind, after, version, v)
case !v11 && (after != chunkkernel.Unknown || v != version):
t.Fatalf("v1.0 control: %s at version %d, want U at the same version %d (landed)", after, v, version)
}
if n := shadowDefects(l); n != 0 {
t.Fatalf("%d shell events refused", n)
}
})
}
}
@@ -125,7 +125,17 @@ func upgradeChunkRecordSeeded(ctx context.Context, s *WALStore, epoch uint64, se
if seeding {
hashOf = cleanStopHashes(seed, pos)
}
return writeChunkRecordPagesFrom(dir, chunks, pos, r, hashOf, progress)
if err := writeChunkRecordPagesFrom(dir, chunks, pos, r, hashOf, progress); err != nil {
return err
}
// An unseeded upgrade leaves its whole local chunks unknown: the
// compare pass's first cursor is written here, before the store's
// marker, so a crash anywhere after the marker still finds the pass
// to run (the attach resumes a cursor; it never infers one).
if !seeding {
return writeInitialUpgradePassCursor(dir, epoch)
}
return nil
}
if marked, e := s.ChunkStateMarker(); marked {
if e != epoch {
@@ -13,6 +13,7 @@ import (
// in the store's bits. Mutant (holds only on Fill to HP): the page says U
// while the bits say some.
func TestV11PartialFillWaitsForTheDurableMark(t *testing.T) {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
s, path, l, f := v11LazyVolume(t)
const idx = 2
if _, err := s.Write(uint32(idx*ctChunkBlocks), makeBlock(ctBlockSize, 0x77)); err != nil {
@@ -12,6 +12,7 @@ import (
// in HEAD), synced at HEAD's position, upgrades with every chunk hash-known and published with its
// content's hash; without the proof every chunk is unknown, for the pass.
func TestV11AttachSeedsFromTheCleanStopInItsConfig(t *testing.T) {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
for _, tc := range []struct {
name string
proof bool
@@ -51,6 +51,7 @@ func v11Attach(t *testing.T, s *WALStore, f *fakeChunkRemote) *chunkLayerImpl {
// .chunkpresence is gone, and the record's pages are written (page I/O on).
// A store without the format build keeps the v1.0 path: no marker, no record.
func TestV11AttachUpgradesTheStoreOnce(t *testing.T) {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
t.Run("v1.0 build", func(t *testing.T) {
v10Only(t)
s, path := v11Store(t)
@@ -199,6 +200,7 @@ func v11Reopen(t *testing.T, s *WALStore, path string, f *fakeChunkRemote) *chun
// - a .chunkpresence left after the record completed is removed, and its
// content is not read (the record holds presence).
func TestV11UpgradeRecoversFromACrashAtEachStep(t *testing.T) {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
t.Run("stale pages before the marker", func(t *testing.T) {
withV11Format(t)
s, path := v11Store(t)
@@ -261,6 +263,7 @@ func TestV11UpgradeRecoversFromACrashAtEachStep(t *testing.T) {
// blocks are all local reopens U, never the damaged page's word for it.
func TestV11DamagedPageIsRebuiltFromTheStoreBits(t *testing.T) {
withV11Format(t)
withoutUpgradePass(t) // the rebuild's own state (the pass after it: TestV11UpgradePassRewindsBelowItsCursorAfterARebuiltPage)
s, path := v11Store(t)
f := newFakeChunkRemote()
l := v11Attach(t, s, f)
+16
View File
@@ -79,6 +79,10 @@ import (
// under-report.
type chunkSink interface {
OnExtentWrite(lba uint64, lsn uint64)
// OnMapEntryChange is called when the store changes a chunk's map entry
// (a write's LSN, or UNKNOWN by a direct/BASE mutation or a reused LSN):
// O(1), under WALStore.mu; it takes only a leaf lock.
OnMapEntryChange(chunk uint64)
BeforeCheckpointAdvance(lsn uint64) error
BeginBaseInstall() error
EndBaseInstall(frontier uint64) error
@@ -413,6 +417,17 @@ type SyncPhaseStats struct {
type chunkCutStats struct {
SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it)
// CandidateVisits counts the chunk indices the barrier's candidate step
// visited (scanned entries and set members), the work a pause pays for.
CandidateVisits int64
// PauseCandidateOps counts per-candidate operations done while the guest
// is paused (from the barrier lock to its release): zero when the pause
// does O(1) work.
PauseCandidateOps int64
// PreSyncNs is the sync right before the barrier, outside the guest
// pause (never part of BarrierPauseNs): the pause's own sync then has
// only what came after it.
PreSyncNs int64
// Disjoint non-payload intervals within barrier-to-settlement fixed cost.
CandidateNs int64
WindowSetupNs int64
@@ -525,6 +540,7 @@ type chunkLayerStats struct {
LastCutH uint64 // the LSN the last successful cut published
LastCutNs int64 // when it completed (wall clock, Unix ns)
CutSeq uint64 // successful cuts of this layer so far (in-process); the latest cut's identity
UpgradePass UpgradePassStatus // the upgrade compare pass after a v1.0 store's upgrade (v1.1): none, seeded, running, done or failed
// BarrierOverBound counts cuts whose barrier copied more than the
// bound after the staging rounds.
BarrierOverBound uint64
@@ -66,6 +66,7 @@ func (r ownedHeadRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n
// fake's own HEAD exists before the first reading; the layer's copy has its
// own keys (ownedHeadRemote).
func heldPerChunk(t *testing.T, chunks uint64, chunkBlocks int, owner string) float64 {
withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows
t.Helper()
f := newFakeChunkRemote()
f.mu.Lock()
@@ -78,6 +78,18 @@ func decodeUpgradePassCursor(b []byte) (upgradePassCursor, error) {
// readUpgradePassCursor reads the persisted cursor for epoch. A missing or
// damaged cursor, or one of another epoch, starts the pass at chunk 0: that
// repeats work, never skips it.
// writeInitialUpgradePassCursor writes the pass's first cursor (nothing
// compared yet) for epoch, unless a cursor is already there (a re-run of the
// upgrade keeps the progress it finds).
func writeInitialUpgradePassCursor(dir string, epoch uint64) error {
if _, err := os.Stat(filepath.Join(dir, upgradePassCursorName)); err == nil {
return nil
} else if !os.IsNotExist(err) {
return err
}
return writeChunkRecordFile(dir, upgradePassCursorName, encodeUpgradePassCursor(upgradePassCursor{Epoch: epoch}))
}
func readUpgradePassCursor(dir string, epoch uint64) (upgradePassCursor, error) {
b, err := os.ReadFile(filepath.Join(dir, upgradePassCursorName))
if errors.Is(err, os.ErrNotExist) {
@@ -164,6 +176,14 @@ func newUpgradePass(dir string, epoch, chunks uint64, pages upgradePassPages, co
cur: c, next: c.Next, wt: c.Next, rew: noRewind, done: c.Next == chunks}, nil
}
// progress is the pass's work and whether it has ended: the chunks compared
// (persisted, plus those since the persisted cursor), and the chunks it walks.
func (p *upgradePass) progress() (compared, total uint64, done bool) {
p.mu.Lock()
defer p.mu.Unlock()
return p.cur.Compared + p.pending, p.chunks, p.done
}
// Admit answers a request that needs every chunk's hash known: nil once the
// pass has ended, else the typed refusal with its progress.
func (p *upgradePass) Admit() error {
@@ -0,0 +1,87 @@
package storage
import (
"crypto/sha256"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/chunkkernel"
)
// After an unclean stop there is no clean-stop proof, so the v1.0.x upgrade
// leaves every whole local chunk unknown (U). The attach then runs the
// compare pass, which leaves none unknown: a chunk equal to HEAD becomes
// hash-known and published with HEAD's hash; a chunk that differs from HEAD
// stays a candidate, never with HEAD's hash.
//
// HEAD names chunks 1, 2 and 3; the store holds chunks 1 and 2 as HEAD has
// them and chunk 3 with other bytes; every other chunk is zero on both sides.
//
// The wait below is a bound on a pass over 16 chunks; once the pass reports
// its completion, that signal can replace it.
func TestV11UncleanUpgradeLeavesNoUnknownAfterThePass(t *testing.T) {
withV11Format(t)
withoutPassWait(t) // the test watches the pass from the attach on
s, _ := v11Store(t)
if err := s.SetLayoutIdentity("claim-a", false); err != nil {
t.Fatal(err)
}
n := int(s.NumBlocks())
head := make([]byte, n*ctBlockSize)
for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ { // chunks 1, 2, 3 in HEAD
copy(head[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
}
for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ {
b := head[lba*ctBlockSize : (lba+1)*ctBlockSize]
if lba >= 3*ctChunkBlocks { // chunk 3 differs locally
b = makeBlock(ctBlockSize, byte(0x90+lba))
}
if _, err := s.Write(uint32(lba), b); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
f := newFakeChunkRemote()
f.seedHead(t, head, syncedPos(s), 1)
cfg := ctConfig(2)
cfg.Bitmap = nil // and no CleanStop: an unclean stop
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
if k := shadowKind(l, 1); k != chunkkernel.Unknown {
t.Fatalf("the control needs an upgrade without a seed: chunk 1 opened %s, want U", k)
}
bound := 20 * time.Second
for deadline := time.Now().Add(bound); ; time.Sleep(50 * time.Millisecond) {
var unknown []uint64
for c := uint64(0); c < l.numChunks; c++ {
if shadowKind(l, c) == chunkkernel.Unknown {
unknown = append(unknown, c)
}
}
if len(unknown) == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("after %s chunks %v are still unknown: no compare pass ran over the upgraded store", bound, unknown)
}
}
hashOf := func(c uint64) [32]byte {
l.shadow.rec.mu.Lock()
defer l.shadow.rec.mu.Unlock()
return l.shadow.rec.hashes[c]
}
for _, c := range []uint64{1, 2} {
first := int(c) * ctChunkBlocks * ctBlockSize
want := sha256.Sum256(head[first : first+ctChunkBlocks*ctBlockSize])
if k, h := shadowKind(l, c), hashOf(c); k != chunkkernel.HashPublished || h != want {
t.Fatalf("chunk %d equal to HEAD ended %s with hash %x, want HP with HEAD's %x", c, k, h[:4], want[:4])
}
}
first := 3 * ctChunkBlocks * ctBlockSize
headSum := sha256.Sum256(head[first : first+ctChunkBlocks*ctBlockSize])
if k, h := shadowKind(l, 3), hashOf(3); k == chunkkernel.HashPublished && h == headSum {
t.Fatal("chunk 3, which differs from HEAD, ended published with HEAD's hash")
}
}
@@ -0,0 +1,233 @@
package storage
import (
"context"
"crypto/sha256"
"log"
"os"
"path/filepath"
"time"
"github.com/seaweedfs/seaweed-block/core/chunkkernel"
)
// The upgrade compare pass in a running layer. After a v1.0 store's upgrade
// with no clean-stop seed every whole local chunk is unknown; the attach runs
// the pass (chunk_upgrade_pass.go), which compares each with HEAD and
// persists its cursor as it goes. A stop never waits for it: the next attach
// resumes at the persisted cursor. Until it has ended, every request that
// seals or publishes (a cut, a snapshot, a backup, a sealing detach) is
// refused with ErrUpgradePassInProgress, which carries the progress, and the
// pass runs at full rate from then on.
// UpgradePassStatus is the pass's state as holder status reports it: none
// (the store needs no pass), seeded (a clean-stop seed made every chunk
// known at the upgrade), running, done, or failed (Outcome says why).
// Compared counts the chunks the pass found unknown and compared; Total is
// the chunks it walks. It is carried across a stop by the pass's cursor.
type UpgradePassStatus struct {
State string // none, seeded, running, done or failed; carried across a stop (read the status, never the pass's cursor file)
Compared uint64 // chunks the pass found unknown and compared, across stops
Total uint64 // chunks the pass walks
// Superseded counts chunks written during their own compare (in this
// process): not hashed, not counted as compared; each is dirty and the
// next cut takes it as any written chunk.
Superseded uint64
Outcome string `json:",omitempty"` // why a failed pass stopped; while the pass has not ended a cut, snapshot, backup or sealing detach is refused with code in_progress
}
// startUpgradePass decides the pass at attach and starts it when work
// remains: a persisted cursor resumes it (or reports it done); with no cursor
// it starts only if the record holds an unknown chunk. upgradedNow says the
// store was upgraded by this attach (for the seeded state). Owner: the
// layer's attach; the pass runs on the layer's context and wait group.
// prepareUpgradePass decides whether a compare pass runs and, for a page
// rebuilt at open, rewinds its cursor durably. The attach calls it before
// anything can write the record's pages (the hooks, the due loop): a rebuilt
// page republished as valid before the rewind is durable would hide the
// damage from the next open after a crash, and the rewind with it.
func (l *chunkLayerImpl) prepareUpgradePass(upgradedNow bool) error {
sh := l.shadow
if sh == nil || !sh.v11 || upgradePassTestDisabled {
return nil
}
dir := chunkRecordDir(l.s.path)
_, epoch := l.s.ChunkStateMarker()
_, statErr := os.Stat(filepath.Join(dir, upgradePassCursorName))
if statErr != nil && !os.IsNotExist(statErr) {
return statErr
}
// No cursor: a pass starts only after an unseeded upgrade by this attach
// (its chunks are unknown) or when a page was rebuilt at open. Chunks
// unknown only because they were written are dirty: cuts take them.
_, anyU := sh.firstUnknown()
if os.IsNotExist(statErr) && !(upgradedNow && anyU) && !sh.rebuilt {
state := "none"
if upgradedNow && l.cfg.CleanStop != nil {
state = "seeded"
}
l.stMu.Lock()
l.passStatus = UpgradePassStatus{State: state, Total: l.numChunks}
l.stMu.Unlock()
return nil
}
p, err := newUpgradePass(dir, epoch, l.numChunks, sh.rec, l.upgradeCompare)
if err != nil {
return err
}
// A page rebuilt at open (damage, a stale page) left its chunks unknown
// again, possibly behind the persisted cursor or a pass that had ended:
// the cursor goes back, durably, to the first chunk of the earliest
// rebuilt page (the kernel's cursor_back) before any request is admitted.
if sh.rebuilt {
if h := upgradeRewindTestHook; h != nil {
h()
}
if err := p.Rewind(sh.cursorBack); err != nil {
return err
}
}
if d := upgradePassTestInterval; d > 0 {
p.interval = d
}
if n := upgradePassTestPersistEvery; n > 0 {
p.persistEvery = n
}
l.stMu.Lock()
l.pass = p
l.stMu.Unlock()
return nil
}
// runUpgradePass starts the pass prepareUpgradePass set up, once the attach
// has started the record's publisher.
func (l *chunkLayerImpl) runUpgradePass() {
l.stMu.Lock()
p := l.pass
l.stMu.Unlock()
if p == nil || p.Admit() == nil {
return // no pass, or it ended before this attach
}
l.wg.Add(1)
go func() {
defer l.wg.Done()
err := p.Run(l.ctx)
if err != nil && l.ctx.Err() != nil {
// A stop: the pages of every chunk compared so far are written
// through and the cursor persisted (at most persistEvery chunks
// of work), so the next attach resumes there. The stop waits
// for this, never for the rest of the pass.
if err := p.advance(); err != nil {
log.Printf("level=WARN storage: upgrade compare pass: cursor at stop: %v", err)
}
return
}
if err != nil {
l.stMu.Lock()
l.passErr = err
l.stMu.Unlock()
log.Printf("level=WARN storage: upgrade compare pass stopped: %v", err)
}
}()
}
// upgradePassTestInterval, set by tests only, slows the pass (a pause between
// chunks) so a test can act while it runs; upgradePassTestPersistEvery
// persists its cursor more often; upgradeCompareTestHook sees each chunk the
// pass compares.
var (
upgradePassTestDisabled bool // tests of the upgrade itself: the state it leaves, no pass after it
upgradePassTestInterval time.Duration
upgradePassTestPersistEvery uint64
upgradeCompareTestHook func(ctx context.Context, idx uint64)
upgradeRewindTestHook func()
dueLoopStartTestHook func() // the attach is about to start the record's due loop
upgradeAfterReadTestHook func(idx uint64)
)
// upgradeCompare compares one chunk with HEAD for the pass: an unknown local
// chunk is read and hashed, and its record takes the hash (and HEAD's
// publication when HEAD names that hash), the same transitions a cut's
// compare makes. It reports whether the chunk was unknown.
func (l *chunkLayerImpl) upgradeCompare(ctx context.Context, idx uint64) (bool, error) {
sh := l.shadow
if sh == nil || sh.rec.Kind(idx) != chunkkernel.Unknown {
return false, nil
}
l.stMu.Lock()
absent := l.absent[idx]
version := l.chunkVersion(idx)
base := l.cutBaseLocked(map[uint64]bool{idx: true})
l.stMu.Unlock()
if absent {
return false, nil // not local: nothing to compare
}
if h := upgradeCompareTestHook; h != nil {
h(ctx, idx)
}
data, err := l.readChunk(idx)
if err != nil {
return false, err
}
if h := upgradeAfterReadTestHook; h != nil {
h(idx)
}
c := capturedChunk{idx: idx, version: version, data: data, sum: sha256.Sum256(data), zero: isAllZero(data)}
sh.hashed(c, func() uint64 { return l.chunkVersion(idx) }, base)
// Superseded by a write: a write since the read leaves the chunk unknown
// (the record refused the stale version's hash). The premise: during the
// pass only the write path moves a chunk's version, and a write marks the
// chunk dirty (chunkMut), so the next cut takes it as any written chunk,
// also after a restart (the write is in the WAL). It is not counted as
// compared.
if sh.rec.Kind(idx) == chunkkernel.Unknown {
l.passSuperseded.Add(1)
return false, nil
}
return true, nil
}
// admitUpgradePass refuses a request that seals or publishes while the pass
// has not ended (typed, with its progress) and hurries the pass from then on.
func (l *chunkLayerImpl) admitUpgradePass() error {
l.stMu.Lock()
p := l.pass
l.stMu.Unlock()
if p == nil {
return nil
}
err := p.Admit()
if err != nil {
l.passHurry.Do(func() { _ = p.Hurry() }) // released never: the pass ends
}
return err
}
// upgradePassStatusLocked is the pass's status for Stats. Caller holds stMu.
func (l *chunkLayerImpl) upgradePassStatusLocked() UpgradePassStatus {
if l.pass == nil {
return l.passStatus
}
compared, total, done := l.pass.progress()
st := UpgradePassStatus{State: "running", Compared: compared, Total: total, Superseded: l.passSuperseded.Load()}
switch {
case l.passErr != nil:
st.State, st.Outcome = "failed", l.passErr.Error()
case done:
st.State = "done"
}
return st
}
// firstUnknown is the record's first unknown chunk, if any (O(S), once at
// attach).
func (s *chunkRecordShadow) firstUnknown() (uint64, bool) {
s.rec.mu.Lock()
defer s.rec.mu.Unlock()
for i, code := range s.rec.kinds {
if kindByCode[code] == chunkkernel.Unknown {
return uint64(i), true
}
}
return 0, false
}
@@ -0,0 +1,450 @@
package storage
import (
"bytes"
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/chunkkernel"
)
// uncleanUpgradeStore is a v1.0 store of 16 chunks written as HEAD has them
// (chunks 1-3 nonzero), and a fake remote holding that HEAD: attached on the
// v1.1 format with no clean-stop proof, every chunk opens unknown.
func uncleanUpgradeStore(t *testing.T) (*WALStore, string, *fakeChunkRemote) {
t.Helper()
s, path := v11Store(t)
if err := s.SetLayoutIdentity("claim-a", false); err != nil {
t.Fatal(err)
}
head := make([]byte, int(s.NumBlocks())*ctBlockSize)
for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ {
copy(head[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
if _, err := s.Write(uint32(lba), head[lba*ctBlockSize:(lba+1)*ctBlockSize]); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
f := newFakeChunkRemote()
f.seedHead(t, head, syncedPos(s), 1)
return s, path, f
}
func uncleanAttach(t *testing.T, s *WALStore, f *fakeChunkRemote) *chunkLayerImpl {
t.Helper()
cfg := ctConfig(2)
cfg.Bitmap = nil
return mustAttach(t, s, f, cfg).(*chunkLayerImpl)
}
func waitPass(t *testing.T, l *chunkLayerImpl, what string, ok func(UpgradePassStatus) bool) UpgradePassStatus {
t.Helper()
for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(10 * time.Millisecond) {
st := l.Stats().UpgradePass
if ok(st) {
return st
}
if time.Now().After(deadline) {
t.Fatalf("%s: pass status %+v", what, st)
}
}
}
// withoutUpgradePass attaches with no compare pass after the upgrade, for a
// test of the upgrade itself (the record state it leaves) or of something
// the pass would only slow down.
func withoutUpgradePass(t *testing.T) {
t.Helper()
upgradePassTestDisabled = true
t.Cleanup(func() { upgradePassTestDisabled = false })
}
// blockPassAt makes the pass stop at chunk at (inside its compare) until the
// returned release is called or the pass is stopped (Close); reached is
// closed when it gets there. The test acts while the pass is held there, with
// no timing, and no cleanup order can join a held pass.
func blockPassAt(t *testing.T, at uint64) (reached <-chan struct{}, release func()) {
t.Helper()
withoutPassWait(t)
r, rel := make(chan struct{}), make(chan struct{})
var once, relOnce sync.Once
upgradeCompareTestHook = func(ctx context.Context, idx uint64) {
if idx == at {
once.Do(func() { close(r) })
select {
case <-rel:
case <-ctx.Done():
}
}
}
release = func() { relOnce.Do(func() { close(rel) }) }
t.Cleanup(func() { release(); upgradeCompareTestHook, upgradePassTestPersistEvery = nil, 0 })
return r, release
}
func waitReached(t *testing.T, reached <-chan struct{}) {
t.Helper()
select {
case <-reached:
case <-time.After(20 * time.Second):
t.Fatal("the pass never reached its barrier")
}
}
// A stop mid-pass never waits for the pass: Close returns at once, with the
// pages of the chunks compared so far written and the cursor persisted. The
// next attach resumes at that cursor (no chunk below it is compared again),
// the status carries the count across the stop, and the pass ends with no
// chunk unknown.
func TestV11UpgradePassStopResumesAtTheCursor(t *testing.T) {
withV11Format(t)
const at = 5
reached, _ := blockPassAt(t, at)
upgradePassTestPersistEvery = 2
s, path, f := uncleanUpgradeStore(t)
l := uncleanAttach(t, s, f)
waitReached(t, reached) // chunks 0-4 compared, the pass held inside chunk 5
if st := l.Stats().UpgradePass; st.State != "running" || st.Total != l.numChunks {
t.Fatalf("status while held: %+v", st)
}
closed := make(chan error, 1)
go func() { closed <- l.Close() }() // the stop releases the held compare: no release() can win before it
select {
case err := <-closed:
if err != nil {
t.Fatal(err)
}
case <-time.After(10 * time.Second):
t.Fatal("Close waited for the rest of the pass")
}
_, epoch := s.ChunkStateMarker()
cur, err := readUpgradePassCursor(chunkRecordDir(path), epoch)
// The stop lands inside chunk at's compare: the cursor is at+1 when that
// compare completed, at when it was cut short; every chunk below it is
// compared either way.
if err != nil || (cur.Next != at && cur.Next != at+1) || cur.Compared != cur.Next {
t.Fatalf("the cursor at the stop: %+v %v; want next %d or %d with every chunk below it compared", cur, err, at, at+1)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
var mu sync.Mutex
var again []uint64
upgradeCompareTestHook = func(_ context.Context, idx uint64) {
mu.Lock()
again = append(again, idx)
mu.Unlock()
}
l2 := uncleanAttach(t, r, f)
st := waitPass(t, l2, "the resumed pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" })
mu.Lock()
defer mu.Unlock()
for _, idx := range again {
if idx < cur.Next {
t.Fatalf("the resumed pass compared chunk %d again, below its cursor %d", idx, cur.Next)
}
}
if st.Compared != l2.numChunks {
t.Fatalf("done status %+v; want every one of %d chunks compared across the stop", st, l2.numChunks)
}
for c := uint64(0); c < l2.numChunks; c++ {
if k := shadowKind(l2, c); k == chunkkernel.Unknown {
t.Fatalf("chunk %d still unknown after the resumed pass", c)
}
}
}
// Every request that seals or publishes waits for the pass: while it runs, a
// cut and a sealing detach are refused with ErrUpgradePassInProgress (its
// progress, nothing published, HEAD still active); once it is done the same
// cut and detach succeed. A sealing detach never degrades to an unsealed one.
func TestV11SealingRequestsWaitForTheUpgradePass(t *testing.T) {
withV11Format(t)
reached, release := blockPassAt(t, 3)
s, _, f := uncleanUpgradeStore(t)
l := uncleanAttach(t, s, f)
waitReached(t, reached) // the pass is running, held inside chunk 3
casBefore := f.stats().cas
for name, op := range map[string]func() error{
"cut": func() error { _, err := l.Cut(ctTimeout(t)); return err },
"detach": func() error { _, err := l.Detach(ctTimeout(t)); return err },
} {
var refusal *ErrUpgradePassInProgress
if err := op(); !errors.As(err, &refusal) || refusal.Total != l.numChunks {
t.Fatalf("%s during the pass: %v, want ErrUpgradePassInProgress with the progress", name, err)
}
}
if f.stats().cas != casBefore || chunkHeadIsDetached(f.stats().head) {
t.Fatal("a refused request published or detached HEAD")
}
release()
waitPass(t, l, "the pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" })
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatalf("cut after the pass: %v", err)
}
r, err := l.Detach(ctTimeout(t))
if err != nil || r.Head.State != chunkHeadDetached {
t.Fatalf("sealing detach after the pass: %+v %v, want a sealed (detached) HEAD", r.Head, err)
}
}
// A page rebuilt at open (damage) leaves its chunks unknown again behind the
// pass's cursor: the attach rewinds the cursor, durably and before any
// request is admitted, to the first of them and compares them again, so none
// stays unknown. Both a pass that had ended (a completed cursor) and one
// stopped midway (a partial cursor) rewind.
func TestV11UpgradePassRewindsBelowItsCursorAfterARebuiltPage(t *testing.T) {
for _, partial := range []bool{false, true} {
t.Run(map[bool]string{false: "completed cursor", true: "partial cursor"}[partial], func(t *testing.T) {
withV11Format(t)
s, path, f := uncleanUpgradeStore(t)
var l *chunkLayerImpl
if partial {
reached, _ := blockPassAt(t, 8)
upgradePassTestPersistEvery = 2
l = uncleanAttach(t, s, f)
waitReached(t, reached)
closed := make(chan error, 1)
go func() { closed <- l.Close() }() // the stop, not a release, lets the held compare go
select {
case err := <-closed:
if err != nil {
t.Fatal(err)
}
case <-time.After(10 * time.Second):
t.Fatal("Close waited for the rest of the pass")
}
upgradeCompareTestHook = nil
} else {
l = uncleanAttach(t, s, f) // waits for the pass: it ends
if st := l.Stats().UpgradePass; st.State != "done" {
t.Fatalf("setup: pass %+v, want done", st)
}
if err := l.shadow.rec.Flush(); err != nil {
t.Fatal(err)
}
}
_, epoch := s.ChunkStateMarker()
before, err := readUpgradePassCursor(chunkRecordDir(path), epoch)
if err != nil || before.Next == 0 {
t.Fatalf("setup: cursor %+v %v", before, err)
}
if err := os.WriteFile(filepath.Join(chunkRecordDir(path), chunkRecordPageName(0)), []byte("damaged"), 0o644); err != nil {
t.Fatal(err)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
reached, release := blockPassAt(t, 1)
l2 := uncleanAttach(t, r, f)
waitReached(t, reached) // chunk 0 compared, chunk 1 held: nothing persisted by the pass yet
if cur, err := readUpgradePassCursor(chunkRecordDir(path), epoch); err != nil || cur.Next != 0 {
t.Fatalf("the cursor on disk while the rewound pass runs: %+v %v; want rewound to chunk 0 before any compare", cur, err)
}
release()
waitPass(t, l2, "the rewound pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" })
for c := uint64(0); c < l2.numChunks; c++ {
if k := shadowKind(l2, c); k == chunkkernel.Unknown {
t.Fatalf("chunk %d stayed unknown after the rebuilt page: the pass did not rewind (cursor was %d)", c, before.Next)
}
}
if st := l2.Stats().UpgradePass; st.State != "done" {
t.Fatalf("pass after the rewind: %+v", st)
}
if _, err := l2.Cut(ctTimeout(t)); err != nil {
t.Fatalf("cut after the rewound pass: %v", err)
}
})
}
}
// A chunk written between the pass's read and its hash is superseded by the
// write: not hashed (the record refuses the stale version), not counted as
// compared, reported as superseded. It is dirty, so the next cut publishes it
// as any written chunk; after a crash before that cut it is still a
// candidate, and the cut after the restart publishes it.
func TestV11AChunkWrittenDuringItsCompareGoesToTheNextCut(t *testing.T) {
for _, crash := range []bool{false, true} {
t.Run(map[bool]string{false: "next cut", true: "crash before the next cut"}[crash], func(t *testing.T) {
withV11Format(t)
s, path, f := uncleanUpgradeStore(t)
const hot = 2
var once sync.Once
upgradeAfterReadTestHook = func(idx uint64) {
if idx == hot {
once.Do(func() {
if _, err := s.Write(uint32(hot*ctChunkBlocks), makeBlock(ctBlockSize, 0xEE)); err != nil {
t.Error(err)
}
})
}
}
t.Cleanup(func() { upgradeAfterReadTestHook = nil })
l := uncleanAttach(t, s, f)
upgradeAfterReadTestHook = nil
st := l.Stats().UpgradePass
if st.State != "done" || st.Compared != l.numChunks-1 || st.Superseded != 1 {
t.Fatalf("pass %+v; want done, every chunk but the written one compared, one superseded", st)
}
if k := shadowKind(l, hot); k != chunkkernel.Unknown {
t.Fatalf("the chunk written during its compare is %s, want still unknown (not hashed with a stale version)", k)
}
if crash {
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
l = uncleanAttach(t, r, f)
}
before := f.stats().cas
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if k := shadowKind(l, hot); k == chunkkernel.Unknown {
t.Fatal("the next cut left the written chunk unknown")
}
if f.stats().cas == before {
t.Fatal("the next cut published nothing: the written chunk was not a candidate")
}
img := f.imageOf(t, f.stats().head)
if got := img[hot*ctChunkBytes : hot*ctChunkBytes+ctBlockSize]; !bytes.Equal(got, makeBlock(ctBlockSize, 0xEE)) {
t.Fatalf("the published chunk %d starts %x, want the bytes written during its compare", hot, got[:8])
}
})
}
}
// The pass's cursor file is the storage package's own: no production code
// outside it names the file (status reports the pass; nothing else reads the
// cursor). The control: the scan finds the name in the pass's own file.
func TestUpgradePassCursorIsReadOnlyByStorage(t *testing.T) {
root := filepath.Join("..", "..")
var found []string
ownSeen := false
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if n := d.Name(); n == ".git" || n == "vendor" || n == "testdata" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return nil
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
if !strings.Contains(string(b), "pass-cursor") {
return nil
}
if filepath.ToSlash(filepath.Dir(p)) == filepath.ToSlash(filepath.Join(root, "core", "storage")) {
ownSeen = true
return nil
}
found = append(found, p)
return nil
})
if err != nil {
t.Fatal(err)
}
if !ownSeen {
t.Fatal("control: the scan did not find the cursor file's name in the storage package")
}
if len(found) > 0 {
t.Fatalf("production code outside storage names the pass cursor file: %v", found)
}
}
// An unseeded upgrade writes the pass's first cursor before the store's
// marker: a crash right after the upgrade, before the pass persisted anything
// (here, the first attach ran no pass at all), restarts with that cursor, so
// the pass runs, cuts are refused until it ends, and no chunk stays unknown.
func TestV11ACrashBeforeThePassFirstPersistsStillRunsThePass(t *testing.T) {
withV11Format(t)
s, path, f := uncleanUpgradeStore(t)
upgradePassTestDisabled = true // the attach after the upgrade starts no pass: as if killed at once
l := uncleanAttach(t, s, f)
upgradePassTestDisabled = false
if k := shadowKind(l, 1); k != chunkkernel.Unknown {
t.Fatalf("setup: chunk 1 after the unseeded upgrade is %s, want U", k)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
reached, release := blockPassAt(t, 3)
l2 := uncleanAttach(t, r, f)
if st := l2.Stats().UpgradePass; st.State != "running" {
t.Fatalf("the attach after the restart: pass %+v, want running (the cursor written before the marker)", st)
}
waitReached(t, reached)
var refusal *ErrUpgradePassInProgress
if _, err := l2.Cut(ctTimeout(t)); !errors.As(err, &refusal) {
t.Fatalf("a cut after the restart, during the pass: %v, want in_progress", err)
}
release()
waitPass(t, l2, "the pass after the restart never ended", func(st UpgradePassStatus) bool { return st.State == "done" })
for c := uint64(0); c < l2.numChunks; c++ {
if k := shadowKind(l2, c); k == chunkkernel.Unknown {
t.Fatalf("chunk %d still unknown after the restart's pass", c)
}
}
}
// A page rebuilt at open is republished (the record's due loop) only after
// the pass's rewind is durable: otherwise a crash between the two leaves the
// page valid on disk under the old cursor, the next open sees no damage, and
// the chunks the page had stay unknown with no pass to compare them.
func TestV11ARebuiltPageIsNotRepublishedBeforeTheRewindIsDurable(t *testing.T) {
withV11Format(t)
s, path, f := uncleanUpgradeStore(t)
l := uncleanAttach(t, s, f) // waits for the pass: it ends
if err := l.shadow.rec.Flush(); err != nil {
t.Fatal(err)
}
page := filepath.Join(chunkRecordDir(path), chunkRecordPageName(0))
if err := os.WriteFile(page, []byte("damaged"), 0o644); err != nil {
t.Fatal(err)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
var dueStarted, rewound bool
dueLoopStartTestHook = func() { dueStarted = true }
upgradeRewindTestHook = func() {
rewound = true
if dueStarted {
t.Error("the record's due loop started before the rewind was durable")
}
if r.chunk.Load() != nil {
t.Error("the layer's hooks were attached (writes publish pages) before the rewind was durable")
}
if b, err := os.ReadFile(page); err != nil || string(b) != "damaged" {
t.Errorf("the rebuilt page was rewritten before the rewind was durable: %v", err)
}
}
t.Cleanup(func() { dueLoopStartTestHook, upgradeRewindTestHook = nil, nil })
l2 := uncleanAttach(t, r, f)
if !rewound || !dueStarted {
t.Fatalf("setup: rewound %v, due loop started %v; want both", rewound, dueStarted)
}
for c := uint64(0); c < l2.numChunks; c++ {
if k := shadowKind(l2, c); k == chunkkernel.Unknown {
t.Fatalf("chunk %d stayed unknown after the rebuilt page", c)
}
}
}
@@ -34,6 +34,9 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) {
e.Local = e.Local.mark(lba%cb, count)
}
v.mapEntries.set(index, e)
if h := s.chunk.Load(); h != nil {
h.sink.OnMapEntryChange(uint64(index))
}
}
// Recover may scan retained records already represented by the durable bitmap.
@@ -18,6 +18,7 @@ func (h *heldWALReadMiss) OnReadMiss(uint64) ([]byte, error) {
return nil, nil
}
func (*heldWALReadMiss) OnExtentWrite(uint64, uint64) {}
func (*heldWALReadMiss) OnMapEntryChange(uint64) {}
func (*heldWALReadMiss) BeforeCheckpointAdvance(uint64) error { return nil }
func (*heldWALReadMiss) BeginBaseInstall() error { return nil }
func (*heldWALReadMiss) EndBaseInstall(uint64) error { return nil }
+9 -3
View File
@@ -637,6 +637,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-TOUCHED-001` | The barrier's candidate step judges only a touched set (a chunk bitmap with a word summary) with INV-WAL-V3-CAPTURE-CANDIDATES-001's predicate, never every chunk; the set covers every chunk whose answer may have changed since the barrier took it. The cut syncs before the barrier, outside the pause. | M5 candidate selection (CandBitmap: NoBitLost, SummaryCovers) | `chunk_layer.go` `candidatesFrom`, `takeTouched`, `seedTouched`, `touch`, `OnMapEntryChange`, `noteMutation`, `setHeadLocked`, `applyCommitLocked`; `walstore_map_checkpoint_v3.go` `recordMapWriteV3`; `base_install_v3.go` `markMapUnknownV3`; `chunk_record_candidates.go` `candidateSet` | `TestIdleCutCandidateWorkIsFlatInS`, `TestOneChangedChunkCutVisitsNoFullScan`, `TestCutSyncsBeforeItsBarrier`, `TestUnknownCommitOutcomeLosesNoChunk`, `TestCandidateSetOrBackKeepsTheSummary` (`chunk_cut_candidate_set_test.go`); `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestACleanFillRecordEndsWithItsHeadRef` (`chunk_fresh_readback_candidates_test.go`); `TestSpacePerChunkAt1TiBShape` (`chunk_space_baseline_test.go`) | The candidate set is the same; an idle cut's candidate work no longer grows with S | ACTIVE |
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE |
| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB |
| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE |
@@ -647,7 +648,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-CHUNK-RECORD-SEED-001` | The v1.0.x upgrade seeds a whole local chunk as published with HEAD's hash only on an unmarked store, with a clean stop read on the HEAD the claim was built on (an idle detach of the store's lineage) at the store's synced position; otherwise it is unknown. | M1 Recovering → Serving (v1.1 upgrade at attach, after a clean stop) | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `TestStart_ReportsTheCleanStopItClaimedFrom`, `TestStart_TheCleanStopIsTheClaimsOwnRead`, `TestStart_NoCleanStopWithoutADetachOfThisLineage` (`core/frontend/chunkstore/layout/start_cleanstop_test.go`); `TestUpgradeSeedsAfterACleanStop`, `TestUpgradeSeedNeedsTheStoreAtTheProofPosition`, `TestUpgradeSeedNeedsTheStoresLineage`, `TestUpgradeSeedNeedsAProofHEADStillShows`, `TestUpgradeSeedCrashAtEachStep` (`core/storage/chunk_record_seed_test.go`); `TestV11AttachSeedsFromTheCleanStopInItsConfig` (`core/storage/chunk_record_v11_seed_test.go`); `TestStartLayoutRootReportsTheCleanStop` (`core/frontend/durable/provider_layout_cleanstop_test.go`) | UpgradeWide3 rows 122 and 123 (`Proof`, `SameEpoch` judged on the HEAD the claim is built on; the claim is a stutter on image and position), 126 to 128 (the per-chunk state models are not in this repository) | STUB |
| `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB |
| `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a hash only with its evidence; a page dirties only on a state or hash change and is written by its count or age (an evict's at once), in snapshot order, after the WAL is synced through the position it shows; G <= min(applied, dirty-from, WAL synced). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush`, `writeSegmentLocked` (`syncThrough`), `writeHeaderLocked` (`durable`) | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`); the WAL bound: `TestV11NoPageClaimsMoreThanTheDurableWAL`, `TestV11APageNeverShowsAWriteTheWALCanLose` (`core/storage/chunk_record_v11_review_test.go`, `chunk_record_v11_hold_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB |
| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE |
| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped`, `TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE |
| `INV-CHUNK-RECORD-V11-001` | On the draft v1.1 format a layer upgrades its store once at attach and opens from its record; a fill's page claims no local block before one durable mark (partial fills and later writes too); an evict clears the store's bits only after its absent page is durable, retries too. | M1 Opened, M3 Serving (draft v1.1 format) | `core/storage/chunk_record_open.go` `openChunkRecordV11`, `loadChunkRecordV11`, `markFills`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordWith`; `core/storage/chunk_record_runtime.go` `holdFills`, `PersistSegmentOf`; `core/storage/chunk_record_shadow.go` `evict`; `core/storage/chunk_layer.go` `EvictChunk`, `Close` | `TestV11AttachUpgradesTheStoreOnce`, `TestV11ReopenJudgesAWriteAfterThePageAsChanged`, `TestV11CleanStopWritesOnlyTheDirtyPages`, `TestV11UpgradeRecoversFromACrashAtEachStep`, `TestV11DamagedPageIsRebuiltFromTheStoreBits`, `TestV11FillsAreMarkedInOneBatchBeforeTheirPagesClaimThem`, `TestV11EvictSurvivesARestart` (`core/storage/chunk_record_v11_test.go`); `TestV11CloseDuringTheUpgradeRefusesTheAttach`, `TestV11EvictWithoutItsAbsentPageClearsNothing`, `TestV11ParkedFillBatchCannotOverwriteAnEvict`, `TestV11MalformedLeftoverPresenceDoesNotRefuseTheAttach`, `TestV11FinalPageFailureIsTheCloseResult` (`core/storage/chunk_record_v11_review_test.go`); `TestV11PartialFillWaitsForTheDurableMark`, `TestV11WriteAfterAHeldFillKeepsTheHold`, `TestV11EvictRetryStillWritesItsAbsentPage` (`core/storage/chunk_record_v11_hold_test.go`); `TestV11AbsentChunkSurvivesALostHeader`, `TestV11LogOnlyWriteSurvivesTheUpgrade` (`core/storage/chunk_record_v11_upgrade_test.go`) | chunk-kernel/2; CoverageDurable row 199 (the WAL is durable through a published position) (not in this repository) | DORMANT |
| `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE |
| `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB |
@@ -820,8 +821,13 @@ Notes:
| `INV-WS-LEASE-HORIZON-001` | Retired: v1.1 keeps no lease horizon current; renewals write nothing and a restarted master waits for its own restart floor (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
| `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE |
| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL, own monotonic clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
| `INV-WS-AUTH-RECORD-V2-001` | Before it serves, this master writes the store's attestation file as format 2, on which a v1.0.x master refuses its whole start; its authority records are envelope version 2 (a v1.0.x master would skip them). It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileInTheEnvelope`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
| `INV-WS-RESTART-GRACE-001` | At format level 1, a renewal writes nothing durable. A forced move, an expired re-grant and a no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
| `INV-WS-AUTH-RECORD-V2-001` | The format finalize writes the store's attestation file as format 2 (`INV-FMT-LEVEL-001`), on which a v1.0.x master refuses its whole start; from then on its authority records are envelope version 2 (a v1.0.x master would skip them); before it, both are v1.0's. It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
| `INV-FMT-LEVEL-001` | The cluster's format level is the attestation file's form: v1.0.x's bare map is level 0, the envelope (format 2, format_level 1) level 1. It only rises: the finalize is its only writer, and an envelope below level 1 is refused at start. | FormatGate Finalize (level 0 → 1) | `core/host/master/store_attestation.go` `decodeStoreAttestations`, `finalize`, `persist`, `level`; `core/host/master/host.go` `New` | `TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable`, `TestAnAttestationEnvelopeBelowLevel1IsRefused` (`core/host/master/format_gate_test.go`); `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAV100MasterRefusesTheAttestationEnvelope` (`core/host/master/golden_v100_test.go`) | `FormatGate` `OneWay` (mutation `level_lowered`) | ACTIVE |
| `INV-FMT-FINALIZE-001` | The finalize is refused, naming them, while a registered host has not reported reads_level >= 1 since the master started. Else it writes the envelope durably, then switches the publisher under both its locks, then answers; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `belowLevel`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable`, `TestAFailedFinalizeWriteLeavesLevel0` (`core/host/master/format_gate_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE |
| `INV-FMT-ELIGIBLE-001` | At format level L no new work goes to a server that reads below L or has not reported: no placement, workspace placement or move target, and its heartbeat is refused binary_too_old. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRefusesAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE |
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
+19
View File
@@ -24,9 +24,28 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one
`level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An
explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses.
- A cut's barrier no longer walks every chunk to find its candidates: its candidate work is the chunks that
changed plus one summary word per 4,096 chunks, so an idle cut's pause does not grow with the volume's size. The
cut also syncs the store once right before its barrier, outside the guest pause (reported as `PreSyncNs`), so the
pause's own sync has only what was written after it.
## Upgrade
- With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was
created with, and v1.1's differ. Upgrade such a host whole: stop every process using the directory, remove
`<dir>/configuration.json`, then start them all on v1.1. Until then a new process refuses the directory, naming the
file and this cure, and a host that mixes old and new processes skips background cuts with an alarm.
- **The v1.1 format is switched on by the operator, and going back works until then.** v1.1 keeps writing the v1.0
format, and blockmaster keeps v1.0's lease semantics, until `sw-block cluster finalize-format --master <addr>`. Each
host reports the format its binary reads; the finalize refuses while a registered host has not reported that it
reads v1.1, and names each one: upgrade it, or retire it (`sw-block cluster retire-host --server <id> --confirm <id>
--master <addr>`, refused while the host still holds a volume).
- Before the finalize, going back to v1.0.x works: stop the v1.1 binaries and start v1.0.x. Name-only snapshot
deletes keep v1.0's semantics until then (a retry after a lost answer may act twice).
- The finalize is one-way. Afterwards a v1.0.x blockmaster refuses to start on the store, and a v1.0.x holder that
meets a volume v1.1 has opened refuses it and writes nothing to it, but exits with a status its systemd unit
treats as retryable, so the unit restarts it until its start limit. With its local store it answers `invalid
superblock`; without one, `HEAD written by a newer version` (v1.0.0 and v1.0.1 report that HEAD as malformed).
None of these means damage: do not rebuild the volume; start v1.1 again.
- After the finalize, a host whose binary does not read v1.1 is refused (`binary_too_old`) and gets no volume.
- v1.1 answers the reverse case, a store or HEAD written by a later version, with a final exit 78
(`store_format_newer`, `head_newer_version`), which the unit does not restart.
+9
View File
@@ -273,6 +273,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `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.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. |
| `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. |
| `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. |
| `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. |
@@ -315,6 +318,12 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `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.CutSeq` | uint64 | successful cuts of this layer so far (in-process); the latest cut's identity |
| `Volumes[].Chunk.Stats.UpgradePass` | object | the upgrade compare pass after a v1.0 store's upgrade (v1.1): none, seeded, running, done or failed |
| `Volumes[].Chunk.Stats.UpgradePass.State` | string | none, seeded, running, done or failed; carried across a stop (read the status, never the pass's cursor file) |
| `Volumes[].Chunk.Stats.UpgradePass.Compared` | uint64 | chunks the pass found unknown and compared, across stops |
| `Volumes[].Chunk.Stats.UpgradePass.Total` | uint64 | chunks the pass walks |
| `Volumes[].Chunk.Stats.UpgradePass.Superseded` | uint64 | Superseded counts chunks written during their own compare (in this process): not hashed, not counted as compared; each is dirty and the next cut takes it as any written chunk. |
| `Volumes[].Chunk.Stats.UpgradePass.Outcome` | string | why a failed pass stopped; while the pass has not ended a cut, snapshot, backup or sealing detach is refused with code in_progress (omitted when empty) |
| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. |
| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. |
| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). |