Merge pull request #438 from seaweedfs/train/20261122-26

train: OSS RC train 26 (#437 lease validity, #436 start limits, #414 procedure gate)
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-22 10:38:47 -08:00
commit 4ac3f3fa70
21 files changed
+422 -88

No files matched your search

@@ -229,9 +229,10 @@ func matchUint(re *regexp.Regexp, s string) (uint64, error) {
// TestPlannedHandoffChecksReadCapturedProductOutput runs every check on the
// output the real binaries printed in one passing hand-over (E=1, G=3, L=1,
// E2=2) and in the refused clean move without an ACK (move-refused,
// show-revoked), and each check on an output of another step, which it must
// refuse.
// E2=2), in the refused clean move without an ACK (move-refused,
// show-revoked), and in the procedure gate's move to s2 and forced move
// (move-clean-s2, head-reopened-s2, force-move*, lost-range), and each check
// on an output of another step, which it must refuse.
func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) {
read := func(name string) string {
b, err := os.ReadFile(filepath.Join("testdata", "planned-handoff", name))
@@ -302,6 +303,34 @@ func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) {
if r := read("show-revoked.stdout"); showsAck(r, e, g) || !hasLine(r, "recorded ACK: none") {
t.Error("the revoked show without an ACK is read as acknowledged")
}
// The procedure gate's two-host outputs (a planned move to s2, a forced
// move s1 -> s2 at E=1 -> E2=2 keeping gen 3, LSN 1).
if got, err := movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s2"); err != nil || got != e2 {
t.Errorf("moved epoch to s2 %d, %v; want %d", got, err, e2)
}
_, err = movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s1")
refused("clean move to s2 read as a move to s1", err)
ok("HEAD reopened by s2", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s2"))
refused("HEAD reopened by s2 read as s1's", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s1"))
if got, err := forcedEpoch(read("force-move.stdout"), e, "s1", "s2"); err != nil || got != e2 {
t.Errorf("forced epoch %d, %v; want %d", got, err, e2)
}
_, err = forcedEpoch(read("force-move.stdout"), e, "s2", "s1")
refused("forced move read the other way round", err)
_, err = forcedEpoch(read("move-clean-s2.stdout"), e, "s1", "s2")
refused("forced epoch", err)
if got, err := forcedKeptLSN(read("force-move.stdout")); err != nil || got != l {
t.Errorf("forced kept LSN %d, %v; want %d", got, err, l)
}
if !previewAdmitted(read("force-move-dry-run-admitted.stdout")) || previewAdmitted(read("force-move-dry-run-refused.stdout")) {
t.Error("the dry-run preview is not told admitted from not admitted")
}
if !strings.Contains(read("force-move-dry-run-refused.stdout"), "admissible at ") {
t.Error("the refused preview has no admissible time")
}
if !strings.Contains(read("lost-range.stdout"), "range 1 of 1: request force-v1-1, r1@") {
t.Error("lost-range does not show the forced move")
}
if !frontendReady([]byte(read("status-primary.json"))) || frontendReady([]byte(`{"FrontendPrimaryReady":false,"Healthy":true}`)) {
t.Error("the frontend-ready check does not read FrontendPrimaryReady")
}
@@ -17,6 +17,7 @@ import (
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
@@ -237,8 +238,12 @@ func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv {
}
// volArgs is the chapter's blockvolume command for one host.
func (env *handoffEnv) volArgs(id string) []string {
b := env.hosts[id]
func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) }
// volArgsFor is the chapter's blockvolume command for b. The default
// scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page
// says; a snapshot inside a test could only make a test fail, never pass.
func (env *handoffEnv) volArgsFor(b bvHost) []string {
return []string{"--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", "v1", "--replica-id", "r1",
"--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status,
"--durable-root", b.root, "--durable-impl", "walstore-chunk",
@@ -303,15 +308,30 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness {
return h
}
// captureOutput writes each sw-block answer to $HANDOFF_CAPTURE_DIR, when set,
// as <test>-<n>-<verb>.stdout/.stderr: the source of testdata/planned-handoff.
func captureOutput(t *testing.T, args []string, stdout, stderr string) {
dir := os.Getenv("HANDOFF_CAPTURE_DIR")
if dir == "" || len(args) < 3 {
return
}
captureSeq++
base := filepath.Join(dir, fmt.Sprintf("%s-%02d-%s-%s", t.Name(), captureSeq, args[1], args[2]))
_ = os.WriteFile(base+".stdout", []byte(stdout), 0o644)
_ = os.WriteFile(base+".stderr", []byte(stderr), 0o644)
}
var captureSeq int
var handoffPorts struct {
sync.Mutex
used map[int]bool
}
// handoffAddress returns a free loopback address below the kernel's
// ephemeral range (32768 and up on Linux). A daemon restarted minutes later
// binds it again, and an outgoing connection may take any ephemeral port in
// between; ports below the range are never handed out that way.
// handoffAddress returns a free loopback address in 10000-19999: below the
// kernel's ephemeral range (32768 and up on Linux), where an outgoing
// connection can take a port while a restarted daemon waits to bind it
// again, and below the 20000-49999 range startWorkspaceWeed draws from.
func handoffAddress(t *testing.T) string {
t.Helper()
handoffPorts.Lock()
@@ -320,7 +340,7 @@ func handoffAddress(t *testing.T) string {
handoffPorts.used = map[int]bool{}
}
for i := 0; i < 500; i++ {
p := 21000 + rand.Intn(11000)
p := 10000 + rand.Intn(10000)
if handoffPorts.used[p] {
continue
}
@@ -341,6 +361,21 @@ type daemon struct {
done chan struct{}
err error
cancel context.CancelFunc
proc *os.Process
}
// term sends SIGTERM, as systemctl stop or restart does, and waits for the
// child to exit.
func (d *daemon) term(t *testing.T, timeout time.Duration) {
t.Helper()
if err := d.proc.Signal(syscall.SIGTERM); err != nil {
t.Fatalf("SIGTERM %s: %v", d.name, err)
}
select {
case <-d.done:
case <-time.After(timeout):
t.Fatalf("%s did not exit within %s of SIGTERM", d.name, timeout)
}
}
// kill kills the child (no ACK is sent on a signal) and waits for it.
@@ -392,6 +427,7 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args ..
t.Fatalf("start %s: %v", name, err)
}
started = true
d.proc = cmd.Process
go func() { d.err = cmd.Wait(); close(d.done) }()
return d
}
@@ -468,6 +504,7 @@ func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, strin
var stdout, stderr strings.Builder
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
captureOutput(t, args, stdout.String(), stderr.String())
var exit *exec.ExitError
switch {
case err == nil:
@@ -17,9 +17,11 @@ import (
)
// The procedure gate: every operator procedure of docs/volume-lifecycle.md
// runs as written, with real binaries, on two blockvolume processes with
// distinct server ids (s1 and s2) sharing one blockmaster and one SeaweedFS.
// The planned return to the same host is TestStandalonePlannedHandoffToTheSameHost.
// runs as written, with real binaries, on blockvolume processes with distinct
// server ids (s1, and s2 where a procedure moves the volume) sharing one
// blockmaster and one SeaweedFS. The two start-time tests and the same-host
// restarts use s1 only. The planned return to the same host is
// TestStandalonePlannedHandoffToTheSameHost.
// TestProcedurePlannedHandoffToAnotherHost: the planned hand-over from s1 to
// s2. The new holder starts with no local copy, claims the sealed HEAD at the
@@ -34,6 +36,9 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
block := pattern("to-another-host!")
env.writeBlock(t, "s1", 0, block)
// Step 1: read the holder; the lease must be granted.
out, _ := h.command(t, env.show...)
must(checkShowGranted(out, e))
g := env.seal(t, "s1", e)
l := env.sealedLSN(t, e, g)
env.revoke(t, e, g)
@@ -49,7 +54,7 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
out, _ := h.command(t, env.show...)
out, _ = h.command(t, env.show...)
must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2),
fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l)))
out, _ = h.command(t, env.chunkShow()...)
@@ -57,27 +62,59 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
if !bytes.Equal(env.readBlock(t, "s2", 0), block) {
t.Fatal("the block written on s1 does not read back on s2")
}
// Control: a block never written reads zero, so the comparison above can
// fail.
if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) {
t.Fatal("a block never written does not read zero on s2")
}
}
// TestProcedureSameHostRestartInsideTheLease: the holder's process dies and is
// started again on its host within the 30 s lease. It keeps holder and epoch
// and serves again at once from its local WAL.
// TestProcedureSameHostRestartInsideTheLease: the page's restart without a
// hand-over, `systemctl restart`: the holder gets SIGTERM, exits, and is
// started again on its host within the unit's RestartSec (5 s), inside the
// 30 s lease. It keeps holder and epoch and serves again at once from its
// local WAL.
func TestProcedureSameHostRestartInsideTheLease(t *testing.T) {
env := startHandoffEnv(t, 2)
must, _ := fatalOn(t)
env := startHandoffEnv(t, 1)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("restart-in-lease")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
first.term(t, 30*time.Second)
env.restartServesAtOnce(t, "blockvolume-s1-again", e, block)
}
again := env.start(t, "blockvolume-s1-again", "s1")
// TestProcedureSameHostCrashRestartInsideTheLease: the page's "the holder
// comes back within the lease" after a crash: the process is killed and
// started again within the unit's RestartSec (5 s). The same outcome as a
// restart.
func TestProcedureSameHostCrashRestartInsideTheLease(t *testing.T) {
env := startHandoffEnv(t, 1)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("crash-in-lease!!")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
env.restartServesAtOnce(t, "blockvolume-s1-again", e, block)
}
// restartServesAtOnce starts s1 again within 5 s of its exit and requires it
// to serve within 15 s ("at once"), as s1/r1 at the same epoch, with the
// written block.
func (env *handoffEnv) restartServesAtOnce(t *testing.T, name string, e uint64, block []byte) {
t.Helper()
must, _ := fatalOn(t)
started := time.Now()
again := env.start(t, name, "s1")
if got := env.adopt(t, again, "s1"); got != e {
t.Fatalf("the restarted holder adopted epoch %d; want the same epoch %d", got, e)
}
if took := time.Since(started); took > 15*time.Second {
t.Fatalf("the restarted holder served after %s; the page says at once", took.Round(time.Second))
}
out, _ := env.h.command(t, env.show...)
must(checkShowGranted(out, e))
env.requireHeadHolder(t, e, "s1")
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the restart does not read back")
}
@@ -99,15 +136,20 @@ func TestProcedureReturnAfterALapsedLease(t *testing.T) {
stopped := time.Now()
time.Sleep(time.Until(stopped.Add(65 * time.Second)))
started := time.Now()
back := env.start(t, "blockvolume-s1-back", "s1")
if got := env.adopt(t, back, "s1"); got != e {
t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e)
}
if took := time.Since(started); took > 30*time.Second {
t.Fatalf("the returning holder served after %s, past its 30 s authority wait", took.Round(time.Second))
}
if back.has("assignment unavailable, not serving") {
t.Fatal("started 65 s after the stop, the holder still logged the not-serving line")
}
out, _ := env.h.command(t, env.show...)
must(checkShowGranted(out, e))
env.requireHeadHolder(t, e, "s1")
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the lapse does not read back")
}
@@ -153,33 +195,23 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) {
t.Fatal("the block written after the last cut reads back on s2; the page says it is lost")
}
// The old host returns with its old local root. It must not take s2's
// line as its own (a holder is server and replica), report its frontend
// ready, or listen for I/O; the page says it does not serve.
back := env.start(t, "blockvolume-s1-back", "s1")
var failures []string
end := time.Now().Add(40 * time.Second)
for time.Now().Before(end) && len(failures) == 0 {
if l := back.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" {
failures = append(failures, "it adopted s2's line: "+l)
}
if env.frontendReadyAt("s1") {
failures = append(failures, "its status reports FrontendPrimaryReady")
}
if listening(env.hosts["s1"].nvme) {
failures = append(failures, "its NVMe/TCP target listens")
}
time.Sleep(time.Second)
}
if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") && !back.has("foreign assignment") {
failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)")
}
if len(failures) > 0 {
t.Errorf("the returning old host after the forced move: %s", strings.Join(failures, "; "))
}
// #425 (V1-SPEC r2.40: a line carries its owner and that owner's endpoints): every line delivered at the forced
// epoch, to the new owner and to the returning old host alike, carries s2's own endpoints, never another host's.
if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back); len(bad) > 0 {
// The old host returns with its old local root, and the example unit
// (Restart=on-failure, RestartSec=5s) starts it again after it exits,
// until its start limit. Each time it must not take s2's line as its own
// (a holder is server and replica), report its frontend ready or listen
// for I/O; it logs a refusal and exits with status 75.
back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 75)
time.Sleep(5 * time.Second) // RestartSec of the example unit
again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 75)
// Control: on a fresh local root there is no stale root, so its refusal
// is the identity check alone; it also exits 75.
fresh := env.hosts["s1"]
fresh.root = fresh.root + "-fresh"
freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 75)
// A line carries its owner and that owner's endpoints: every line
// delivered at the forced epoch, to the new owner and to each returning
// old host alike, carries s2's own endpoints, never another host's.
if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, again, freshRoot); len(bad) > 0 {
t.Errorf("epoch-%d deliveries not proven to carry s2's endpoints (want data=%s ctrl=%s in every recipient's lines):\n%s",
e2, env.hosts["s2"].data, env.hosts["s2"].ctrl, strings.Join(bad, "\n"))
}
@@ -189,10 +221,12 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) {
}
}
// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed and
// revoked, but its process dies before it sends the ACK. The clean move is
// refused; only a forced move to another node remains, and since HEAD is
// sealed, nothing acknowledged is lost.
// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed, its
// process is gone before the revoke (so no process ever sends the ACK), and
// the lease is revoked with the sealed generation. The clean move is refused;
// only a forced move to another node remains, and since HEAD is sealed,
// nothing acknowledged is lost. Killing before the revoke makes the missing
// ACK certain; the page's row "Revoked, but no ACK" has the same outcome.
func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) {
env := startHandoffEnv(t, 2)
must, mustU := fatalOn(t)
@@ -242,7 +276,7 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) {
var ready []time.Time
end := time.Now().Add(90 * time.Second)
for time.Now().Before(end) {
if env.frontendReadyAt("s1") || listening(env.hosts["s1"].nvme) {
if env.servingNow("s1") {
ready = append(ready, time.Now())
if len(ready) >= 5 {
break
@@ -253,10 +287,19 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) {
if len(ready) == 0 {
t.Fatal("the returning holder never served within 90 s")
}
if last := lastLogTime(back, "clock-skew margin has not elapsed"); !last.IsZero() && ready[0].Before(last) {
t.Errorf("the returning holder served at %s, before its renewal was still refused for the barrier at %s: it served without a lease",
// Started before the barrier, its renewals must have been refused for it
// at least once; log times have 1 s resolution.
last := lastLogTime(back, "clock-skew margin has not elapsed")
if last.IsZero() {
t.Fatal("started 40 s after the stop, the returning holder logged no renewal refused for the barrier")
}
if ready[0].Before(last.Add(time.Second)) {
t.Errorf("the returning holder served at %s, while its renewal was still refused for the barrier at %s: it served without a lease",
ready[0].Format("15:04:05.000"), last.Format("15:04:05"))
}
if !back.has("workspace lease: re-granted after ") {
t.Error("the returning holder served without logging its re-grant")
}
if got := env.adopt(t, back, "s1"); got != e {
t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e)
}
@@ -280,12 +323,15 @@ func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) {
first.kill(t)
time.Sleep(31 * time.Second)
// Attempt 2 starts about 66 s after the stop and its wait ends about
// 96 s after it, against a barrier of at most 95 s, so attempt 2 normally
// serves; up to 4 attempts allow for scheduling on a loaded host.
for attempt := 1; ; attempt++ {
d := env.start(t, fmt.Sprintf("blockvolume-s1-try%d", attempt), "s1")
served := false
end := time.Now().Add(45 * time.Second)
for time.Now().Before(end) {
if env.frontendReadyAt("s1") {
if env.servingNow("s1") {
served = true
break
}
@@ -308,6 +354,9 @@ func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) {
if err := d.wait(5 * time.Second); exitCode(err) != 75 {
t.Fatalf("attempt %d did not serve and did not exit 75: %v", attempt, err)
}
if !d.has("blockvolume: exiting status=75 reason=assignment_timeout") {
t.Fatalf("attempt %d exited 75 without the reason assignment_timeout", attempt)
}
if attempt == 4 {
t.Fatal("four supervised starts never served")
}
@@ -345,6 +394,62 @@ func exitCode(err error) int {
return -1
}
// oldHostRefuses starts the old holder b after the volume moved to epoch e2
// on another host, and returns it. While it runs it must not adopt the new
// line, report its frontend ready or listen; it must log a refusal and exit
// with wantExit.
func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64, wantExit int) *daemon {
t.Helper()
d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
var failures []string
end := time.Now().Add(60 * time.Second)
for alive := true; alive && time.Now().Before(end); {
if l := d.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" {
failures = append(failures, "it adopted the new holder's line: "+l)
}
if env.frontendReadyAt("s1") {
failures = append(failures, "its status reports FrontendPrimaryReady")
}
if listening(b.nvme) {
failures = append(failures, "its NVMe/TCP target listens")
}
select {
case <-d.done:
alive = false
case <-time.After(500 * time.Millisecond):
}
}
if err := d.wait(5 * time.Second); exitCode(err) != wantExit {
failures = append(failures, fmt.Sprintf("it did not exit with status %d: %v", wantExit, err))
}
if !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") {
failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)")
}
if len(failures) > 0 {
t.Errorf("%s after the forced move: %s", name, strings.Join(failures, "; "))
}
return d
}
// servingNow reports whether the host serves: its frontend is ready or its
// NVMe/TCP target accepts connections.
func (env *handoffEnv) servingNow(id string) bool {
return env.frontendReadyAt(id) || listening(env.hosts[id].nvme)
}
// requireHeadHolder checks that HEAD is active, held by host/r1 at epoch e.
func (env *handoffEnv) requireHeadHolder(t *testing.T, e uint64, host string) {
t.Helper()
out, _ := env.h.command(t, env.chunkShow()...)
head, err := parseHead(out)
if err != nil {
t.Fatal(err)
}
if head.State != "active" || head.Epoch != e || head.Holder != host+"/r1" {
t.Fatalf("HEAD %+v; want active at epoch %d held by %s/r1", head, e, host)
}
}
func pattern(s string) []byte { return bytes.Repeat([]byte(s), 4096/len(s)) }
func (env *handoffEnv) start(t *testing.T, name, id string) *daemon {
@@ -462,7 +567,7 @@ func (env *handoffEnv) forceMove(t *testing.T, e uint64, target, request string)
}
// wrongOwnerEndpoints returns every "assignment stream delivery" log line at epoch e (in any of ds) whose data or control
// endpoint is not owner's (#425), plus an entry for each recipient whose log cannot be read or shows no epoch-e
// endpoint is not owner's, plus an entry for each recipient whose log cannot be read or shows no epoch-e
// delivery at all (each recipient must positively have received the owner's line).
func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string {
var bad []string
@@ -0,0 +1,4 @@
preview (advisory): at master time 2026-11-22T15:36:16.705621624Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.
forced move admitted
HEAD now: gen 3, epoch 1, holder s1/r1, remote LSN 1, published at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution)
if moved now: writes with LSN <= 1 are kept; writes acknowledged after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost
@@ -0,0 +1,3 @@
preview (advisory): at master time 2026-11-22T15:35:12.107989752Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.
forced move not admitted: workspace forced move lease expiry plus clock-skew margin has not elapsed
admissible at 2026-11-22T15:36:16.617154582Z, master clock
@@ -0,0 +1,3 @@
forced move issued: volume v1 request force-v1-1: r1@1 on s1 -> r1@2 on s2 (kept HEAD gen 3, remote LSN 1)
volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN.
next: start volume v1 on s2 (this command moved authority only)
@@ -0,0 +1 @@
{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795361693554515613,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s2/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}}
@@ -0,0 +1,2 @@
range 1 of 1: request force-v1-1, r1@1 -> epoch 2, lost after LSN 1, until 2026-11-22T15:36:16.617154582Z (master clock)
volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN.
@@ -0,0 +1,2 @@
clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s2 (sealed HEAD gen 3, remote LSN 1)
next: start volume v1 on s2 (this command moved authority only)
+3 -2
View File
@@ -277,8 +277,9 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking {
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
}
now := p.workspaceNow()
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) {
lease := *s.Lease
lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano())
if p.WorkspaceLeaseValidity(lease) == 0 {
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
}
if s.Ack != nil && *s.Ack != ack {
@@ -144,6 +144,18 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
return l, true
}
// WorkspaceLeaseValidity reports host validity on the publisher clock, with
// the configured TTL and the larger configured/persisted skew bound.
// M2 grant/revoke ACK; INV-WS-FORCED-MOVE-HALF-SKEW-001.
func (p *Publisher) WorkspaceLeaseValidity(l WorkspaceLease) time.Duration {
return p.workspaceLeaseValidityAt(l, p.workspaceNow())
}
func (p *Publisher) workspaceLeaseValidityAt(l WorkspaceLease, now time.Time) time.Duration {
remaining := time.Unix(0, l.ExpiresAtNS).Add(-p.workspaceSkew(&l) / 2).Sub(now)
return max(0, min(remaining, p.workspaceTTL))
}
// PublishedLine is a volume's committed authority line as the lease view
// publishes it.
type PublishedLine struct {
@@ -261,7 +273,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// A grant without positive host validity (expiry minus half the skew
// bound, leaseFact) would make the host fence on an invalid reply and lose
// its remaining validity; refuse with an error instead.
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 {
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
summary := p.leaseStats.summaryDue(now)
p.leaseMu.Unlock()
@@ -0,0 +1,61 @@
package authority
import (
"context"
"testing"
"time"
)
func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) {
for _, tc := range []struct {
name string
elapsed time.Duration
allowed bool
restart bool
}{
{"before", 28*time.Second - time.Nanosecond, true, false},
{"at", 28 * time.Second, false, false},
{"after", 29 * time.Second, false, false},
{"horizon-before", 43*time.Second - time.Nanosecond, true, true},
{"horizon-at", 43 * time.Second, false, true},
{"horizon-after", 44 * time.Second, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
disk, _ := newTempStore(t)
start := time.Unix(1000, 0)
now := start
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if tc.restart {
// Reopening at +20s gives a restart deadline of +50s, beyond
// the persisted +45s horizon. ACK must stop at +43s.
now = start.Add(20 * time.Second)
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
p.mu.Lock()
deadline := p.leaseDeadlineLocked("v")
horizon := p.workspace["v"].Lease.ExpiresAtNS
p.mu.Unlock()
if !deadline.After(time.Unix(0, horizon)) {
t.Fatal("fixture deadline does not exceed persisted horizon")
}
}
now = start.Add(tc.elapsed)
err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7})
if (err == nil) != tc.allowed {
t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err)
}
if (p.WorkspaceState("v").Ack != nil) != tc.allowed {
t.Fatal("ACK persistence differs from admission")
}
})
}
}
@@ -112,7 +112,7 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro
done <- result{err: err}
return
}
done <- result{fact: leaseFact(id.VolumeId, l)}
done <- result{fact: leaseFact(c.p, id.VolumeId, l)}
}()
select {
case r := <-done:
@@ -78,23 +78,9 @@ func workspaceError(err error) error {
return status.Error(codes.FailedPrecondition, err.Error())
}
func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact {
// Client anchors this duration to its request START, not response arrival.
// The host fences half a skew bound before the stored master expiry.
// Never grant more than the server's configured 30s TTL after a restart.
skew := time.Duration(l.MaxClockSkewNS)
// Older persisted leases predate the bound; use the production default.
if skew <= 0 {
skew = 20 * time.Second
}
remaining := time.Until(time.Unix(0, l.ExpiresAtNS).Add(-skew / 2))
if remaining > 30*time.Second {
remaining = 30 * time.Second
}
if remaining < 0 {
remaining = 0
}
return &control.WorkspaceLeaseFact{VolumeId: volume, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ExpiresAtNs: l.ExpiresAtNS, ValidForNs: int64(remaining), Revoking: l.Revoking}
func leaseFact(p *authority.Publisher, volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact {
// The client anchors this duration to its request START, not response arrival.
return &control.WorkspaceLeaseFact{VolumeId: volume, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ExpiresAtNs: l.ExpiresAtNS, ValidForNs: int64(p.WorkspaceLeaseValidity(l)), Revoking: l.Revoking}
}
// holderMatches implements INV-AUTH-HOLDER-IDENTITY-001 for both holder RPCs.
@@ -125,7 +111,7 @@ func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.Workspace
if err != nil {
return nil, workspaceError(err)
}
return leaseFact(q.GetVolumeId(), l), nil
return leaseFact(s.host.Publisher(), q.GetVolumeId(), l), nil
}
func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
@@ -140,7 +126,7 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden
if !ok {
return nil, status.Error(codes.FailedPrecondition, "workspace moved during revocation")
}
return leaseFact(q.GetVolumeId(), lease), nil
return leaseFact(s.host.Publisher(), q.GetVolumeId(), lease), nil
}
func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) {
@@ -416,7 +402,7 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum
return out, nil
}
if lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()); ok {
out.Lease = leaseFact(q.GetVolumeId(), lease) // granted expiry, not the durable horizon
out.Lease = leaseFact(s.host.Publisher(), q.GetVolumeId(), lease) // granted expiry, not the durable horizon
}
if state.Ack != nil {
out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen}
@@ -19,7 +19,7 @@ func (c skewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.Wo
if err != nil {
return nil, err
}
return leaseFact(id.VolumeId, l), nil
return leaseFact(c.p, id.VolumeId, l), nil
}
func (skewLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) {
panic("expiry must not ACK clean")
@@ -145,3 +145,30 @@ func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) {
t.Fatal("configuration not applied to host validity", lease, reply)
}
}
// The lease reply uses the publisher clock even when it differs from this
// process's wall clock; configured skew also covers legacy leases with no bound.
func TestWorkspaceLeaseFactUsesPublisherClockAndSkew(t *testing.T) {
now := time.Unix(1000, 0)
p := authority.NewPublisher(nil, authority.WithWorkspaceLeaseConfig(12*time.Second, func() time.Time { return now }), authority.WithWorkspaceMaxClockSkew(4*time.Second))
for _, tc := range []struct {
name string
expiry time.Duration
skew int64
want time.Duration
}{
{"legacy-configured-bound", 10 * time.Second, 0, 8 * time.Second},
{"persisted-smaller-bound", 10 * time.Second, int64(2 * time.Second), 8 * time.Second},
{"persisted-larger-bound", 10 * time.Second, int64(6 * time.Second), 7 * time.Second},
{"configured-ttl-cap", 40 * time.Second, 0, 12 * time.Second},
{"expired", time.Second, 0, 0},
} {
t.Run(tc.name, func(t *testing.T) {
l := authority.WorkspaceLease{ReplicaID: "r", Epoch: 1, ExpiresAtNS: now.Add(tc.expiry).UnixNano(), MaxClockSkewNS: tc.skew}
fact := leaseFact(p, "v", l)
if fact.ValidForNs != int64(tc.want) {
t.Fatalf("validity=%s, want %s", time.Duration(fact.ValidForNs), tc.want)
}
})
}
}
@@ -9,6 +9,8 @@
#
# Load the module at boot: echo ublk_drv | sudo tee /etc/modules-load.d/ublk.conf
[Unit]
StartLimitIntervalSec=600
StartLimitBurst=10
Description=Seaweed Block volume over ublk (one replica, root)
Documentation=https://github.com/seaweedfs/seaweed-block
After=network-online.target sw-blockmaster.service
@@ -7,6 +7,8 @@
# For ublk (needs root) do not edit this unit: use
# sw-blockvolume-ublk.service, which has its own state directory.
[Unit]
StartLimitIntervalSec=600
StartLimitBurst=10
Description=Seaweed Block volume (one replica)
Documentation=https://github.com/seaweedfs/seaweed-block
After=network-online.target sw-blockmaster.service
@@ -358,7 +358,7 @@ stateDiagram-v2
[*] --> Granted: move issue starts the new holder's lease
Granted --> Granted: Renew before horizon and deadline (from memory; registered server id, from its registered host)
Granted --> Revoking: BeginWorkspaceRevocation
Revoking --> Acked: host acks detached HEAD gen while the lease is valid (from its registered host)
Revoking --> Acked: registered host acks detached HEAD gen; publisher-clock validity after half max(configured, persisted) skew is positive
Acked --> Moved: CLEAN move, including same host, new epoch
Granted --> Expired: horizon or deadline passes
Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant
+5 -4
View File
@@ -134,7 +134,7 @@ a pre-issued publication.
| none | Granted | `RenewWorkspaceLease` from the current primary (server id, replica id) at the current epoch; a missing/foreign server is refused by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`); no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Granted | Granted | current primary server/replica/epoch required by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing server refused); renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001` |
| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, positive granted validity after half the configured/persisted skew on the publisher clock; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` |
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
@@ -722,7 +722,7 @@ Notes:
| `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`) | — | 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 |
| `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/host/master/workspace_service.go` `leaseFact`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE |
| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE |
| `INV-WS-LOST-RANGE-QUERY-001` | `QueryWorkspaceLostRange` returns the stored ranges unchanged: every issued forced move's range in issue order, or the single range of a given request id. | M2 lease: Moved → epoch issued (readout) | `core/authority/workspace_lost_range.go` `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `LostRanges`; `cmd/sw-block/workspace.go` `runWorkspaceLostRange` | `TestWorkspaceLostRangeAccumulatesInIssueOrder` (`core/authority/workspace_lost_range_readout_test.go`); `TestLostRangesBindsTheAnswer` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
| `INV-WS-LOST-RANGE-FAILCLOSED-001` | If an issued forced move's range record is missing or fails its range or HEAD-time checksum, the readout fails: the grant carries no range but the reason, the query returns `DataLoss`, the CLI exits 4; none reports the move as no loss. | M2 lease: Moved → epoch issued | `core/authority/workspace_lost_range.go` `LoadWorkspaceLostRanges`, `decodeLostRangeHeadTimes`, `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `grantWithLostRange`, `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `classify`, `checkRange`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange` | `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected` (`core/authority/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row7_ReadoutUnproven` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
@@ -755,7 +755,7 @@ Notes:
- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here.
- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models.
- `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). The holder check (`INV-WS-FORCED-CONFIRM-HOLDER-001`) sends that one `QueryWorkspace` RPC; only the move is withheld.
- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The validity is a duration computed on the master's wall clock (`time.Until`); `leaseFact` also caps it at 30 s and uses a 20 s bound when an older persisted lease carries none.
- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The authority-owned `WorkspaceLeaseValidity` computes duration on the publisher clock with its configured TTL and the larger configured/persisted skew, including legacy leases with no stored bound. Renewal admission, RPC replies and revocation ACK admission share that calculation; ACK uses the granted deadline clamped to the durable horizon.
- `INV-WS-LOST-RANGE-READOUT-001`: a stored range holds the kept HEAD's remote LSN; the forced-move barrier as LostUntil, in master time; the kept HEAD's generation (via the move record); and the HEAD entry's filer mtime read with that HEAD, or "unknown". A missing or damaged record is `INV-WS-LOST-RANGE-FAILCLOSED-001`. A failure after the issue (for example the binding reconciliation) is answered `Internal` naming the move ISSUED, never as a refusal: see M2 Moved → epoch issued. `PreviewWorkspaceMove` runs the forced admission, reads HEAD only once admitted, and writes nothing: see M2 Expired → Moved (forced) (tests `TestWorkspaceForcedMovePreviewWritesNothing`, `TestWorkspaceForceMove_Row2_DryRunPreview`).
- `INV-WS-LOST-RANGE-UNCERTAIN-001`, `INV-WS-LOST-RANGE-PRE-ISSUE-001`: on a volume already uncertain, every failed move, an admission refusal or a HEAD-read error included, is answered as an unknown outcome and logged as unknown; only the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see `INV-AUTH-UNCERTAIN-001` and M2 Uncertain → Uncertain (move answer).
- Enforced by reading (no test asserts it): the publisher's second admission check when it issues a forced move (`prepareWorkspaceMoveLocked` calls `forcedMoveAdmissionLocked`).
@@ -1028,6 +1028,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc
|---|---|---|---|---|
| Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | Existing `workspaceLeaseCloseoutTimeout` (3 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. |
| Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. |
| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s`. Each cycle is the assignment wait (default 30 s) + 5 s, reaching the limit in about 6 minutes. If the assignment wait exceeds about 55 s, raise the interval too or the window never fills | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. |
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
@@ -1060,7 +1061,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-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. A local-root nonce joins the pair later (pending). | `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, at most 30 s. | `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.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `Publisher.AckWorkspaceRevocation` (`core/authority/workspace.go`) checks expiry again inline, without the skew term: open. `leaseFact` (`core/host/master/workspace_service.go`) recomputes the host validity with `time.Now` instead of the publisher's clock, with a 20 s skew fallback, while `RenewWorkspaceLease` refuses a grant on the same term inline: open (one helper for both). `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 30 s TTL is written three times: the publisher's default TTL (`core/authority/authority.go`), the cap in `leaseFact`, and the reply bound in `Refresh`: 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. | authority (grant); volume host (guard) |
| `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. | `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. | 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 after the start-time wait. | `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 |
| `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host |
| `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host |
@@ -79,6 +79,21 @@ The binaries take command-line flags. The `SWB_*` variables are read only by
the example units, which turn them into flags. blockvolume itself reads only
`SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`.
Both blockvolume units restart failed processes after 5 seconds, except exit 78
(a no-restart outcome; the final log line names the reason). Exit 75 retries
through the ordinary lease and HEAD-claim gates.
`StartLimitIntervalSec=600` and `StartLimitBurst=10` in `[Unit]` allow at most
10 starts in a 10-minute window; another start in that window is refused and
the unit enters `failed` (`start-limit-hit`). This bounds retries on a host
that no longer holds the volume. Each retry cycle is the assignment wait
(default 30 seconds) plus `RestartSec=5s`, so the retries reach the limit in
about 6 minutes, inside 600 seconds. Raising the assignment wait above about
55 seconds prevents this window from filling; raise `StartLimitIntervalSec`
with it to retain the bound. After correcting the assignment or disabling
the obsolete unit, an operator can use `systemctl reset-failed <unit>` and
`systemctl start <unit>` to resume attempts. An ACKed planned stop exits 0
and is not automatically restarted.
## Required setup: make the volume known to blockmaster
blockmaster gives a blockvolume an assignment only for a volume and replica
@@ -0,0 +1,41 @@
package testops
import (
"strings"
"testing"
)
// M2 restart: the shipped supervisor bounds retries after exit 75.
func TestBlockvolumeUnitsBoundStartupRetries(t *testing.T) {
for _, name := range []string{"sw-blockvolume.service", "sw-blockvolume-ublk.service"} {
t.Run(name, func(t *testing.T) {
body := readRepoFile(t, "deploy", "systemd", name)
section := ""
seen := map[string]bool{}
for _, line := range strings.Split(body, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "[") {
section = line
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
want, checked := map[string]string{"StartLimitIntervalSec": "600", "StartLimitBurst": "10"}[key]
if !checked {
continue
}
if seen[key] || section != "[Unit]" || value != want {
t.Errorf("%s: %s=%s in %s (duplicate=%t), want %s=%s once in [Unit]", name, key, value, section, seen[key], key, want)
}
seen[key] = true
}
for _, key := range []string{"StartLimitIntervalSec", "StartLimitBurst"} {
if !seen[key] {
t.Errorf("%s: missing [Unit] %s", name, key)
}
}
})
}
}