mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge branch 'feat/oss-snap-begin' into feat/oss-snap-abort
# Conflicts: # docs/design/invariants.md
This commit is contained in:
commit
8aef3e04cb
20 files changed
+1379
-32
No files matched your search
@@ -0,0 +1,427 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// INV-WS-DELETE-NO-LIVE-HOLDER-001, the guard half: a restore target created but never
|
||||
// attached (no blockvolume ever started for it) is deletable already on 1.0.
|
||||
// volume-delete completes without a revoke, its HEAD becomes a deleted
|
||||
// tombstone, and the source volume and its snapshot are untouched. The 1.0.1
|
||||
// red half is a target whose blockvolume started, was assigned and exited
|
||||
// before it claimed HEAD (the TestNeverStartedLine... tests below).
|
||||
func TestNeverAttachedRestoreTargetIsDeletable(t *testing.T) {
|
||||
env := startHandoffEnvWith(t, 1, []string{"v2"})
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
holder := env.start(t, "blockvolume-v1", "s1")
|
||||
env.adopt(t, holder, "s1")
|
||||
env.writeBlock(t, "s1", 0, cutCrashBlock('N', 0))
|
||||
env.snapshot(t, "s1", "v1", "s1")
|
||||
|
||||
// The target exists in the catalog; its blockvolume never starts.
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
|
||||
out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC,
|
||||
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-never-started")
|
||||
var del struct{ Completed bool }
|
||||
if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed {
|
||||
t.Fatalf("volume-delete of a never-attached target must complete; exit %d:\n%s\n%s", code, out, errOut)
|
||||
}
|
||||
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
if !strings.Contains(shown, `"state":"deleted"`) {
|
||||
t.Fatalf("the deleted target's HEAD is not a deleted tombstone:\n%s", shown)
|
||||
}
|
||||
// The source and its snapshot are untouched.
|
||||
if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('N', 0)) {
|
||||
t.Fatalf("the source's block changed")
|
||||
}
|
||||
if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 {
|
||||
t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps))
|
||||
}
|
||||
}
|
||||
|
||||
// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the fence of NeverStarted -> Deleting): once a
|
||||
// never-attached target's delete is admitted, a late start of its blockvolume
|
||||
// must not claim it: the process exits without serving and the catalog still
|
||||
// says deleted. Recorded on 1.0 to see where it stands.
|
||||
func TestNeverStartedDeleteFencesALateStart(t *testing.T) {
|
||||
env := startHandoffEnvWith(t, 1, []string{"v2"})
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
holder := env.start(t, "blockvolume-v1", "s1")
|
||||
env.adopt(t, holder, "s1")
|
||||
env.writeBlock(t, "s1", 0, cutCrashBlock('L', 0))
|
||||
env.snapshot(t, "s1", "v1", "s1")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC,
|
||||
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-late")
|
||||
if code != 0 {
|
||||
t.Fatalf("volume-delete of a never-attached target: exit %d:\n%s\n%s", code, out, errOut)
|
||||
}
|
||||
b := env.hosts["n-v2"]
|
||||
late := env.h.start(t, "blockvolume-v2-late", env.h.volume, env.volArgsFor(b)...)
|
||||
err := late.wait(60 * time.Second)
|
||||
served := late.has("durable: HEAD claim for volume=v2 done") || volumeFrontendReady(b.status, "v2")
|
||||
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
t.Logf("late start after the delete: exit %v, served %v, HEAD %s", err, served, firstLine(shown))
|
||||
if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(shown, `"state":"deleted"`) {
|
||||
t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving and leave the volume deleted; exit %v, served %v, HEAD:\n%s", err, served, shown)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the race): a start of a never-attached target and its
|
||||
// volume-delete run at the same time, five times. Exactly one wins each time:
|
||||
// either the volume is deleted and the process never served, or the process
|
||||
// claimed and served and the delete is refused as for a live holder.
|
||||
func TestNeverStartedDeleteRacesAStart(t *testing.T) {
|
||||
targets := []string{"v2", "v3", "v4", "v5", "v6"}
|
||||
env := startHandoffEnvWith(t, 1, targets)
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
holder := env.start(t, "blockvolume-v1", "s1")
|
||||
env.adopt(t, holder, "s1")
|
||||
env.writeBlock(t, "s1", 0, cutCrashBlock('R', 0))
|
||||
env.snapshot(t, "s1", "v1", "s1")
|
||||
for _, v := range targets {
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
b := env.hosts["n-"+v]
|
||||
type delResult struct {
|
||||
out string
|
||||
code int
|
||||
}
|
||||
deleted := make(chan delResult, 1)
|
||||
d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
|
||||
defer cancel()
|
||||
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC,
|
||||
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-"+v+"-race")
|
||||
if err != nil {
|
||||
code = -1
|
||||
}
|
||||
deleted <- delResult{out + errOut, code}
|
||||
}()
|
||||
r := <-deleted
|
||||
_ = d.wait(30 * time.Second)
|
||||
// Served means the process claimed HEAD (no I/O is admitted before the
|
||||
// claim) or its frontend became ready; adopting the assignment comes
|
||||
// before the claim and is not serving.
|
||||
served := d.has("durable: HEAD claim for volume="+v+" done") || volumeFrontendReady(b.status, v)
|
||||
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
isDeleted := strings.Contains(shown, `"state":"deleted"`)
|
||||
t.Logf("%s: delete exit %d, served %v, HEAD deleted %v: %s", v, r.code, served, isDeleted, firstLine(r.out))
|
||||
switch {
|
||||
case r.code == 0 && isDeleted && !served:
|
||||
case r.code != 0 && served && !isDeleted:
|
||||
default:
|
||||
t.Errorf("1.0.1: %s: not exactly one winner: delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted)
|
||||
}
|
||||
d.kill(t)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *handoffEnv) workspaceShow(t *testing.T, v string) string {
|
||||
out, errOut, _ := env.h.run(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v)
|
||||
return out + errOut
|
||||
}
|
||||
|
||||
func (env *handoffEnv) deleteNoRevoke(ctx context.Context, v, request string) (string, int) {
|
||||
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC,
|
||||
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", request)
|
||||
if err != nil {
|
||||
code = -1
|
||||
}
|
||||
return out + errOut, code
|
||||
}
|
||||
|
||||
// lineOf returns the master's durable authority record for v (the line:
|
||||
// replica, epoch, and any workspace lease), as stored in --authority-store.
|
||||
func (env *handoffEnv) lineOf(t *testing.T, v string) string {
|
||||
t.Helper()
|
||||
dir := ""
|
||||
for i, a := range env.masterArgs {
|
||||
if a == "--authority-store" && i+1 < len(env.masterArgs) {
|
||||
dir = env.masterArgs[i+1]
|
||||
}
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, v+".v3auth.json"))
|
||||
if os.IsNotExist(err) {
|
||||
return "(no line)"
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(strings.Fields(string(data)), " ")
|
||||
}
|
||||
|
||||
// requireNeverStarted checks the state by its facts: the master's line for
|
||||
// v is at epoch e (with or without a lease, as lease says) and HEAD is below
|
||||
// it (epoch headEpoch).
|
||||
func (env *handoffEnv) requireNeverStarted(t *testing.T, v string, e, headEpoch uint64, lease bool) {
|
||||
t.Helper()
|
||||
line, head := env.lineOf(t, v), env.headOf(t, v)
|
||||
ok := strings.Contains(line, fmt.Sprintf(`"Epoch":%d,`, e)) && strings.Contains(head, fmt.Sprintf(`"epoch":%d,`, headEpoch)) &&
|
||||
strings.Contains(line, `"Lease":`) == lease
|
||||
if !ok {
|
||||
t.Fatalf("setup: %s is not a line at epoch %d (lease %v) over HEAD at epoch %d:\nline: %s\nHEAD: %s", v, e, lease, headEpoch, line, head)
|
||||
}
|
||||
t.Logf("%s: line %s\nHEAD %s", v, line, head)
|
||||
}
|
||||
|
||||
// strandStoreDown (S1): v's first start runs with the store (filer) down.
|
||||
// The process heartbeats and the master writes the line at epoch 1; local
|
||||
// readiness blocks before the assignment is applied, no lease is granted,
|
||||
// and the process exits. The filer comes back. Line at 1, no lease, HEAD 0.
|
||||
func (env *handoffEnv) strandStoreDown(t *testing.T, v string) {
|
||||
t.Helper()
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
env.cluster.stopProc(t, "filer")
|
||||
d := env.h.start(t, "blockvolume-"+v+"-store-down", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...)
|
||||
err := d.wait(120 * time.Second)
|
||||
env.cluster.restartProc(t, "filer")
|
||||
w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second)
|
||||
if err == nil || d.has("adopted as PRIMARY") {
|
||||
t.Fatalf("setup: %s's start with the store down exited %v, adopted %v", v, err, d.has("adopted as PRIMARY"))
|
||||
}
|
||||
env.requireNeverStarted(t, v, 1, 0, false)
|
||||
}
|
||||
|
||||
// strandAtGrant (S2): v's first start with the right flags is stopped
|
||||
// (SIGSTOP) the moment the master shows its lease granted, after the
|
||||
// adoption and before the HEAD claim, then killed. Line at 1 with a granted
|
||||
// lease, HEAD 0. When the claim wins the race the next candidate is tried;
|
||||
// it returns the stranded volume.
|
||||
func (env *handoffEnv) strandAtGrant(t *testing.T, candidates ...string) string {
|
||||
t.Helper()
|
||||
for _, v := range candidates {
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
d := env.h.start(t, "blockvolume-"+v+"-stopped-at-grant", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...)
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for !d.has("adopted as PRIMARY") && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
for time.Now().Before(deadline) {
|
||||
out, _, _, _ := runCLI(context.Background(), env.h, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v)
|
||||
if strings.Contains(out, "lease state: granted") {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := d.proc.Signal(syscall.SIGSTOP); err != nil {
|
||||
t.Fatalf("setup: stop %s: %v", v, err)
|
||||
}
|
||||
claimed := !strings.Contains(env.headOf(t, v), `"epoch":0,"holder":""`)
|
||||
_ = d.proc.Signal(syscall.SIGKILL)
|
||||
_ = d.wait(10 * time.Second)
|
||||
if claimed {
|
||||
t.Logf("%s: the claim won the race; trying the next candidate", v)
|
||||
continue
|
||||
}
|
||||
env.requireNeverStarted(t, v, 1, 0, true)
|
||||
return v
|
||||
}
|
||||
t.Fatalf("setup: the claim won the race for every candidate %v", candidates)
|
||||
return ""
|
||||
}
|
||||
|
||||
// 1.0.1 red (INV-WS-DELETE-NO-LIVE-HOLDER-001): a line whose epoch HEAD never
|
||||
// reached has acknowledged nothing, so volume-delete completes WITHOUT a
|
||||
// revoke; HEAD becomes a deleted tombstone, the source is untouched, and no
|
||||
// granted lease stays on the deleted volume. Routes, each without root:
|
||||
// - S1: a first start with the store down (line, no lease);
|
||||
// - S2: a first start stopped at the lease grant (line and lease), deleted
|
||||
// at once and again after the lease lapsed (65 s);
|
||||
// - clean move: the volume moved clean to a target that never starts (a
|
||||
// line and a lease at the new epoch, HEAD at the old one, detached).
|
||||
//
|
||||
// On 1.0 every delete is refused as volume_in_use (live authority needs a
|
||||
// revocation ACK that no process can give).
|
||||
func TestNeverStartedLineIsDeletableWithoutARevoke(t *testing.T) {
|
||||
deleted := func(t *testing.T, env *handoffEnv, v, request string) {
|
||||
t.Helper()
|
||||
before := env.workspaceShow(t, v)
|
||||
out, code := env.deleteNoRevoke(context.Background(), v, request)
|
||||
var del struct{ Completed bool }
|
||||
completed := code == 0 && json.Unmarshal([]byte(firstLine(out)), &del) == nil && del.Completed
|
||||
head, after := env.headOf(t, v), env.workspaceShow(t, v)
|
||||
t.Logf("delete exit %d, completed %v, HEAD %s\nworkspace show before:\n%s\nafter:\n%s\ndelete output:\n%s", code, completed, head, before, after, out)
|
||||
if !completed {
|
||||
t.Fatalf("1.0.1: volume-delete of %s (line above HEAD) must complete without a revoke; exit %d", v, code)
|
||||
}
|
||||
if !strings.Contains(head, `"state":"deleted"`) || strings.Contains(after, "lease state: granted") {
|
||||
t.Fatalf("a completed delete must leave a deleted HEAD and no granted lease")
|
||||
}
|
||||
}
|
||||
t.Run("S1-store-down", func(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v2")
|
||||
env.strandStoreDown(t, "v2")
|
||||
deleted(t, env, "v2", "del-v2-s1")
|
||||
requireSourceUntouched(t, env)
|
||||
})
|
||||
t.Run("S2-stopped-at-grant", func(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v3", "v3b", "v3c")
|
||||
v := env.strandAtGrant(t, "v3", "v3b", "v3c")
|
||||
deleted(t, env, v, "del-"+v+"-s2")
|
||||
requireSourceUntouched(t, env)
|
||||
})
|
||||
t.Run("S2-lease-lapsed", func(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v4", "v4b", "v4c")
|
||||
v := env.strandAtGrant(t, "v4", "v4b", "v4c")
|
||||
time.Sleep(65 * time.Second)
|
||||
deleted(t, env, v, "del-"+v+"-s2-lapsed")
|
||||
})
|
||||
t.Run("clean-move-target-never-started", func(t *testing.T) {
|
||||
env := startHandoffEnv(t, 2)
|
||||
must, mustU := fatalOn(t)
|
||||
old := env.start(t, "blockvolume-s1", "s1")
|
||||
e := env.adopt(t, old, "s1")
|
||||
env.writeBlock(t, "s1", 0, pattern("never-start-move"))
|
||||
g := env.seal(t, "s1", e)
|
||||
l := env.sealedLSN(t, e, g)
|
||||
env.revoke(t, e, g)
|
||||
must(old.wait(30 * time.Second))
|
||||
env.waitAck(t, e, g)
|
||||
out, _ := env.h.command(t, env.moveClean(e, "s2", "move-v1-1")...)
|
||||
e2 := mustU(movedEpochTo(out, e, g, l, "s2"))
|
||||
env.requireNeverStarted(t, "v1", e2, e, true)
|
||||
deleted(t, env, "v1", "del-v1-moved")
|
||||
})
|
||||
}
|
||||
|
||||
func requireSourceUntouched(t *testing.T, env *handoffEnv) {
|
||||
t.Helper()
|
||||
if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('A', 0)) {
|
||||
t.Fatalf("the source's block changed")
|
||||
}
|
||||
if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 {
|
||||
t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps))
|
||||
}
|
||||
}
|
||||
|
||||
// 1.0.1 red: after that delete, a start of the target with the store up
|
||||
// must not claim it: it exits without serving and the HEAD stays deleted.
|
||||
// S1 and S2.
|
||||
func TestNeverStartedLineDeleteFencesALateStart(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
targets []string
|
||||
}{
|
||||
{"S1-store-down", []string{"v2"}},
|
||||
{"S2-stopped-at-grant", []string{"v3", "v3b", "v3c"}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, c.targets...)
|
||||
v := c.targets[0]
|
||||
if c.name == "S1-store-down" {
|
||||
env.strandStoreDown(t, v)
|
||||
} else {
|
||||
v = env.strandAtGrant(t, c.targets...)
|
||||
}
|
||||
if out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-late"); code != 0 {
|
||||
t.Fatalf("1.0.1: volume-delete of %s (line above HEAD): exit %d:\n%s", v, code, out)
|
||||
}
|
||||
b := env.hosts["n-"+v]
|
||||
late := env.h.start(t, "blockvolume-"+v+"-late", env.h.volume, env.volArgsFor(b)...)
|
||||
err := late.wait(90 * time.Second)
|
||||
served := volumeFrontendReady(b.status, v)
|
||||
head := env.headOf(t, v)
|
||||
if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(head, `"state":"deleted"`) {
|
||||
t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving; exit %v, served %v, HEAD %s", err, served, head)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 1.0.1 red: a start (store up) of an S1 target and its volume-delete race,
|
||||
// with the start delayed by 0 s to 3 s. Each time exactly one wins: the
|
||||
// volume is deleted and never served, or it served and the delete was
|
||||
// refused. With a 3 s lead the delete must win.
|
||||
func TestNeverStartedLineDeleteRacesAStart(t *testing.T) {
|
||||
targets := []string{"v2", "v3", "v4", "v5", "v6"}
|
||||
delays := []time.Duration{0, 0, 200 * time.Millisecond, time.Second, 3 * time.Second}
|
||||
env := startSourceWithSnapshot(t, targets...)
|
||||
for i, v := range targets {
|
||||
env.strandStoreDown(t, v)
|
||||
b := env.hosts["n-"+v]
|
||||
type delResult struct {
|
||||
out string
|
||||
code int
|
||||
}
|
||||
deleted := make(chan delResult, 1)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
|
||||
defer cancel()
|
||||
out, code := env.deleteNoRevoke(ctx, v, "del-"+v+"-race")
|
||||
deleted <- delResult{out, code}
|
||||
}()
|
||||
time.Sleep(delays[i])
|
||||
d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...)
|
||||
r := <-deleted
|
||||
_ = d.wait(60 * time.Second)
|
||||
served := volumeFrontendReady(b.status, v)
|
||||
isDeleted := strings.Contains(env.headOf(t, v), `"state":"deleted"`)
|
||||
t.Logf("%s (start +%v): delete exit %d, served %v, HEAD deleted %v: %s", v, delays[i], r.code, served, isDeleted, firstLine(r.out))
|
||||
switch {
|
||||
case r.code == 0 && isDeleted && !served:
|
||||
case r.code != 0 && served && !isDeleted && delays[i] < 3*time.Second:
|
||||
default:
|
||||
t.Errorf("1.0.1: %s: want exactly one winner (the delete with a 3 s lead): delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted)
|
||||
}
|
||||
d.kill(t)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.0.1 red (master restart, one direction): the master is SIGKILLed and
|
||||
// restarted between the stranding and the delete; the delete still completes
|
||||
// without a revoke, from what the master and the HEAD keep durably. S1 and S2.
|
||||
func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) {
|
||||
for _, s2 := range []bool{false, true} {
|
||||
name := map[bool]string{false: "S1-store-down", true: "S2-stopped-at-grant"}[s2]
|
||||
t.Run(name, func(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v2", "v2b", "v2c")
|
||||
v := "v2"
|
||||
if s2 {
|
||||
v = env.strandAtGrant(t, "v2", "v2b", "v2c")
|
||||
} else {
|
||||
env.strandStoreDown(t, v)
|
||||
}
|
||||
restartKilledMaster(t, env)
|
||||
out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-after-restart")
|
||||
if head := env.headOf(t, v); code != 0 || !strings.Contains(head, `"state":"deleted"`) {
|
||||
t.Fatalf("1.0.1: after a master restart, volume-delete of %s must complete; exit %d, HEAD %s:\n%s", v, code, head, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guard, green on 1.0 (master restart, the other direction): a target whose
|
||||
// holder DID claim its HEAD, was SIGKILLed, and whose lease the restarted
|
||||
// master no longer holds in memory, is not never-started: volume-delete
|
||||
// without a revoke and an ACK is refused and the HEAD is not tombstoned.
|
||||
func TestClaimedTargetAfterAMasterRestartIsNotNeverStarted(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v2")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
d := env.startTarget(t, "v2", "blockvolume-v2")
|
||||
if head := env.headOf(t, "v2"); strings.Contains(head, `"holder":""`) {
|
||||
t.Fatalf("setup: v2 serves but its HEAD is not claimed: %s", head)
|
||||
}
|
||||
d.kill(t)
|
||||
restartKilledMaster(t, env)
|
||||
out, code := env.deleteNoRevoke(context.Background(), "v2", "del-v2-claimed")
|
||||
if head := env.headOf(t, "v2"); code == 0 || strings.Contains(head, `"state":"deleted"`) {
|
||||
t.Fatalf("a claimed target was deleted without a revoke after a master restart; exit %d, HEAD %s:\n%s", code, head, out)
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,26 @@ type WorkspaceHead struct {
|
||||
Gen, Epoch, RemoteLSN uint64
|
||||
Holder string
|
||||
Detached bool
|
||||
FilerMtimeNS int64
|
||||
// Deleting: HEAD is deleting, purging or deleted (returned with
|
||||
// ErrWorkspaceHeadDeleting): no claim can move it again.
|
||||
Deleting bool
|
||||
FilerMtimeNS int64
|
||||
}
|
||||
|
||||
// ErrWorkspaceHeadUnclaimed is a HEAD reader's answer for a volume's initial
|
||||
// HEAD that no holder ever claimed (epoch 0, no holder, active): the head
|
||||
// returned with it carries its generation and epoch 0. It names no identity,
|
||||
// so a caller that needs one treats it as any read error; the delete
|
||||
// admission reads it as never started (TERM-LIVE-HOLDER-001).
|
||||
var ErrWorkspaceHeadUnclaimed = errors.New("HEAD never claimed: epoch 0, no holder")
|
||||
|
||||
// ErrWorkspaceHeadDeleting is a HEAD reader's answer for a HEAD that is
|
||||
// deleting, purging or deleted: the head returned with it has Deleting set.
|
||||
// A caller that needs an active or detached identity treats it as any read
|
||||
// error; the delete admission reads it as past the fence (a re-run of a
|
||||
// delete that stopped midway).
|
||||
var ErrWorkspaceHeadDeleting = errors.New("HEAD is deleting, purging or deleted")
|
||||
|
||||
// ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its
|
||||
// issuing write failed after it may have reached the store, or the volume's
|
||||
// workspace persistence is already uncertain. Memory shows it unissued, but
|
||||
@@ -132,7 +149,16 @@ func (p *Publisher) RecordWorkspacePlacement(ctx context.Context, volume string,
|
||||
|
||||
// RecordWorkspaceDeletion protects reservation release against live or pending
|
||||
// authority. A current clean ACK is proof of drain; a lease alone is not.
|
||||
func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, pendingPlacement bool, persist func() error) error {
|
||||
// RecordWorkspaceDeletion admits a delete of volume (INV-WS-DELETE-NO-LIVE-HOLDER-001)
|
||||
// when it has no live holder (TERM-LIVE-HOLDER-001): no line (and no
|
||||
// placement that may have queued one), a clean revocation ACK for the line,
|
||||
// or a HEAD below the line's epoch (never started). head is HEAD as the
|
||||
// caller read it before taking any lock (nil: not read, which refuses a line
|
||||
// without an ACK, as before); owner is the line's owner "<server>/<replica>"
|
||||
// ("" when unknown), used only to name the refusal. A Sealed HEAD without an
|
||||
// ACK keeps the ACK rule. The delete's HEAD compare-and-swap to deleting is
|
||||
// the fence against a claim that lands after the read.
|
||||
func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, pendingPlacement bool, head *WorkspaceHead, owner string, persist func() error) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -142,12 +168,19 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
|
||||
if s != nil && len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued {
|
||||
return fmt.Errorf("workspace delete: move pending")
|
||||
}
|
||||
if _, line, ok := p.workspaceLineLocked(volume); ok {
|
||||
if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID {
|
||||
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete")
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
var ack *WorkspaceRevokeAck
|
||||
if s != nil {
|
||||
ack = s.Ack
|
||||
}
|
||||
switch v := WorkspaceHolderState(ok, line.info.Epoch, line.info.ReplicaID, owner, ack, head); v {
|
||||
case HolderNoLine:
|
||||
if pendingPlacement {
|
||||
return fmt.Errorf("workspace delete: placement may have queued authority")
|
||||
}
|
||||
} else if pendingPlacement {
|
||||
return fmt.Errorf("workspace delete: placement may have queued authority")
|
||||
case HolderDrained, HolderNeverStarted, HolderDeleting:
|
||||
default:
|
||||
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete (holder: %s)", v)
|
||||
}
|
||||
return persist()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// INV-WS-DELETE-NO-LIVE-HOLDER-001 at the admission itself
|
||||
// (RecordWorkspaceDeletion), on a line at epoch 2 whose ACK is for epoch 1: a
|
||||
// HEAD below the line is never started (admitted); an ACK of an older epoch
|
||||
// does not drain the line, so a HEAD claimed at epoch 2 is refused; a HEAD at
|
||||
// a higher epoch, another holder at the line's epoch, an unread HEAD and a
|
||||
// pending move are refused; a HEAD past the fence (deleting) is admitted.
|
||||
func TestDeleteAdmissionVerdicts(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
store, _ := newTempStore(t)
|
||||
p, _ := cleanMoveToGrantee(t, store, &now)
|
||||
const owner = "new-node/r"
|
||||
persisted := 0
|
||||
admit := func(head *WorkspaceHead) error {
|
||||
return p.RecordWorkspaceDeletion(context.Background(), "v", false, head, owner, func() error { persisted++; return nil })
|
||||
}
|
||||
refused := func(what string, head *WorkspaceHead) {
|
||||
t.Helper()
|
||||
before := persisted
|
||||
err := admit(head)
|
||||
if err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") || persisted != before {
|
||||
t.Fatalf("%s: %v (persisted %d -> %d); want refused before the reservation", what, err, before, persisted)
|
||||
}
|
||||
}
|
||||
refused("an ACK of epoch 1 with HEAD claimed at epoch 2", &WorkspaceHead{Gen: 8, Epoch: 2, Holder: owner})
|
||||
refused("HEAD at a higher epoch", &WorkspaceHead{Gen: 9, Epoch: 3, Holder: owner})
|
||||
refused("another holder at the line's epoch", &WorkspaceHead{Gen: 8, Epoch: 2, Holder: "third-node/r"})
|
||||
refused("HEAD not read", nil)
|
||||
head := predecessorHead // epoch 1: the grantee never claimed epoch 2
|
||||
if err := admit(&head); err != nil || persisted != 1 {
|
||||
t.Fatalf("HEAD below the line: %v (persisted %d); want admitted", err, persisted)
|
||||
}
|
||||
if err := admit(&WorkspaceHead{Gen: 9, Deleting: true}); err != nil || persisted != 2 {
|
||||
t.Fatalf("HEAD deleting (a rerun): %v (persisted %d); want admitted", err, persisted)
|
||||
}
|
||||
p.mu.Lock()
|
||||
s := cloneWorkspace(p.workspace["v"])
|
||||
s.Moves = append(s.Moves, WorkspaceMoveRecord{RequestID: "pending", VolumeID: "v", Kind: "clean"})
|
||||
p.workspace["v"] = s
|
||||
p.mu.Unlock()
|
||||
if err := admit(&head); err == nil || !strings.Contains(err.Error(), "move pending") {
|
||||
t.Fatalf("a pending move: %v; want refused", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package authority
|
||||
|
||||
// WorkspaceHolderVerdict is the one answer to "is there a live holder of V"
|
||||
// (TERM-LIVE-HOLDER-001). The line's holder at epoch e may have acknowledged
|
||||
// guest writes and may publish exactly when the verdict is Live.
|
||||
type WorkspaceHolderVerdict int
|
||||
|
||||
const (
|
||||
// HolderUnknown: HEAD was not read or could not be read, names a higher
|
||||
// epoch, or names another holder at the line's epoch. Always refused.
|
||||
HolderUnknown WorkspaceHolderVerdict = iota
|
||||
// HolderNoLine: there is no authority line.
|
||||
HolderNoLine
|
||||
// HolderDrained: a clean revocation ACK is recorded for the line.
|
||||
HolderDrained
|
||||
// HolderSealed: HEAD names the line's holder at its epoch, detached.
|
||||
HolderSealed
|
||||
// HolderNeverStarted: HEAD is below the line's epoch. No claim at that
|
||||
// epoch had applied when HEAD was read, so nothing was acknowledged or
|
||||
// published under it (no I/O is admitted before the claim), whatever
|
||||
// lease exists. The delete's HEAD compare-and-swap to deleting fences a
|
||||
// claim that lands after the read.
|
||||
HolderNeverStarted
|
||||
// HolderLive: HEAD names the line's holder at its epoch, active.
|
||||
HolderLive
|
||||
// HolderDeleting: HEAD is deleting, purging or deleted. No claim can
|
||||
// move it again, so it is past the delete's fence: a delete that stopped
|
||||
// midway (its commit timed out, its mark's outcome was unknown) is
|
||||
// admitted again and can finish.
|
||||
HolderDeleting
|
||||
)
|
||||
|
||||
func (v WorkspaceHolderVerdict) String() string {
|
||||
switch v {
|
||||
case HolderNoLine:
|
||||
return "no line"
|
||||
case HolderDrained:
|
||||
return "drained"
|
||||
case HolderSealed:
|
||||
return "sealed"
|
||||
case HolderNeverStarted:
|
||||
return "never started"
|
||||
case HolderLive:
|
||||
return "live"
|
||||
case HolderDeleting:
|
||||
return "deleting"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// WorkspaceHolderState decides the verdict from durable inputs only: the
|
||||
// authority line (present, epoch, replica, and its owner "<server>/<replica>"
|
||||
// by the single owner decision; "" when unknown), the recorded revocation
|
||||
// ACK, and HEAD as read (nil when it was not read or could not be read).
|
||||
// Pure: no I/O, no state, no clock. It does not depend on master memory, so
|
||||
// it holds across a blockmaster restart.
|
||||
func WorkspaceHolderState(linePresent bool, lineEpoch uint64, lineReplica, owner string, ack *WorkspaceRevokeAck, head *WorkspaceHead) WorkspaceHolderVerdict {
|
||||
switch {
|
||||
case !linePresent:
|
||||
return HolderNoLine
|
||||
case ack != nil && ack.Epoch == lineEpoch && ack.ReplicaID == lineReplica:
|
||||
return HolderDrained
|
||||
case head != nil && head.Deleting:
|
||||
return HolderDeleting
|
||||
case head == nil:
|
||||
return HolderUnknown
|
||||
case head.Epoch < lineEpoch:
|
||||
return HolderNeverStarted
|
||||
case head.Epoch > lineEpoch || owner == "" || head.Holder != owner:
|
||||
return HolderUnknown
|
||||
case head.Detached:
|
||||
return HolderSealed
|
||||
}
|
||||
return HolderLive
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package authority
|
||||
|
||||
import "testing"
|
||||
|
||||
// TERM-LIVE-HOLDER-001: one pure verdict from the line, the ACK and HEAD.
|
||||
// "Never started" is HEAD below the line's epoch, not "never leased"; every
|
||||
// doubtful case is Unknown (refused).
|
||||
func TestWorkspaceHolderState(t *testing.T) {
|
||||
const owner = "node-a/r1"
|
||||
head := func(epoch uint64, holder string, detached bool) *WorkspaceHead {
|
||||
return &WorkspaceHead{Gen: 3, Epoch: epoch, Holder: holder, Detached: detached}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
line bool
|
||||
ack *WorkspaceRevokeAck
|
||||
head *WorkspaceHead
|
||||
owner string
|
||||
want WorkspaceHolderVerdict
|
||||
}{
|
||||
{"no line", false, nil, nil, owner, HolderNoLine},
|
||||
{"ACK for the line", true, &WorkspaceRevokeAck{ReplicaID: "r1", Epoch: 2, HeadGen: 3}, nil, owner, HolderDrained},
|
||||
{"ACK for an older epoch", true, &WorkspaceRevokeAck{ReplicaID: "r1", Epoch: 1}, head(2, owner, true), owner, HolderSealed},
|
||||
{"HEAD not read", true, nil, nil, owner, HolderUnknown},
|
||||
{"HEAD never claimed (epoch 0)", true, nil, head(0, "", false), owner, HolderNeverStarted},
|
||||
{"HEAD at an older epoch", true, nil, head(1, "node-b/r1", false), owner, HolderNeverStarted},
|
||||
{"HEAD claimed at the line's epoch, active", true, nil, head(2, owner, false), owner, HolderLive},
|
||||
{"HEAD claimed at the line's epoch, sealed", true, nil, head(2, owner, true), owner, HolderSealed},
|
||||
{"another holder at the line's epoch", true, nil, head(2, "node-b/r1", false), owner, HolderUnknown},
|
||||
{"HEAD at a higher epoch", true, nil, head(3, owner, false), owner, HolderUnknown},
|
||||
{"owner unknown at the line's epoch", true, nil, head(2, owner, false), "", HolderUnknown},
|
||||
{"HEAD deleting (a delete that stopped midway)", true, nil, &WorkspaceHead{Gen: 4, Epoch: 0, Deleting: true}, owner, HolderDeleting},
|
||||
{"HEAD deleting at the line's epoch", true, nil, &WorkspaceHead{Gen: 4, Epoch: 2, Holder: owner, Deleting: true}, owner, HolderDeleting},
|
||||
} {
|
||||
if got := WorkspaceHolderState(c.line, 2, "r1", c.owner, c.ack, c.head); got != c.want {
|
||||
t.Errorf("%s: %s; want %s", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,10 @@ func DecodeRoot(b []byte) (Root, error) {
|
||||
if r.err != nil {
|
||||
return Root{}, r.err
|
||||
}
|
||||
again, _ := out.Encode()
|
||||
again, err := out.Encode()
|
||||
if err != nil {
|
||||
return Root{}, err
|
||||
}
|
||||
if !bytes.Equal(again, b) {
|
||||
return Root{}, fmt.Errorf("%w: root bytes are not canonical", ErrMalformed)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
)
|
||||
|
||||
// ErrMissing reports an object a root reaches that is not in the store: a
|
||||
// root, a segment or a chunk. It is never read as zeros.
|
||||
var ErrMissing = errors.New("layout: object missing")
|
||||
|
||||
// ErrCorrupt reports an object whose bytes do not match its name.
|
||||
var ErrCorrupt = errors.New("layout: object corrupt")
|
||||
|
||||
// Fetch reads the whole object at p. A missing object is (nil, false, nil);
|
||||
// any other failure is an error.
|
||||
type Fetch func(ctx context.Context, p string) (data []byte, found bool, err error)
|
||||
|
||||
// Reader resolves images of one volume: its roots and segments are read
|
||||
// from <base>/<volume>/, each chunk from the pool of the volume its root
|
||||
// entry names.
|
||||
type Reader struct {
|
||||
base, vol string
|
||||
fetch Fetch
|
||||
}
|
||||
|
||||
// NewReader returns a Reader of vol under base.
|
||||
func NewReader(base, vol string, fetch Fetch) (*Reader, error) {
|
||||
if err := checkOwner(vol); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fetch == nil {
|
||||
return nil, errors.New("layout: reader needs a fetch")
|
||||
}
|
||||
return &Reader{base: base, vol: vol, fetch: fetch}, nil
|
||||
}
|
||||
|
||||
// get fetches the object at rel under volume vol and checks its bytes hash
|
||||
// to want.
|
||||
func (r *Reader) get(ctx context.Context, vol, rel string, want Hash) ([]byte, error) {
|
||||
p := path.Join(r.base, vol, rel)
|
||||
b, ok, err := r.fetch(ctx, p)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("layout: read %s: %w", p, err)
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: %s", ErrMissing, p)
|
||||
}
|
||||
if got := Sum(b); got != want {
|
||||
return nil, fmt.Errorf("%w: %s hashes to %s", ErrCorrupt, p, got)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Image is one root of the volume, opened.
|
||||
type Image struct {
|
||||
r *Reader
|
||||
root Root
|
||||
}
|
||||
|
||||
// Open reads and checks the root rn.
|
||||
func (r *Reader) Open(ctx context.Context, rn RootName) (*Image, error) {
|
||||
b, err := r.get(ctx, r.vol, rn.Path(), rn.Hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err := DecodeRoot(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: root %s: %v", ErrCorrupt, rn, err)
|
||||
}
|
||||
return &Image{r: r, root: root}, nil
|
||||
}
|
||||
|
||||
// Segment reads the segment of shard; ok is false when the root names no
|
||||
// segment for it (every index of the shard reads as zeros).
|
||||
func (img *Image) Segment(ctx context.Context, shard uint64) (seg Segment, ok bool, err error) {
|
||||
n, ok := img.root.Segments[shard]
|
||||
if !ok {
|
||||
return Segment{}, false, nil
|
||||
}
|
||||
b, err := img.r.get(ctx, img.r.vol, n.Path(), n.Hash)
|
||||
if err != nil {
|
||||
return Segment{}, false, err
|
||||
}
|
||||
seg, err = DecodeSegment(b)
|
||||
if err != nil {
|
||||
return Segment{}, false, fmt.Errorf("%w: segment %s: %v", ErrCorrupt, n, err)
|
||||
}
|
||||
if seg.Shard != shard {
|
||||
return Segment{}, false, fmt.Errorf("%w: segment %s holds shard %d", ErrCorrupt, n, seg.Shard)
|
||||
}
|
||||
return seg, true, nil
|
||||
}
|
||||
|
||||
// Chunk is a resolved chunk: zeros, or the bytes of Ref.
|
||||
type Chunk struct {
|
||||
Zero bool
|
||||
Ref Ref
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Resolve finds the entry of index: root -> segment -> ref. An index the
|
||||
// root does not name is zeros; a segment the root names but the store lacks
|
||||
// is ErrMissing.
|
||||
func (img *Image) Resolve(ctx context.Context, index uint64) (ref Ref, zero bool, err error) {
|
||||
seg, ok, err := img.Segment(ctx, Shard(index))
|
||||
if err != nil {
|
||||
return Ref{}, false, err
|
||||
}
|
||||
if !ok {
|
||||
return Ref{}, true, nil
|
||||
}
|
||||
ref, ok = seg.Chunks[index]
|
||||
if !ok {
|
||||
return Ref{}, true, nil
|
||||
}
|
||||
return ref, false, nil
|
||||
}
|
||||
|
||||
// Chunk resolves index and reads its bytes from the pool of the volume
|
||||
// that owns it. A chunk the root names but the owner's pool lacks is
|
||||
// ErrMissing.
|
||||
func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) {
|
||||
ref, zero, err := img.Resolve(ctx, index)
|
||||
if err != nil {
|
||||
return Chunk{}, err
|
||||
}
|
||||
if zero {
|
||||
return Chunk{Zero: true}, nil
|
||||
}
|
||||
b, err := img.r.get(ctx, ref.Owner, ref.Chunk.Path(), ref.Chunk.Hash)
|
||||
if err != nil {
|
||||
return Chunk{}, err
|
||||
}
|
||||
return Chunk{Ref: ref, Data: b}, nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// objStore is a fake store of whole objects by full path.
|
||||
type objStore struct {
|
||||
obj map[string][]byte
|
||||
fail string // a path whose fetch fails
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (s *objStore) fetch(_ context.Context, p string) ([]byte, bool, error) {
|
||||
s.asked = append(s.asked, p)
|
||||
if p == s.fail {
|
||||
return nil, false, errors.New("filer unavailable")
|
||||
}
|
||||
b, ok := s.obj[p]
|
||||
return b, ok, nil
|
||||
}
|
||||
|
||||
const base = "/swblock/chunks"
|
||||
|
||||
// readFixture: volume "t" (a restore target) whose root names chunk 3
|
||||
// ("own") in its own pool, chunk 10002 ("src data") in the pool of "src",
|
||||
// and nothing else; every object is written.
|
||||
func readFixture(t *testing.T) (*objStore, RootName, map[uint64]Ref) {
|
||||
t.Helper()
|
||||
s := &objStore{obj: map[string][]byte{}}
|
||||
put := func(vol, rel string, b []byte) { s.obj[path.Join(base, vol, rel)] = b }
|
||||
own := NameChunk(3, []byte("own"))
|
||||
foreign := NameChunk(10002, []byte("src data"))
|
||||
put("t", own.Path(), []byte("own"))
|
||||
put("src", foreign.Path(), []byte("src data"))
|
||||
m := map[uint64]Ref{3: {Owner: "t", Chunk: own}, 10002: {Owner: "src", Chunk: foreign}}
|
||||
root, segs, err := Build(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for n, b := range segs {
|
||||
put("t", n.Path(), b)
|
||||
}
|
||||
rn, rb, err := NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put("t", rn.Path(), rb)
|
||||
return s, rn, m
|
||||
}
|
||||
|
||||
func newReader(t *testing.T, s *objStore) *Reader {
|
||||
t.Helper()
|
||||
r, err := NewReader(base, "t", s.fetch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestRead_OwnChunk(t *testing.T) {
|
||||
s, rn, _ := readFixture(t)
|
||||
r := newReader(t, s)
|
||||
img, err := r.Open(context.Background(), rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := img.Chunk(context.Background(), 3)
|
||||
if err != nil || c.Zero || !bytes.Equal(c.Data, []byte("own")) || c.Ref.Owner != "t" {
|
||||
t.Fatalf("chunk 3: %+v %v", c, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An index the root does not name reads as zeros: in a shard with a
|
||||
// segment, and in a shard with none. Zeros never touch the pool.
|
||||
func TestRead_AbsentIndexIsZeros(t *testing.T) {
|
||||
s, rn, _ := readFixture(t)
|
||||
r := newReader(t, s)
|
||||
img, err := r.Open(context.Background(), rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, idx := range []uint64{4, 9999, 10001, 50000} {
|
||||
s.asked = nil
|
||||
c, err := img.Chunk(context.Background(), idx)
|
||||
if err != nil || !c.Zero || c.Data != nil {
|
||||
t.Fatalf("index %d: %+v %v; want zeros", idx, c, err)
|
||||
}
|
||||
for _, p := range s.asked {
|
||||
if strings.Contains(p, "/"+PoolDir+"/") {
|
||||
t.Fatalf("index %d read the pool (%s) for a zero chunk", idx, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A foreign name resolves in the source volume's pool, never in the
|
||||
// reading volume's.
|
||||
func TestRead_ForeignChunkFromSourcePool(t *testing.T) {
|
||||
s, rn, m := readFixture(t)
|
||||
// A same-named object in t's own pool must not be what is read.
|
||||
s.obj[path.Join(base, "t", m[10002].Chunk.Path())] = []byte("decoy")
|
||||
r := newReader(t, s)
|
||||
img, err := r.Open(context.Background(), rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.asked = nil
|
||||
c, err := img.Chunk(context.Background(), 10002)
|
||||
if err != nil || c.Zero || !bytes.Equal(c.Data, []byte("src data")) || c.Ref.Owner != "src" {
|
||||
t.Fatalf("chunk 10002: %+v %v", c, err)
|
||||
}
|
||||
want := path.Join(base, "src", m[10002].Chunk.Path())
|
||||
if got := s.asked[len(s.asked)-1]; got != want {
|
||||
t.Fatalf("read %s; want the source pool path %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A missing segment or chunk is an error, never zeros; so is a missing
|
||||
// root.
|
||||
func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Run("root", func(t *testing.T) {
|
||||
s, rn, _ := readFixture(t)
|
||||
delete(s.obj, path.Join(base, "t", rn.Path()))
|
||||
if _, err := newReader(t, s).Open(ctx, rn); !errors.Is(err, ErrMissing) {
|
||||
t.Fatalf("open of a missing root: %v; want ErrMissing", err)
|
||||
}
|
||||
})
|
||||
t.Run("segment", func(t *testing.T) {
|
||||
s, rn, _ := readFixture(t)
|
||||
img, err := newReader(t, s).Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delete(s.obj, path.Join(base, "t", img.root.Segments[1].Path()))
|
||||
for _, idx := range []uint64{10002, 10003} { // named, and not named, in that shard
|
||||
c, err := img.Chunk(ctx, idx)
|
||||
if !errors.Is(err, ErrMissing) || c.Zero {
|
||||
t.Fatalf("index %d with its segment missing: %+v %v; want ErrMissing", idx, c, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("own chunk", func(t *testing.T) {
|
||||
s, rn, m := readFixture(t)
|
||||
delete(s.obj, path.Join(base, "t", m[3].Chunk.Path()))
|
||||
img, err := newReader(t, s).Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, err := img.Chunk(ctx, 3); !errors.Is(err, ErrMissing) || c.Zero {
|
||||
t.Fatalf("missing own chunk: %+v %v; want ErrMissing", c, err)
|
||||
}
|
||||
})
|
||||
t.Run("foreign chunk", func(t *testing.T) {
|
||||
s, rn, m := readFixture(t)
|
||||
delete(s.obj, path.Join(base, "src", m[10002].Chunk.Path()))
|
||||
img, err := newReader(t, s).Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, err := img.Chunk(ctx, 10002); !errors.Is(err, ErrMissing) || c.Zero {
|
||||
t.Fatalf("missing foreign chunk: %+v %v; want ErrMissing", c, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A failed fetch is an error and not ErrMissing; bytes that do not match
|
||||
// their name are ErrCorrupt.
|
||||
func TestRead_FetchFailureAndCorruption(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, rn, m := readFixture(t)
|
||||
r := newReader(t, s)
|
||||
img, err := r.Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.fail = path.Join(base, "t", m[3].Chunk.Path())
|
||||
if _, err := img.Chunk(ctx, 3); err == nil || errors.Is(err, ErrMissing) {
|
||||
t.Fatalf("failed fetch: %v; want an error that is not ErrMissing", err)
|
||||
}
|
||||
s.fail = ""
|
||||
for name, p := range map[string]string{
|
||||
"chunk": path.Join(base, "t", m[3].Chunk.Path()),
|
||||
"segment": path.Join(base, "t", img.root.Segments[0].Path()),
|
||||
} {
|
||||
s2, rn2, _ := readFixture(t)
|
||||
s2.obj[p] = append(append([]byte(nil), s2.obj[p]...), 'x')
|
||||
img2, err := newReader(t, s2).Open(ctx, rn2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := img2.Chunk(ctx, 3); !errors.Is(err, ErrCorrupt) {
|
||||
t.Errorf("%s altered: %v; want ErrCorrupt", name, err)
|
||||
}
|
||||
}
|
||||
s3, rn3, _ := readFixture(t)
|
||||
rp := path.Join(base, "t", rn3.Path())
|
||||
s3.obj[rp] = append(append([]byte(nil), s3.obj[rp]...), 0)
|
||||
if _, err := newReader(t, s3).Open(ctx, rn3); !errors.Is(err, ErrCorrupt) {
|
||||
t.Errorf("root altered: %v; want ErrCorrupt", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A segment stored under one shard's name but holding another shard is
|
||||
// refused (its bytes match its hash, so only the shard check catches it).
|
||||
func TestRead_SegmentOfAnotherShardRefused(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := &objStore{obj: map[string][]byte{}}
|
||||
seg := Segment{Shard: 2, Chunks: map[uint64]Ref{20000: {Owner: "t", Chunk: NameChunk(20000, []byte("z"))}}}
|
||||
sn, sb, err := NameSegment(seg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lie := SegName{Shard: 0, Hash: sn.Hash}
|
||||
s.obj[path.Join(base, "t", lie.Path())] = sb
|
||||
root := Root{Segments: map[uint64]SegName{0: lie}}
|
||||
rn, rb, err := NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.obj[path.Join(base, "t", rn.Path())] = rb
|
||||
img, err := newReader(t, s).Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := img.Chunk(ctx, 5); !errors.Is(err, ErrCorrupt) {
|
||||
t.Fatalf("segment of shard 2 under shard 0: %v; want ErrCorrupt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewReader_RefusesBadInput(t *testing.T) {
|
||||
f := func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }
|
||||
if _, err := NewReader(base, "a/b", f); err == nil {
|
||||
t.Error("volume with a slash accepted")
|
||||
}
|
||||
if _, err := NewReader(base, "t", nil); err == nil {
|
||||
t.Error("nil fetch accepted")
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,9 @@ func ingestRF3Incarnations(t *testing.T, h *Host, r1, r2, r3 rf3Slot) {
|
||||
type switchProbe struct {
|
||||
mu sync.Mutex
|
||||
currentReady bool
|
||||
// currentUnknown: the current primary did not answer (status GET
|
||||
// refused or timed out), so CurrentKnown is false.
|
||||
currentUnknown bool
|
||||
// When hold is set, a probe signals entered and then blocks until
|
||||
// release is closed.
|
||||
hold bool
|
||||
@@ -99,7 +102,7 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit
|
||||
// Only r2 is seen, so its promotion needs a known frontier
|
||||
// it covers (#181); r3 is silent in these tests.
|
||||
SyncAckLSN: 70,
|
||||
CurrentKnown: true,
|
||||
CurrentKnown: !p.currentUnknown,
|
||||
Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, DurableLSN: 70},
|
||||
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}},
|
||||
}, nil
|
||||
@@ -213,6 +216,24 @@ func TestBootGrace_UnsupportedPathHonorsGraceThenFailsOver(t *testing.T) {
|
||||
expectFailoverToR2(t, h, "unready past its boot grace")
|
||||
}
|
||||
|
||||
// A current primary that did not answer its status probe is UNKNOWN, not
|
||||
// failed: the unsupported path never reassigns on it, however ready the
|
||||
// survivor (an unknown fact is never read as failed). Only a positive
|
||||
// not-ready report from the primary itself moves the line.
|
||||
func TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary(t *testing.T) {
|
||||
h := newBootGraceMaster(t, Config{})
|
||||
defer closeTestMaster(t, h)
|
||||
p := probeOf(t, h)
|
||||
|
||||
p.mu.Lock()
|
||||
p.currentUnknown = true
|
||||
p.mu.Unlock()
|
||||
unsupportedTick(t, h, readySlot("r1-a"))
|
||||
expectLineStaysR1(t, h, "status probe of the current primary timed out")
|
||||
unsupportedTick(t, h, readySlot("r1-a"))
|
||||
expectLineStaysR1(t, h, "still unanswered on the next tick")
|
||||
}
|
||||
|
||||
// An explicit unhealthy current primary gets no grace on this path.
|
||||
func TestBootGrace_UnsupportedPathUnhealthyCurrentFailsOverAtOnce(t *testing.T) {
|
||||
h := newBootGraceMaster(t, Config{})
|
||||
|
||||
@@ -336,7 +336,9 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac
|
||||
break
|
||||
}
|
||||
}
|
||||
if enabledCandidate && (!result.CurrentKnown || !result.Current.Ready) {
|
||||
// Only a positive not-ready report from the current primary moves the
|
||||
// line. A primary that did not answer is unknown, never failed.
|
||||
if enabledCandidate && result.CurrentKnown && !result.Current.Ready {
|
||||
// Unsupported does not mean the current primary is unhealthy:
|
||||
// a different slot may be stale. Judge the current primary
|
||||
// from its own fresh heartbeat slot, never from placement.
|
||||
|
||||
@@ -544,7 +544,7 @@ func TestMountedFailover_ProductLoopRF3ProbeCanAuthorizeStaleHeartbeatReadiness(
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentSlotMissingButSurvivorProbeReady(t *testing.T) {
|
||||
func TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing(t *testing.T) {
|
||||
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{
|
||||
ExpectedSlotsPerVolume: 3,
|
||||
})
|
||||
@@ -570,28 +570,22 @@ func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentSlotMissingButSurvivor
|
||||
}
|
||||
|
||||
// K8s can keep the server/node fresh while the generated primary
|
||||
// blockvolume pod is gone. That produces PartialInventory and excludes
|
||||
// the volume from the normal supported snapshot; the product loop must
|
||||
// still use placement + probe evidence to promote an eligible survivor.
|
||||
// blockvolume pod is gone: PartialInventory, and the current primary's
|
||||
// status cannot be read (CurrentKnown false). That is UNKNOWN, not
|
||||
// failed: on a partition the primary may still be serving, so no
|
||||
// automatic reassign happens, however ready the survivors. Failover is
|
||||
// an admin forced move with its barrier.
|
||||
ingestRF3PartialInventoryMissingCurrent(t, h, "vol-rf3", "node-a", "node-b", "node-c")
|
||||
placements := h.Lifecycle().Placements.ListPlacements()
|
||||
report := authority.SupportabilityReport{Unsupported: map[string]authority.VolumeUnsupportedEvidence{
|
||||
"vol-rf3": {VolumeID: "vol-rf3", Reasons: []string{authority.ReasonPartialInventory}},
|
||||
}}
|
||||
probes, blocked, asks := h.applyUnsupportedPromotionEvidenceGate(placements, report, nil)
|
||||
if probes != 1 || blocked != 0 || len(asks) != 1 {
|
||||
line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3")
|
||||
t.Fatalf("probes=%d blocked=%d asks=%+v placements=%+v line=%+v want one direct unsupported promotion ask", probes, blocked, asks, placements, line)
|
||||
probes, _, asks := h.applyUnsupportedPromotionEvidenceGate(placements, report, nil)
|
||||
if probes != 1 || len(asks) != 0 {
|
||||
t.Fatalf("probes=%d asks=%+v; want one probe and no reassign for an unanswered current primary", probes, asks)
|
||||
}
|
||||
if asks[0].ReplicaID != "r3" || asks[0].Intent != authority.IntentReassign {
|
||||
t.Fatalf("ask=%+v want highest durable survivor r3 reassign", asks[0])
|
||||
}
|
||||
if err := h.ctrl.SubmitAssignmentAsk(asks[0]); err != nil {
|
||||
t.Fatalf("submit unsupported promotion ask: %v", err)
|
||||
}
|
||||
failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3")
|
||||
if failover.Epoch != 2 || failover.EndpointVersion != 1 {
|
||||
t.Fatalf("failover line=%+v want highest durable survivor r3@2/1", failover)
|
||||
if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); line.ReplicaID != "r1" || line.Epoch != initial.Epoch {
|
||||
t.Fatalf("line=%+v; want r1@%d unchanged", line, initial.Epoch)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -106,7 +107,10 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe
|
||||
return nil, lifecycleError("delete workspace bindings", err)
|
||||
}
|
||||
_, placed := stores.Placements.GetPlacement(req.GetVolumeId())
|
||||
err = s.host.Publisher().RecordWorkspaceDeletion(ctx, req.GetVolumeId(), bound && placed, func() error {
|
||||
// The lifecycle delete does not read HEAD: a line without an ACK is
|
||||
// refused here even when it never started (INV-WS-DELETE-NO-LIVE-HOLDER-001
|
||||
// admits that only through the chunk volume delete and its HEAD fence).
|
||||
err = s.host.Publisher().RecordWorkspaceDeletion(ctx, req.GetVolumeId(), bound && placed, nil, "", func() error {
|
||||
if e := stores.Placements.DeletePlacement(req.GetVolumeId()); e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -131,6 +135,11 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe
|
||||
// workload planner, binding/placement/move RPCs and CreateVolume all refuse
|
||||
// it.
|
||||
func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
|
||||
// HEAD and the line's owner, read before any lock (as MoveWorkspace
|
||||
// does), bounded: a HEAD below the line's epoch proves the line never
|
||||
// started (TERM-LIVE-HOLDER-001). A read that fails leaves head nil,
|
||||
// which refuses a line without an ACK (fail closed).
|
||||
head, owner := s.deleteHolderEvidence(ctx, req.GetVolumeId())
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -151,7 +160,21 @@ func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolu
|
||||
_, placed := stores.Placements.GetPlacement(vol)
|
||||
var res lifecycle.DeletionReservation
|
||||
var persistErr error
|
||||
err = s.host.Publisher().RecordWorkspaceDeletion(ctx, vol, bound && placed, func() error {
|
||||
// A rerun of a delete whose token already holds the reservation (or a
|
||||
// committed one) was decided by its first admission: it is not decided
|
||||
// again. It goes on to the catalog step, whose HEAD compare-and-swap is
|
||||
// the fence: a HEAD a holder claimed in between is refused there and the
|
||||
// reservation given back, so neither the volume nor its id is stranded.
|
||||
if r, held := stores.Deletions.Get(vol); held && (r.State == lifecycle.ReservationCommitted || slices.Contains(r.Tokens, req.GetToken())) {
|
||||
res, persistErr = stores.Deletions.Admit(vol, req.GetToken())
|
||||
if persistErr != nil {
|
||||
return nil, status.Errorf(codes.Unavailable, "mark volume deleting: %v", persistErr)
|
||||
}
|
||||
_, known := stores.Volumes.GetVolume(vol)
|
||||
s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q known=%t state=%s (rerun of a held delete)", vol, known, res.State)
|
||||
return &control.MarkVolumeDeletingResponse{Known: known, State: res.State}, nil
|
||||
}
|
||||
err = s.host.Publisher().RecordWorkspaceDeletion(ctx, vol, bound && placed, head, owner, func() error {
|
||||
res, persistErr = stores.Deletions.Admit(vol, req.GetToken())
|
||||
return persistErr
|
||||
})
|
||||
@@ -974,3 +997,29 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme
|
||||
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
|
||||
return fact
|
||||
}
|
||||
|
||||
// deleteHolderEvidence reads vol's HEAD with the configured reader, bounded
|
||||
// at 5 s, and the published line's owner "<server>/<replica>". Either may be
|
||||
// missing: no reader, a failed read or no line gives a nil head or "".
|
||||
func (s *services) deleteHolderEvidence(ctx context.Context, vol string) (*authority.WorkspaceHead, string) {
|
||||
owner := ""
|
||||
if line, ok := s.host.Publisher().PublishedAuthorityLine(vol); ok {
|
||||
if server := s.host.workspaceLineOwner(line, vol, line.ReplicaID, line.Epoch); server != "" {
|
||||
owner = server + "/" + line.ReplicaID
|
||||
}
|
||||
}
|
||||
if s.host.cfg.WorkspaceHeadReader == nil || vol == "" {
|
||||
return nil, owner
|
||||
}
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
head, err := s.host.cfg.WorkspaceHeadReader(readCtx, vol)
|
||||
if errors.Is(err, authority.ErrWorkspaceHeadUnclaimed) || errors.Is(err, authority.ErrWorkspaceHeadDeleting) {
|
||||
return &head, owner // the initial HEAD (never claimed), or one past the delete's fence
|
||||
}
|
||||
if err != nil {
|
||||
s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q: HEAD unreadable (%v); a line without an ACK is refused", vol, err)
|
||||
return nil, owner
|
||||
}
|
||||
return &head, owner
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
// INV-WS-DELETE-NO-LIVE-HOLDER-001 on the real master: a line whose holder
|
||||
// never claimed HEAD at its epoch is admitted for delete without an ACK, on
|
||||
// HEAD's evidence read before the locks; a HEAD claimed at the line's epoch,
|
||||
// or one that cannot be read, is refused as before; the lifecycle
|
||||
// DeleteVolume RPC (which reads no HEAD) refuses even the never-started line.
|
||||
func TestDeleteAdmitsANeverStartedLine(t *testing.T) {
|
||||
var headEpoch atomic.Int64
|
||||
var headFails, headDeleting atomic.Bool
|
||||
h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
if headFails.Load() {
|
||||
return authority.WorkspaceHead{}, errors.New("filer unreachable")
|
||||
}
|
||||
if headDeleting.Load() { // marked by the delete
|
||||
return authority.WorkspaceHead{Gen: 3, Deleting: true}, authority.ErrWorkspaceHeadDeleting
|
||||
}
|
||||
e := uint64(headEpoch.Load())
|
||||
if e == 0 { // the initial HEAD, as the filer reader returns it
|
||||
return authority.WorkspaceHead{Gen: 2}, authority.ErrWorkspaceHeadUnclaimed
|
||||
}
|
||||
return authority.WorkspaceHead{Gen: 2, Epoch: e, Holder: "node-a/r1"}, nil
|
||||
}, nil)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
for i, vol := range []string{"v", "w"} {
|
||||
reviewCreate(t, conn, ctx, vol)
|
||||
ws := control.NewWorkspaceServiceClient(conn)
|
||||
b := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-a", DataAddr: fmt.Sprintf("127.0.0.1:%d", 10000+2*i), CtrlAddr: fmt.Sprintf("127.0.0.1:%d", 10001+2*i)}
|
||||
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: vol, ServerId: "node-a", ReplicaId: "r1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reviewHeartbeat(t, conn, ctx, vol, "node-a", b.DataAddr, b.CtrlAddr)
|
||||
}
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, h.Publisher(), "v")
|
||||
waitAuthorityLine(t, h.Publisher(), "w")
|
||||
// A lease granted, HEAD never claimed: the stranded state the release
|
||||
// candidate could not delete.
|
||||
if _, err := control.NewWorkspaceServiceClient(conn).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lc := control.NewLifecycleServiceClient(conn)
|
||||
mark := func(vol, token string) error {
|
||||
_, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: vol, Token: token})
|
||||
return err
|
||||
}
|
||||
refusedLive := func(what string, err error) {
|
||||
t.Helper()
|
||||
if err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") {
|
||||
t.Fatalf("%s: %v; want the live-authority refusal", what, err)
|
||||
}
|
||||
}
|
||||
|
||||
headEpoch.Store(int64(line.Epoch)) // claimed at the line's epoch: live
|
||||
refusedLive("HEAD claimed at the line's epoch", mark("v", "del-live"))
|
||||
headFails.Store(true) // unreadable HEAD: fail closed
|
||||
refusedLive("HEAD unreadable", mark("v", "del-unreadable"))
|
||||
headFails.Store(false)
|
||||
headEpoch.Store(0) // never claimed
|
||||
_, err := lc.DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "w"})
|
||||
refusedLive("the lifecycle DeleteVolume of a never-started line", err)
|
||||
res, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"})
|
||||
if err != nil || res.GetState() != lifecycle.ReservationAdmitted {
|
||||
t.Fatalf("delete of a never-started line: %+v %v; want admitted without an ACK", res, err)
|
||||
}
|
||||
// The delete stopped before it marked HEAD, and the holder then claimed
|
||||
// HEAD (its lease was still valid): a rerun of the same delete (its token
|
||||
// holds the reservation) is admitted without a new verdict, so it reaches
|
||||
// the catalog step, whose HEAD fence refuses the live HEAD and gives the
|
||||
// reservation back. A different delete is still decided, and refused.
|
||||
headEpoch.Store(int64(line.Epoch))
|
||||
res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"})
|
||||
if err != nil || res.GetState() != lifecycle.ReservationAdmitted {
|
||||
t.Fatalf("rerun of an admitted delete after the holder claimed HEAD: %+v %v; want admitted (the catalog step decides)", res, err)
|
||||
}
|
||||
refusedLive("a new delete while the holder holds HEAD", mark("v", "del-other"))
|
||||
headEpoch.Store(0)
|
||||
// The delete marked HEAD deleting, then its commit timed out: the re-run
|
||||
// is admitted again (HEAD past the fence), not stranded as volume_in_use.
|
||||
headDeleting.Store(true)
|
||||
res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"})
|
||||
if err != nil || res.GetState() != lifecycle.ReservationAdmitted {
|
||||
t.Fatalf("re-run after a commit that timed out: %+v %v; want admitted again", res, err)
|
||||
}
|
||||
// A NEW delete request (another token, so no held-token skip) meeting the
|
||||
// deleting HEAD is decided by the verdict, and the verdict admits it: a
|
||||
// HEAD past the fence is HolderDeleting, not a live holder.
|
||||
res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-second-request"})
|
||||
if err != nil || res.GetState() != lifecycle.ReservationAdmitted {
|
||||
t.Fatalf("a new delete request meeting a deleting HEAD: %+v %v; want admitted by the verdict", res, err)
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,17 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori
|
||||
return authority.WorkspaceHead{}, err
|
||||
}
|
||||
// DecodeHeadDocument above owns the supported-format checks.
|
||||
// The initial HEAD of a volume no holder ever claimed: epoch 0, no
|
||||
// holder, active. It names no identity, so callers that need one get
|
||||
// an error as before; the delete reads it as "never started".
|
||||
// A HEAD the delete has marked (deleting, purging, deleted): no claim
|
||||
// can move it again; the delete's re-run reads it as past the fence.
|
||||
if doc.Gen > 0 && doc.LegacyDetached == nil && (doc.State == "deleting" || doc.State == "purging" || doc.State == "deleted") {
|
||||
return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, Deleting: true, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadDeleting
|
||||
}
|
||||
if doc.Gen > 0 && doc.Epoch == 0 && doc.Holder == "" && doc.LegacyDetached == nil && doc.DetachedBy == nil && (doc.State == "" || doc.State == "active") {
|
||||
return authority.WorkspaceHead{Gen: doc.Gen, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadUnclaimed
|
||||
}
|
||||
if doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") {
|
||||
return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state")
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
)
|
||||
|
||||
// These are decoder controls, not the W2 Detach/filer integration proof.
|
||||
@@ -43,3 +46,60 @@ func TestWorkspaceHEADCanonicalState(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The initial HEAD of a volume no holder ever claimed (epoch 0, no holder,
|
||||
// active) reads as ErrWorkspaceHeadUnclaimed with its generation and epoch 0:
|
||||
// still an error to every caller that needs an identity, and the delete's
|
||||
// evidence of "never started". A claimed or detached HEAD is unchanged, and
|
||||
// an epoch-0 HEAD with a holder or a detach proof stays invalid.
|
||||
func TestWorkspaceHEADUnclaimed(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, doc string
|
||||
unclaimed bool
|
||||
}{
|
||||
{"initial", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0}`, true},
|
||||
{"initial active", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"active"}`, true},
|
||||
{"epoch 0 with a holder", `{"format":1,"gen":1,"epoch":0,"holder":"x/r1","remote_lsn":0}`, false},
|
||||
{"epoch 0 detached", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"detached","detachedBy":{"holder":"","epoch":0,"gen":1}}`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(tc.doc)) }))
|
||||
defer s.Close()
|
||||
read, err := NewWorkspaceHEADReader(s.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := read(context.Background(), "v")
|
||||
if got := errors.Is(err, authority.ErrWorkspaceHeadUnclaimed); got != tc.unclaimed {
|
||||
t.Fatalf("unclaimed=%v (err %v); want %v", got, err, tc.unclaimed)
|
||||
}
|
||||
if tc.unclaimed && (h.Gen != 1 || h.Epoch != 0) {
|
||||
t.Fatalf("unclaimed HEAD %+v; want its generation and epoch 0", h)
|
||||
}
|
||||
if !tc.unclaimed && err == nil {
|
||||
t.Fatalf("HEAD %+v accepted; want an error", h)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A HEAD the delete has marked (deleting, purging, deleted) reads as
|
||||
// ErrWorkspaceHeadDeleting with Deleting set: the delete's re-run sees it as
|
||||
// past the fence; every other caller still gets an error.
|
||||
func TestWorkspaceHEADDeleting(t *testing.T) {
|
||||
for _, state := range []string{"deleting", "purging", "deleted"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
doc := `{"format":1,"gen":5,"epoch":0,"holder":"","remote_lsn":0,"state":"` + state + `"}`
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(doc)) }))
|
||||
defer s.Close()
|
||||
read, err := NewWorkspaceHEADReader(s.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := read(context.Background(), "v")
|
||||
if !errors.Is(err, authority.ErrWorkspaceHeadDeleting) || !h.Deleting || h.Gen != 5 {
|
||||
t.Fatalf("HEAD %s: %+v, %v; want ErrWorkspaceHeadDeleting with Deleting and its generation", state, h, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,7 @@ This alpha MVP does not yet claim:
|
||||
- production-ready durability
|
||||
- multi-node Kubernetes operation
|
||||
- failover while a pod remains mounted
|
||||
- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`)
|
||||
- real operator reconciliation
|
||||
- backend data shredding on delete
|
||||
- snapshots, clone, resize, block mode, topology spread, or NVMe-oF
|
||||
|
||||
@@ -151,6 +151,24 @@ flowchart LR
|
||||
Stream --> Initial[Move-less epoch: placement owner]
|
||||
```
|
||||
|
||||
**Chunk volume delete and its re-run.**
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Ask[MarkVolumeDeleting with token] --> Held{Token holds the reservation, or it is committed?}
|
||||
Held -->|yes: re-run| Catalog[Catalog step: HEAD compare-and-swap to deleting]
|
||||
Held -->|no| Verdict{WorkspaceHolderState}
|
||||
Verdict -->|never started or deleting| Admit[Reservation admitted]
|
||||
Verdict -->|live, sealed, unknown| Refuse[Refused: volume_in_use]
|
||||
Admit --> Catalog
|
||||
Catalog -->|HEAD not held| Mark[HEAD deleting, then purge, then commit]
|
||||
Catalog -->|a holder claimed HEAD| GiveBack[Refused; reservation given back]
|
||||
Mark -->|stopped before commit| Ask
|
||||
Admit -->|stopped before the mark| Ask
|
||||
```
|
||||
|
||||
Model: [NeverStarted r2 exhaustive results](../spec/NeverStarted-r2-results.md).
|
||||
|
||||
Model trace: [WorkspaceRegrant round 4 pins and simulation results](../spec/WorkspaceRegrant-owner-label-results.md)
|
||||
binds the owner-label switch, five configurations and reported results to exact
|
||||
hashes. Captured labels use StreamLabelFromStore=FALSE; the mutant models a
|
||||
@@ -172,6 +190,7 @@ a pre-issued publication.
|
||||
| Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
|
||||
| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed MOVED or DELETED lease refusal exits 78 at once; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` |
|
||||
| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
|
||||
| none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` |
|
||||
| Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
|
||||
|
||||
### M3 Replica role and peer state
|
||||
@@ -514,7 +533,7 @@ stateDiagram-v2
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
330 rows: 260 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 315 new.
|
||||
332 rows: 261 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 317 new.
|
||||
|
||||
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
|
||||
|
||||
@@ -773,7 +792,8 @@ Notes:
|
||||
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE |
|
||||
| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK. | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | ACTIVE |
|
||||
| `INV-WS-DELETE-NEEDS-ACK-001` | ARCHIVED: replaced by `INV-WS-DELETE-NO-LIVE-HOLDER-001`, which also admits a line whose holder never claimed HEAD at its epoch (HEAD is the proof of "started", not the lease). | — | — | — | — | ARCHIVED |
|
||||
| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE |
|
||||
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
|
||||
@@ -794,6 +814,7 @@ Notes:
|
||||
| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
|
||||
| `INV-WS-MASTER-WAIT-001` | A workspace primary's startup wait has no bound while blockmaster gives no reply or refuses its credentials or identity; it ends 30 s after max(the first reply after the local open and recovery, the master's barrier time), and a typed MOVED or DELETED lease refusal ends it at once with 78. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78` (`cmd/blockvolume/process_exit_authority_test.go`) | — | ACTIVE |
|
||||
|
||||
- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. Availability window: a delete admitted for a never-started line that stops before it marks HEAD leaves the volume reserved for deletion; if the holder then claims HEAD, the volume cannot be used until that delete is re-run (the catalog step then refuses the live HEAD and gives the reservation back). Re-run an interrupted delete.
|
||||
- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process.
|
||||
- `INV-WS-MASTER-WAIT-001`: every reply produced by blockmaster's handler starts or continues a contact streak; a transport failure (`Unavailable`, `DeadlineExceeded`, `Canceled`) ends it. So a master that answers and drops in turn postpones the 30 s bound for as long as it flaps, also for an obsolete unit; it never ends the wait early (`TestFlappingMasterNeverExpiresEarly`). The barrier time travels as a duration the master computes from the same two predicates as admission, added by the volume to its own monotonic request start; the master re-checks the barrier on every re-grant, so a wrong duration only moves the 75 exit. The status codes alone still mean retry 75 (`INV-WS-STARTUP-RETRY-001`); only the typed `WorkspaceLeaseRefusal` detail (MOVED, DELETED) permits the early 78. Scale: after a master restart every lapsed volume has the same barrier time T and the master grants them one at a time, each grant one store write W under the publisher lock, so the last of N volumes is granted about T + 0.1 s + N x W; a volume whose grant comes 30 s past T exits 75 and is started again, so that starts at N >= 30 s / W. Measured: W p50 1.03 ms, p99 2.33 ms, max 14.5 ms (400 writes of the file authority store on an NVMe ext4 disk, `TestWorkspaceGrantStoreWriteTime`), so 200 volumes about T + 0.6 s and the 30 s point near 12,900 volumes (p99); 20 real volume processes served at most 0.81 s after T (`TestManyVolumesServeTogetherAfterMasterRestart`). The bound holds for that store device: on a device whose flushes stall (an fsync held for seconds), one stalled write puts every waiting volume behind it, so the blockmaster store's device is a deployment premise of serving within 2 s of the barrier. A granted process whose attach keeps failing (the chunk store unreachable) retries inside the same bound and then exits 75: it does not hold the lease while never serving. An identity refusal has no bound until an identity-checked call (a renewal, a delivered assignment) is accepted, or until 30 s of replies pass with no new identity refusal; the window then opens again. A serving holder that starts getting identity refusals is outside this row: its lease expires and it fences and exits 75 (`lease_expired`).
|
||||
- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal.
|
||||
@@ -982,6 +1003,7 @@ Notes:
|
||||
| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE |
|
||||
| `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-FRONTIER-PROBE-001` | For a volume with three or more slots, the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release | — | ACTIVE |
|
||||
| `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | Under `best_effort`, the gate allows no candidate when a nonzero required frontier is given, and otherwise allows the highest-durable ready candidate. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
|
||||
@@ -1138,6 +1160,7 @@ A row that names a function existing only on an open pull request says so ("on #
|
||||
|
||||
| Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role |
|
||||
|---|---|---|---|---|---|
|
||||
| `TERM-LIVE-HOLDER-001` Live holder of a workspace volume | The line's holder at epoch e may have acknowledged guest writes and may publish exactly when: the authority line exists at e for its owner (`TERM-HOLDER-001`), no clean revocation ACK is recorded for (replica, e), and HEAD as read names `<server>/<replica>` at e, active. HEAD below e means never started at e: no I/O is admitted before the claim. | the authority line, the recorded ACK, HEAD (`Epoch`, `Holder`, `Detached`) | `authority.WorkspaceHolderState` (pure): no line, drained, sealed, never started, live, unknown | the forced-move admission still reads the lease; a sealed HEAD without an ACK keeps the ACK rule | blockmaster |
|
||||
| `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `<server id>/<replica id>` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) |
|
||||
| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. The takeover margin (half the skew bound) exceeds the configured fence-exit budget (watch cadence 50 ms + drain timeout 5 s), assuming normal scheduling; blockmaster refuses a smaller or equal margin at startup, deriving the budget from `durable.ChunkFenceWatchInterval` and `volume.WorkspaceDrainTimeout`. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) |
|
||||
| `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 when the startup wait runs out (`INV-WS-MASTER-WAIT-001`). | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host |
|
||||
|
||||
@@ -210,7 +210,9 @@ The volume computes whether it may become primary; blockmaster decides; only the
|
||||
|
||||
**RF=3 gate** (`core/host/master/promotion_probe.go`, `promotionAllowedReplicas`, `chooseAllowedPromotionTarget`): no promotion when the probe failed or is not installed, or the ack profile is unknown; a candidate is skipped when it is not `replica_ready` with a known frontier, or its durable LSN is below the required frontier. The decision is recorded as an ops event (`candidate_covers_required_frontier`, `candidate_frontier_behind`, `no_promotion_ready_candidate`). The required frontier per volume (`RequiredLSNByVolume`) is not set by `cmd/blockmaster` today, so the frontier is unknown and coverage is proven from the survivors instead: with `sync_quorum` or `sync_all`, the ready candidate with the highest durable LSN is promoted only when at least P-K+1 of the P peers are probed ready (known durable LSN) and have a fresh heartbeat, where K is the number of peer acks a write needs (`waitForSyncAcks`: P for `sync_all`, (P+1)/2 for `sync_quorum`). Any P-K+1 peers include one that holds every acknowledged write that their sampled frontiers represent. The probes of one tick are snapshots, not a fence: a primary that is still running can acknowledge after a sample was taken (for example, r3 reports 70 in a held probe response, the old primary then acknowledges 71, and r2 at 70 is still selected). That is the missing primary lease below (§12, #195). For RF=3 that is both peers under `sync_quorum` and one under `sync_all`; with fewer, nothing is promoted. An unknown frontier is never read as zero. `best_effort` is unchanged (§12).
|
||||
|
||||
**What blocks a promotion:** any engine reason above; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran.
|
||||
**A current primary that does not answer is unknown, not failed.** When its status cannot be read (a pod gone, a partition), blockmaster does not reassign on either path, however ready the survivors: on a partition the primary may still be serving. Only the primary's own not-ready report moves the line automatically; otherwise failover is a manual admin action in this release.
|
||||
|
||||
**What blocks a promotion:** any engine reason above; a current primary whose status cannot be read; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# NeverStarted r2: exhaustive results for the never-started delete
|
||||
|
||||
A chunk volume whose line was granted but whose HEAD was never claimed can be
|
||||
deleted (`INV-WS-DELETE-NO-LIVE-HOLDER-001`, `TERM-LIVE-HOLDER-001`). A rerun
|
||||
of a delete whose token already holds the reservation (or a committed one) is
|
||||
admitted without a new verdict; the catalog's HEAD compare-and-swap is the
|
||||
fence. The model checks this head behaviour, the earlier heads it replaces, and
|
||||
mutations of each guard.
|
||||
|
||||
Assumptions (not modelled): one delete process per volume at a time; the gap
|
||||
between HEAD deleted and the volume marked deleted; an interrupted delete is
|
||||
re-run by the operator.
|
||||
|
||||
## Results
|
||||
|
||||
Status: **EXHAUSTIVE** (TLC, every configuration finished). Depth and distinct
|
||||
state counts are as reported by TLC.
|
||||
|
||||
**Must not violate** (the code at 72efeb3a, unchanged since: FixDeleting + FixToken). Invariants
|
||||
checked: TypeOK, NoTwoHolders, NoValidityBehindLine, NoServedWriteLost,
|
||||
DeleteNeverStrandsALiveHolder, NoRefusalContradiction,
|
||||
NoLiveHolderWhileDeleting, RerunCanFinish, RerunCanSettle,
|
||||
SkipOnlyReplaysADecision.
|
||||
|
||||
| Configuration | Distinct states | Depth | Result |
|
||||
|---|---|---|---|
|
||||
| `safe_head_72efeb3a_nosnap` | 25,831,776 | 50 | No error |
|
||||
| `safe_head_72efeb3a` (snapshot revert on) | 48,737,939 | 50 | No error |
|
||||
|
||||
**Must violate** (each fires as expected):
|
||||
|
||||
| Configuration | What it is | Violated |
|
||||
|---|---|---|
|
||||
| `f1_head_stuck` | earlier head: a delete stopped after its HEAD mark | RerunCanFinish |
|
||||
| `f1b_fix_deleting_settle` | earlier head: a delete stopped before its mark, then the holder claims | RerunCanSettle |
|
||||
| `mut_no_head_fence` | the catalog's mark is a blind write | NoServedWriteLost |
|
||||
| `mut_fix_mark_no_fence` | HEAD marked without its fence | NoLiveHolderWhileDeleting |
|
||||
| `mut_blind_claim` | a claim that ignores deleting | DeleteNeverStrandsALiveHolder |
|
||||
| `mut_admit_claimed` | a claimed HEAD admitted | NoServedWriteLost |
|
||||
| `mut_lc_admits_ns` | the lifecycle delete admits a never-started line | DeleteNeverStrandsALiveHolder |
|
||||
| `mut_token_any` | the skip for any token while admitted | SkipOnlyReplaysADecision |
|
||||
| `mut_token_rerun_trusts` | a skipped rerun's catalog step trusts the admission | NoLiveHolderWhileDeleting |
|
||||
| `mut_mem_restart`, `mut_mem_restart_two_holders` | empty lease memory after restart plus a barrier-less move | NoValidityBehindLine |
|
||||
| `mut_mem_restart_nth` | the same, NoTwoHolders alone | NoTwoHolders |
|
||||
| `mut_move_ignores_lease` | a move on HEAD alone while a lease is valid | NoValidityBehindLine |
|
||||
| `mut_move_ignores_lease_nth` | the same, NoTwoHolders alone | NoTwoHolders |
|
||||
| `wit_fix_other_token_admitted` | witness: a new token is decided by the verdict | WitnessOtherTokenAdmitted |
|
||||
| `wit_fix_stale_deleting_admits_live` | witness: a stale deleting read admits; the catalog refuses | WitnessStaleDeletingAdmitsLive |
|
||||
| `wit_fix_stale_read_joins_deleting` | witness: a stale read joins the mark | WitnessStaleReadJoinsDeleting |
|
||||
| `wit_fix_rerun_after_mark_finished` | witness: a delete stopped after its mark is finished by a rerun | WitnessRerunAfterMarkFinished |
|
||||
| `wit_token_rerun_admits_live` | witness: the skip admits over a live HEAD; the catalog gives it back | WitnessRerunAdmittedLive |
|
||||
|
||||
21 of 21 configurations as expected. A violated witness shows that the state
|
||||
it names is reachable (the fix is not vacuous); it is not a defect.
|
||||
@@ -103,6 +103,12 @@ Two kinds of config are **expected to violate**:
|
||||
|
||||
Each `.cfg` names its spec on its first line.
|
||||
|
||||
## Never-started delete results
|
||||
|
||||
[NeverStarted r2 exhaustive results](NeverStarted-r2-results.md): 21 of 21
|
||||
configurations as expected; the two must-not-violate configurations finished
|
||||
with no error (25,831,776 and 48,737,939 distinct states, depth 50).
|
||||
|
||||
## Owner-label simulation results
|
||||
|
||||
[Workspace owner-label simulation results](WorkspaceRegrant-owner-label-results.md)
|
||||
|
||||
Reference in new issue
Block a user