Compare commits

..
Author SHA1 Message Date
pingqiuandClaude Opus 5.5 fb1cdd9a9a seaweed-block: the fail-stop witness's child is bounded and joined
Review: the child test binary ran with no deadline, so a join that hangs
would hang the witness. It now runs under a 30 s context (killed and
reaped at the deadline, with -test.timeout=20s of its own), and a
timeout fails as a timeout, never as the expected exit 3. A join that
hangs instead of exiting fails the witness in about 23 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:40:31 -08:00
pingqiuandClaude Opus 5.5 dee2ce19bb seaweed-block: docs: the unit check includes unloaded instances overridden by their own drop-ins
Review: list-unit-files finds unit files and templates, and list-units
finds instances in memory, so an unloaded instance whose ExecStart is
set only by its own drop-in directory was missed. The inventory now also
takes the enabled instance links and the instance drop-in directories;
systemctl cat on an instance shows the template with its drop-ins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:40:29 -08:00
pingqiuandClaude Opus 5.5 e045cbd39c seaweed-block: the rig's failed join exits without unwinding, proven in a child
Review: a panic in a cleanup still runs the later cleanups, so teardown
happened under a live worker. A failed join now ends the test binary
with os.Exit(3); a child test binary proves it: with a worker that never
returns it exits 3 and a later teardown cleanup never runs (its marker
is absent), with a returned worker it passes and the marker is present.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:18:56 -08:00
pingqiuandClaude Opus 5.5 deea764e4b seaweed-block: docs: the unit check covers every blockvolume unit; the notes drop the unconditional renewal claim
Review: the restart-binary check enumerates every blockvolume unit file
and template instance (sw-blockvolume*, loaded or not), since a
systemctl glob skips an enabled but stopped unit; and the v1.1.2 notes
now require the latest received report, say a v1.1.2 process renews
only after its own first answered heartbeat, and state the
delayed-report residual instead of claiming an old replacement can never
extend a lease.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:18:53 -08:00
pingqiuandClaude Opus 5.5 0e4fc3f35b seaweed-block: the fence test checks the bound from both sides; a failed join stops before teardown
Review: the never-answered test now measures from the lease runtime's own
wait start (a test hook) to its return and requires the bound, no less
and at most 500 ms more, so a runtime fencing at ten times the bound
fails it. The rig's cleanup join is fail-stop: a lease runtime that does
not return within 10 s stops the test binary before the host, the server
and the shared settings are torn down; a negative test covers the join.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:02:19 -08:00
pingqiuandClaude Opus 5.5 91abc295c2 seaweed-block: docs: the host check matches what --version prints; the guarantees name the latest report
Review: blockvolume --version prints 'revision=<commit> modified=<...>',
not a release number. The hard-rule check now compares every running
process's and every unit binary's line with the installed v1.1.x
binary's, and stops on another revision, modified=true or unknown, an
error or no output. The 30 s wait is described as usually catching a
missed process, not guaranteed to; the residual says a delayed report can
come from a stopped old process and grounds safety in which process can
still serve. The finalize ledger rows require the latest received report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 17:02:17 -08:00
pingqiuandClaude Opus 5.5 1889068239 seaweed-block: docs: the finalize operator text becomes a hard rule checked on each host
Ruling: a delayed heartbeat report can stand in for a newer process, so
the 30 s wait alone does not close the window. The manual and the v1.1.2
notes now state a hard rule, no v1.0.x volume process runs or starts from
the end of the upgrade until the finalize completes, checked on each host
from the running processes and the units rather than through blockmaster;
the wait stays as a backstop, and the remaining case is stated, not
claimed closed. v1.1.3 removes the rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 16:38:44 -08:00
pingqiuandClaude Opus 5.5 8b7df905ad seaweed-block: the first-heartbeat tests witness the window, test the bound and join the runtime
Review: the held-heartbeat test now waits until the first heartbeat is
inside the master's handler before checking that no renewal arrives, so
the window is witnessed open; the fence test checks that the lease
runtime waits its configured bound, no less, and names it in the fence
cause; both tests join the lease runtime within a bound at cleanup,
before the host and the server close.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 16:26:44 -08:00
pingqiuandClaude Opus 5.5 8ac51a2409 seaweed-block: docs: the operator procedure before the format finalize
The finalize section of the operations manual and the v1.1.2 notes state
the operator bound for the window before a new process's first answered
heartbeat: no v1.0.x volume process running or able to start until the
finalize completes, and a wait of at least 30 seconds after the last
volume process start. v1.1.3 carries the process identity on every
renewal and removes the procedure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 16:21:45 -08:00
pingqiuandClaude Opus 5.5 a11fe5165b seaweed-block: the v1.0-heartbeat check's intent case runs a real finalize
The intent case set only the master's finalizing flag; the renewal check
reads the publisher's own flag, which BeginFormatFinalize sets, so at
level 0 that case never reached the check. It now holds a real finalize
at its durable barrier, as the serving tests do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:37:52 -08:00
pingqiuandClaude Opus 5.5 2dae56beeb seaweed-block: the wait for the first answered heartbeat is bounded; past it the holder fences
Ruling: the first renewal waits for the first answered heartbeat at most
one lease validity (the longest validity a reply may carry); past that the
lease runtime installs its guard fenced, so a holder whose heartbeat is
never answered neither renews nor serves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:19:27 -08:00
pingqiuandClaude Opus 5.5 53bdf7442f seaweed-block: a v1.0-shaped heartbeat supersedes the cached report, so its renewals are refused
Identity check (2) of the format finalize bound: a heartbeat with no
incarnation and no reads level, from a new process on the holder's
server, replaces the capable predecessor's report for the volume (as
level 0), so that process's renewals are refused at level 1 and during
the finalize intent; the capable process renews again after reporting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:13:48 -08:00
pingqiuandClaude Opus 5.5 256f3dc68b seaweed-block: a holder's first lease renewal waits for its first answered heartbeat
The heartbeat loop closes a signal when the master first answers this
process's heartbeat; the workspace lease runtime starts its guard (and so
its first renewal) only after it, so every renewal is judged on this
process's own report. A host whose heartbeat loop never started has
nothing to wait for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:13:47 -08:00
pingqiuandClaude Opus 5.5 5b1d87eafc seaweed-block: red: a holder renews its lease before its first heartbeat is answered
Identity check (1) of the format finalize bound: until the master answers
a holder process's first heartbeat (which names its incarnation), it holds
only the predecessor's report for the volume, so a renewal in that window
is judged on the predecessor's proof. The lease runtime starts as soon as
the assignment epoch is known, independent of the heartbeat loop: with
the first heartbeat held open the holder renews anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:13:38 -08:00
Chris LuandClaude Opus 5.5 72293a16e3 seaweed-block: judge a heal or failover on the volume's own report
Only a same-owner endpoint refresh judged the volume's own process. A heal of
the current holder after a failed fence round, or a failover to a replica's
committed holder, places no new work on that server either, but it still read
the server's lowest level, so one old sibling process refused the recovery of
a capable holder. A reassign to the replica's committed holder now judges the
volume's own report like the refresh; a new placement keeps the server-wide
gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:22:34 -08:00
Chris LuandClaude Opus 5.5 49fa66919f seaweed-block: wait on a published line's owner, not every placed slot
A move does not rewrite the placement, so once a volume moved, its former
host's slot stayed in the grant waits. When that host's report for the volume
expired, the slot became a wait the new holder's reports never cleared, and
the status stayed degraded. The new holder, absent from the placement, got no
wait at all. A volume with a published line now waits on the line's owner
only; placed slots wait until a line exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:15:58 -08:00
Chris LuandClaude Opus 5.5 c9af4c6bb9 seaweed-block: pass the published line to the refresh owner check
The same-owner refresh check passed VolumeAuthorityLine's AuthorityBasis to
workspaceLineOwner, which takes a PublishedLine, so core/host/master did not
build. Resolve the owner through workspaceSourceHost, which reads the
published line for the same replica and epoch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:15:50 -08:00
pingqiu e52261bf51 fix(block): preserve capable refresh and report waits during finalize 2026-12-05 14:10:00 -08:00
pingqiu 82b5e521cd Normalize finalize manual ending after master merge 2026-12-05 12:53:55 -08:00
pingqiu 0eaa2db23e Merge master and preserve finalize release guidance 2026-12-05 12:52:25 -08:00
pingqiu 4e40e691ab fix: preserve durability exit contract and strengthen finalize controls 2026-12-05 05:46:00 -08:00
pingqiu c34bc1bdeb fix: distinguish format placements from serving grants 2026-12-05 05:21:57 -08:00
pingqiu 5a6dc81a69 fix: retain current process report checks across finalize 2026-12-05 04:37:51 -08:00
pingqiu 3b213b4915 test: pin finalize intent crash and refusal behavior 2026-12-05 04:06:41 -08:00
pingqiu 6f737f7419 fix(block): guard format finalize with serving-holder reports 2026-12-05 03:51:25 -08:00
pingqiu 684e87c0b2 test(block): expose serving-report and finalize grant races 2026-12-05 03:06:30 -08:00
57 changed files with 3069 additions and 1972 deletions

No files matched your search

+1042 -1030
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 54 KiB

+12 -1
View File
@@ -1,4 +1,6 @@
# Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
# FormatGate.Finalize: BeginFormatFinalize checks and sets its memory-only intent atomically under Publisher mu + leaseMu; the durable raise holds neither lock.
# FormatGate.Grant: grants/regrants and deadline-extending renewals require GrantReport (a current process report) during intent and at level 1.
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
cmd/sw-block/chunk.go CutTime.Poll
cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
@@ -18,7 +20,11 @@ cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
cmd/sw-block/volume_verbs.go CutTime.Poll
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
core/authority/authority.go DeleteRetire.RetireLine
core/authority/authority.go FormatGate.Finalize
core/authority/authority.go FormatGate.Place
core/authority/authority_store_file.go DeleteRetire.RetireLine
core/authority/format_finalize.go FormatGate.Finalize
core/authority/format_finalize.go FormatGate.Grant
core/authority/workspace.go HolderInterface.ForcedMove
core/authority/workspace.go HolderInterface.PlannedMove
core/authority/workspace.go MoveAdmission.Ack
@@ -34,6 +40,9 @@ core/authority/workspace.go StopAndRestart.LeaseEnds
core/authority/workspace.go StopAndRestart.ReadForced
core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
core/authority/workspace_lease_v100.go FormatGate.Finalize
core/authority/workspace_lease_view.go FormatGate.Grant
core/authority/workspace_lease_view.go FormatGate.Renew
core/authority/workspace_lease_view.go HolderInterface.Grant
core/authority/workspace_lease_view.go HolderInterface.Regrant
core/authority/workspace_retirement.go DeleteRetire.RetireLine
@@ -207,9 +216,11 @@ core/host/master/product_loop.go FencingRound.Decide
core/host/master/product_loop.go Promotion.Decide
core/host/master/services.go FormatGate.Report
core/host/master/spec_retirement.go DeleteRetire.ReadOK
core/host/master/store_attestation.go FormatGate.Finalize
core/host/master/store_attestation.go ReplicationPeer.Attest
core/host/master/workspace_binding.go FormatGate.Grant
core/host/master/workspace_binding.go FormatGate.Place
core/host/master/workspace_binding.go MoveAdmission.Ack
core/host/master/workspace_service.go FormatGate.Grant
core/host/master/workspace_service.go FormatGate.Place
core/host/master/workspace_service.go FormatGate.Renew
core/host/master/workspace_service.go MoveAdmission.ReadForMove
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
2 # FormatGate.Finalize: BeginFormatFinalize checks and sets its memory-only intent atomically under Publisher mu + leaseMu; the durable raise holds neither lock.
3 # FormatGate.Grant: grants/regrants and deadline-extending renewals require GrantReport (a current process report) during intent and at level 1.
4 cmd/blockvolume/snapshot_operation_shutdown.go
5 cmd/sw-block/chunk.go
6 cmd/sw-block/cut_progress_poll.go
20 cmd/sw-block/volume_verbs.go
21 cmd/sw-block/workspace_show.go
22 core/authority/authority.go
23 core/authority/authority.go
24 core/authority/authority.go
25 core/authority/authority_store_file.go
26 core/authority/format_finalize.go
27 core/authority/format_finalize.go
28 core/authority/workspace.go
29 core/authority/workspace.go
30 core/authority/workspace.go
40 core/authority/workspace.go
41 core/authority/workspace_delete_reservation.go
42 core/authority/workspace_delete_reservation.go
43 core/authority/workspace_lease_v100.go
44 core/authority/workspace_lease_view.go
45 core/authority/workspace_lease_view.go
46 core/authority/workspace_lease_view.go
47 core/authority/workspace_lease_view.go
48 core/authority/workspace_retirement.go
216 core/host/master/product_loop.go
217 core/host/master/services.go
218 core/host/master/spec_retirement.go
219 core/host/master/store_attestation.go
220 core/host/master/store_attestation.go
221 core/host/master/workspace_binding.go
222 core/host/master/workspace_binding.go
223 core/host/master/workspace_service.go
224 core/host/master/workspace_service.go
225 core/host/master/workspace_service.go
226 core/host/master/workspace_service.go
@@ -13,7 +13,6 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -50,11 +49,11 @@ func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
out, runErr := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("master did not fail-stop with exit74: %v context=%v\n%s", runErr, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master did not fail-stop with exit1: %v context=%v\n%s", runErr, ctx.Err(), out)
}
text := string(out)
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
t.Fatalf("missing single persistence ERROR: %s", text)
}
oldRaw, err := json.Marshal(old)
@@ -26,13 +26,6 @@ import (
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
//
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
// kill: the tick that ends creation comes at most a loop after it, the
// loss a window after that tick's silence floor, and the tick that reads
// the loss at most a loop later. The test waits twice that.
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
@@ -55,8 +48,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
}
master := h.start(t, "blockmaster", bins.master,
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for _, b := range hosts {
lockDir := b.root + ".locks"
@@ -91,8 +84,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
// 3. The next tick reads the survivors' write: creation ended, and the
// gate fails the volume over.
var p2 *host
predicted := gapLoop + gapWindow + gapLoop
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
@@ -6,6 +6,9 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"regexp"
"strings"
"testing"
"time"
@@ -18,14 +21,26 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// The real master issues the move and reports the current holder. Only the unit and holder
// process are fixtures: enabling the unit renews the real assigned epoch;
// the holder's stop ACK goes through the real detached-HEAD check.
func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
for _, loseAnswer := range []bool{false, true} {
t.Run(fmt.Sprintf("lost-answer-%v", loseAnswer), func(t *testing.T) {
if os.Getenv("VOLUME_START_MASTER_CHILD") != t.Name() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
cmd.Env = append(os.Environ(), "VOLUME_START_MASTER_CHILD="+t.Name())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("bounded master stop/restart/start child: %v\n%s", err, out)
}
return
}
for _, tc := range []struct{ loseAnswer, restartMaster bool }{{false, false}, {true, false}, {false, true}, {true, true}} {
loseAnswer := tc.loseAnswer
t.Run(fmt.Sprintf("lost-answer-%v/master-restart-%v", loseAnswer, tc.restartMaster), func(t *testing.T) {
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
t.Setenv(key, "")
}
@@ -42,6 +57,7 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
}
defer conn.Close()
rpc := control.NewWorkspaceServiceClient(conn)
observations := control.NewObservationServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newFakeHost(t)
@@ -66,6 +82,12 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
exited79 := false
env.Systemctl = func(ctx context.Context, args ...string) (string, error) {
if args[0] == "enable" {
// A real newly enabled holder reports before it can receive its
// first serving deadline; a move record alone grants no I/O.
if _, err := observations.ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil {
return "report", err
}
ws, err := rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"})
if err != nil {
return "query", err
@@ -109,6 +131,22 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
if code, out, errs := runStop(env, stopOpts{Volume: "vol-f", NoCut: true, Timeout: time.Second}); code != 0 {
t.Fatalf("stop=%d %s %s", code, out, errs)
}
if tc.restartMaster {
// Keep the configured endpoint while losing all memory-only reports.
cfg.Listen = mh.Addr()
stop()
_ = conn.Close()
restarted, restartStop := startDeleteMaster(t, cfg)
defer restartStop()
restartedConn, err := grpc.NewClient(restarted.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer restartedConn.Close()
rpc = control.NewWorkspaceServiceClient(restartedConn)
observations = control.NewObservationServiceClient(restartedConn)
recorder.WorkspaceServiceClient = rpc
}
code, out, errs := runStart(env, v, startOpts{Wait: time.Second})
if loseAnswer {
if code != wsExitUnknown || h.called("enable") != 1 {
+3 -1
View File
@@ -189,7 +189,9 @@ type Publisher struct {
// 0 keeps v1.0's master semantics (a current lease horizon, version-1
// records), 1 is v1.1's. Written under mu and leaseMu, read under
// either.
formatLevel uint32
formatLevel uint32
formatFinalizing bool // guarded by mu and leaseMu; no store I/O while setting it
requireFormatReadProofs bool // configured by the master before serving
// Level 0's horizon extender (workspace_lease_v100.go).
leaseClosing bool // guarded by mu and leaseMu
extWG sync.WaitGroup // admitted extenders
@@ -32,9 +32,8 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) {
// non-nil error replaces that step's result. Tests only.
var dirFault atomic.Pointer[func(step string) error]
// ExitDurabilityUnknown is the process exit code of a fail-stop whose
// persisted outcome is unknown (sysexits EX_IOERR): an authority record's
// rename here, or blockmaster's lifecycle store persistence failure.
// ExitDurabilityUnknown is the process exit code of the fail-stop after a
// record's rename whose durability is unknown (sysexits EX_IOERR).
const ExitDurabilityUnknown = 74
// failStopDurabilityUnknown ends the process: the rename is done but the
+25 -102
View File
@@ -32,7 +32,6 @@ type TopologyController struct {
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
outcome map[string]string // volume -> what the last intake did with it (LastOutcome); kept like bootGrace
now func() time.Time
}
@@ -45,21 +44,10 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
unsupported: make(map[string]UnsupportedEvidence),
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
bootGrace: make(map[string]*primaryBootGrace),
outcome: make(map[string]string),
now: time.Now,
}
}
// LastOutcome says what the last snapshot intake that carried the volume
// as supported did with it: the ask it enqueued, or why it enqueued none
// ("" before any). The master logs it beside a promotion gate's replace
// decision, so a decision the controller did not act on says why.
func (c *TopologyController) LastOutcome(volumeID string) string {
c.mu.Lock()
defer c.mu.Unlock()
return c.outcome[volumeID]
}
// SetNowForTest overrides the controller's clock source. Tests
// use this to drive RetryWindow / Stuck transitions deterministically.
// Production code MUST NOT call this.
@@ -137,21 +125,6 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error {
// desired state live; SubmitObservedState always processes the
// report.
func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
return c.submitObservedState(snap, report, nil)
}
// SubmitObservedStateOutcomes is SubmitObservedState that also returns what
// this intake did with each volume it carried (supported, pending or
// unsupported), read while the intake still holds the controller's lock: a
// later intake (the background observation host shares the controller)
// cannot change it. A volume this intake did not carry has no entry.
func (c *TopologyController) SubmitObservedStateOutcomes(snap ClusterSnapshot, report SupportabilityReport) (map[string]string, error) {
out := map[string]string{}
err := c.submitObservedState(snap, report, out)
return out, err
}
func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report SupportabilityReport, outcomes map[string]string) error {
// Validate non-empty supported snapshots the same way
// SubmitClusterSnapshot does. Empty supported + empty report
// is allowed (no-op).
@@ -190,7 +163,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
// stale unsupported record from a prior build is cleared,
// because pending is a transitional state, not a fault.
delete(c.unsupported, vid)
c.outcome[vid] = "no ask: supportability pending"
}
for vid, ev := range report.Unsupported {
c.clearDesiredLocked(vid)
@@ -208,7 +180,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
Basis: AuthorityBasis{},
Reason: joinReasons(ev.Reasons),
}
c.outcome[vid] = "no ask: unsupported: " + joinReasons(ev.Reasons)
}
// Process supported volumes via the existing decision path.
@@ -225,17 +196,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID)
c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
}
if outcomes != nil {
for vid := range report.Pending {
outcomes[vid] = c.outcome[vid]
}
for vid := range report.Unsupported {
outcomes[vid] = c.outcome[vid]
}
for _, vol := range volumes {
outcomes[vol.VolumeID] = c.outcome[vol.VolumeID]
}
}
return nil
}
@@ -292,13 +252,11 @@ func (c *TopologyController) processSupportedVolumeLocked(
if vol.Authority.Assigned && !volumeIncludesReplica(vol, vol.Authority.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, vol.Authority, "snapshot authority outside accepted topology: "+vol.Authority.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: snapshot authority outside accepted topology"
return
}
if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: publisher authority outside accepted topology"
return
}
@@ -311,44 +269,24 @@ func (c *TopologyController) processSupportedVolumeLocked(
// Stale snapshot: do not emit from a stale basis, but keep any
// existing desired (publish-until-observed convergence record).
if !basisMatchesLine(vol.Authority, currentLine, hasLine) {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: stale snapshot basis %s@%d, line %s@%d", vol.Authority.ReplicaID, vol.Authority.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
// Stale slot facts: likewise keep any existing desired and emit
// nothing from this snapshot.
if staleFacts {
c.outcome[vol.VolumeID] = "no ask: superseded slot facts"
return
}
ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
if !emit {
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: " + reason
return
}
// Same-ask dedupe: while the identical ask is pending (queued, or
// taken by the publisher and still being applied), do not
// re-enqueue. Without this guard, repeated identical supported
// feeds would mint a new Reassign epoch each iteration —
// authority churn. An identical ask that is no longer pending
// ended without a publication (lost): enqueue it again, keeping
// its DesiredAt so a repeatedly lost ask still reports Stuck.
// Same-ask dedupe: if the identical ask is already the current
// desired, do not re-enqueue. Without this guard, repeated
// identical supported feeds would mint a new Reassign epoch
// each iteration — authority churn.
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
since := prev.DesiredAt.UTC().Format(time.RFC3339Nano)
if c.queue.pending(vol.VolumeID) {
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", since, ask.Intent, ask.ReplicaID, prev.Reason)
return
}
// Not pending also after the publisher published it since the line
// was read: lost only while the line is still the one decided against.
if line, ok := c.reader.VolumeAuthorityLine(vol.VolumeID); ok != hasLine || line != currentLine {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: the line moved to %s@%d while deciding against %s@%d", line.ReplicaID, line.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued again %s %s (%s): desired since %s, its last ask ended without a publication", ask.Intent, ask.ReplicaID, prev.Reason, since)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
return
}
@@ -370,7 +308,6 @@ func (c *TopologyController) processSupportedVolumeLocked(
}
c.desired[vol.VolumeID] = desired
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued %s %s (%s)", ask.Intent, ask.ReplicaID, reason)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
}
@@ -535,7 +472,7 @@ func (c *TopologyController) decideVolume(
if !hasLine {
cands := placeableCandidates(vol, serverIndex)
if len(cands) == 0 {
return AssignmentAsk{}, "no placeable candidate for the first line", false
return AssignmentAsk{}, "", false
}
best := choosePlacementCandidate(cands, projectedLoad)
return AssignmentAsk{
@@ -550,7 +487,7 @@ func (c *TopologyController) decideVolume(
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
if !ok {
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
return AssignmentAsk{}, "", false
}
if candidateAcceptable(current, serverIndex) {
@@ -563,20 +500,19 @@ func (c *TopologyController) decideVolume(
// current primary is alive, so it is a planned move: the same
// guard as a failback (the target in every acknowledgement set).
if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion || !target.PlannedMoveAllowed {
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
return AssignmentAsk{}, "", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
}, "rebalance", true
}
return AssignmentAsk{}, "the current primary is acceptable", false
return AssignmentAsk{}, "", false
}
// A restarted current primary that is placeable but not ready yet
@@ -586,13 +522,9 @@ func (c *TopologyController) decideVolume(
if !superseded && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
}
if superseded {
return AssignmentAsk{}, "the current primary holds its boot grace (by its newer recorded fact)", false
}
return AssignmentAsk{}, "the current primary holds its boot grace", false
return AssignmentAsk{}, "", false
}
why := "no acceptable candidate besides the current primary"
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
if len(other) > 0 {
best := chooseFailoverCandidate(other, projectedLoad)
@@ -600,17 +532,15 @@ func (c *TopologyController) decideVolume(
// its target (one decider): no evidence, no promotion.
if best.PromotionEvidence.Kind == adapter.PrimaryKindPromotion {
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
}, "failover", true
}
why = "failover target " + best.ReplicaID + " has no promotion evidence"
}
// No promotion-ready peer exists. Keep the current authority endpoint fresh
// when the current replica is still reachable/eligible; this preserves
@@ -618,7 +548,7 @@ func (c *TopologyController) decideVolume(
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
}
return AssignmentAsk{}, why, false
return AssignmentAsk{}, "", false
}
// endpointStale reports whether the current primary's line needs a new
@@ -641,17 +571,10 @@ func refreshAsk(volumeID string, current ReplicaCandidate, line AuthorityBasis)
CtrlAddr: current.CtrlAddr,
Intent: IntentRefreshEndpoint,
Incarnation: current.Incarnation,
ExpectCurrent: expectedLineOf(line),
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr},
}
}
// expectedLineOf conditions an ask on the line it was decided against: a
// publication that lands while the ask waits in the queue (an operator's
// failback) refuses it instead of being overwritten.
func expectedLineOf(line AuthorityBasis) *ExpectedLine {
return &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
}
func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool {
for _, slot := range vol.Slots {
if slot.ReplicaID == replicaID {
@@ -1,252 +0,0 @@
package authority
import (
"context"
"errors"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// The same-ask dedupe holds a desired Reassign only while that ask is
// pending: queued, or taken by the publisher and still being applied. An
// ask the publisher took and ended without publishing (its apply refused
// it) is lost, and the next intake of the same state enqueues it again.
// Holding the lost ask as "already desired" would keep the volume on its
// old primary for good.
func TestALostReassignIsEnqueuedAgainOnTheNextIntake(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{}, reader)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
submit := func() {
t.Helper()
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
}
submit()
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
// The publisher holds the ask (applying it): the same state again is
// deduplicated, nothing is queued twice.
submit()
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "already desired since ") {
t.Fatalf("while the ask is being applied: outcome %q, want already desired", out)
}
// The apply ended without a publication (the line is still r1@1) and
// the publisher waits for its next ask: the ask is lost.
next := make(chan AssignmentAsk, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
go func() {
if ask, err := ctrl.Next(ctx); err == nil {
next <- ask
}
}()
synctest.Wait() // the publisher is back in Next, holding nothing
submit()
select {
case ask := <-next:
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("after the loss: %+v, want Reassign r2 again", ask)
}
case <-ctx.Done():
t.Fatalf("a lost Reassign was never enqueued again; the controller's outcome: %q", ctrl.LastOutcome("v1"))
}
})
}
// A Reassign lost again and again keeps its first DesiredAt across every
// re-enqueue, so it still becomes Stuck once the retry window passes from
// that first desire: a retry that re-anchored DesiredAt would never report
// the volume stuck however long its asks keep failing.
func TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck(t *testing.T) {
const window = 10 * time.Second
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{RetryWindow: window}, reader)
clk := newFakeClock(time.Date(2026, 12, 5, 9, 0, 0, 0, time.UTC))
ctrl.SetNowForTest(clk.Now)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
first := clk.Now()
ended, cancel := context.WithCancel(context.Background())
cancel() // the publisher's next call after an apply that published nothing
for cycle := 0; cycle < 4; cycle++ {
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if cycle > 0 && !strings.HasPrefix(ctrl.LastOutcome("v1"), "enqueued again Reassign r2") {
t.Fatalf("cycle %d: outcome %q, want the lost ask enqueued again", cycle, ctrl.LastOutcome("v1"))
}
if d, ok := ctrl.DesiredFor("v1"); !ok || !d.DesiredAt.Equal(first) {
t.Fatalf("cycle %d at +%v: desired %+v (ok=%v), want DesiredAt kept at the first desire %v", cycle, clk.Now().Sub(first), d, ok, first)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("cycle %d: took %+v, want Reassign r2", cycle, ask)
}
_, _ = ctrl.Next(ended) // the apply ended without a publication: the ask is lost
clk.Advance(4 * time.Second)
}
// +16 s since the first desire, past the 10 s window: the latest intake
// (+12 s) found the desire unconfirmed past the window.
ev, stuck := ctrl.LastConvergenceStuck("v1")
if !stuck {
t.Fatalf("a Reassign lost on every apply for %v is not reported stuck (window %v)", clk.Now().Sub(first), window)
}
if !ev.DesiredAt.Equal(first) || ev.Ask.ReplicaID != "r2" {
t.Fatalf("stuck evidence %+v, want the first desire (%v) of Reassign r2", ev, first)
}
}
// publishOnRead runs publish once, right after the controller's skip+1-th
// line read: the publisher applies its ask between the read an intake decides
// against and that intake's dedupe.
type publishOnRead struct {
*fakeBasisReader
skip int
publish func()
}
func (r *publishOnRead) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) {
line, ok := r.fakeBasisReader.VolumeAuthorityLine(volumeID)
if r.publish != nil {
if r.skip > 0 {
r.skip--
} else {
p := r.publish
r.publish = nil
p()
}
}
return line, ok
}
// An ask the publisher publishes, and then asks past, while an intake is
// deciding against the line read before that publication is not lost: the
// intake must not enqueue it again, or a planned move would be minted twice.
func TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
publishing := &publishOnRead{fakeBasisReader: reader}
ctrl := NewTopologyController(TopologyControllerConfig{}, publishing)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
ended, cancel := context.WithCancel(context.Background())
cancel()
publishing.skip = 1 // the intake's load count reads the line first
publishing.publish = func() {
reader.Set("v1", "r2", AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"})
_, _ = ctrl.Next(ended) // published: the publisher is back for its next ask
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); strings.HasPrefix(out, "enqueued again") {
t.Fatalf("an ask published during the intake was enqueued again: %q", out)
}
expectNoNext(t, ctrl)
}
// A controller Reassign waits in the queue until the publisher takes it. A
// publication that lands meanwhile outside the queue (an operator's failback)
// is not overwritten by the ask decided against the older line, whether the
// ask is a first one or a lost one enqueued again.
func TestAQueuedReassignDoesNotOverwriteALaterPublication(t *testing.T) {
for _, lost := range []bool{false, true} {
holder := &basisReaderHolder{}
ctrl := NewTopologyController(TopologyControllerConfig{}, holder)
pub := NewPublisher(ctrl)
holder.set(pub)
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
line, _ := pub.VolumeAuthorityLine("v1")
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if lost {
nextAskOrFail(t, ctrl)
ended, cancel := context.WithCancel(context.Background())
cancel()
_, _ = ctrl.Next(ended) // the apply ended without a publication
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "enqueued again Reassign r2") {
t.Fatalf("outcome %q, want the lost ask enqueued again", out)
}
}
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign,
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 10, Basis: adapter.BasisPlanned},
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch}}); err != nil {
t.Fatalf("failback: %v", err)
}
ask := nextAskOrFail(t, ctrl)
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("lost=%v: took %+v, want Reassign r2", lost, ask)
}
if err := pub.apply(ask); !errors.Is(err, ErrExpectedLineMoved) {
t.Fatalf("lost=%v: the queued Reassign decided against %s@%d: err=%v, want ErrExpectedLineMoved", lost, line.ReplicaID, line.Epoch, err)
}
if after, _ := pub.VolumeAuthorityLine("v1"); after.ReplicaID != "r3" || after.Epoch != line.Epoch+1 {
t.Fatalf("lost=%v: line %+v, want the failback's r3@%d", lost, after, line.Epoch+1)
}
}
}
@@ -0,0 +1,114 @@
package authority
import (
"fmt"
"sort"
"sync/atomic"
"time"
)
// FormatReadProof is an in-memory report captured before entering grant locks.
// Revision changes whenever a reporting process or its read level changes.
// Reading it under the grant locks is atomic and never waits on another lock.
type FormatReadProof struct {
Server, Process, Replica string
Epoch uint64
Reads uint32
Reported bool
Revision *atomic.Uint64
Version uint64
}
func (r FormatReadProof) current(replica string, epoch uint64, incarnation string) bool {
return r.Reported && r.Reads >= 1 && r.Replica == replica && r.Epoch == epoch &&
r.Revision != nil && r.Revision.Load() == r.Version &&
(incarnation == "" || r.Process == incarnation)
}
// FormatServingBlocker names a possibly-serving process without a proven report.
type FormatServingBlocker struct{ Volume, Server, Detail string }
// RequireFormatReadProofs enables the master's report gate before serving.
func (p *Publisher) RequireFormatReadProofs() {
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.requireFormatReadProofs = true
}
// BeginFormatFinalize atomically checks possible live leases and closes the
// level-0 grant path. No I/O or caller callback runs under these locks.
// The caller serializes placement/owner changes with this memory step, then
// admits new work at the target level while the durable write runs.
func (p *Publisher) BeginFormatFinalize(proofs map[string]FormatReadProof, otherGuardsPassed bool) []FormatServingBlocker {
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
now := p.workspaceNow()
var blocked []FormatServingBlocker
for volume, lv := range p.leaseViews {
if !lv.d.bound || !lv.d.leasePresent || (lv.d.revoking && lv.d.ackRecorded) {
continue
}
skew := time.Duration(lv.d.maxSkewNS)
until := lv.deadline.Add(skew)
if p.formatLevel == 0 {
if horizon := time.Unix(0, lv.d.horizon).Add(skew); horizon.After(until) {
until = horizon
}
}
if !lv.d.uncertain && !now.Before(until) {
continue
}
proof := proofs[volume]
_, line, ok := p.workspaceLineLocked(volume)
if ok && (lv.d.issuedHost == "" || proof.Server == lv.d.issuedHost) && proof.current(lv.d.replica, lv.d.epoch, line.info.Incarnation) {
continue
}
server := proof.Server
if lv.d.issuedHost != "" {
server = lv.d.issuedHost
}
if server == "" {
server = "unknown"
}
detail := fmt.Sprintf("volume %s: serving process has not reported reading level 1", volume)
if proof.Process != "" {
detail += fmt.Sprintf(" (process %s reads level %d)", proof.Process, proof.Reads)
}
blocked = append(blocked, FormatServingBlocker{volume, server, detail})
}
sort.Slice(blocked, func(i, j int) bool {
if blocked[i].Server == blocked[j].Server {
return blocked[i].Volume < blocked[j].Volume
}
return blocked[i].Server < blocked[j].Server
})
if len(blocked) == 0 && otherGuardsPassed {
p.formatFinalizing = true
p.requireFormatReadProofs = true
}
return blocked
}
// CancelFormatFinalize reopens the level-0 grant path after a failed durable raise.
func (p *Publisher) CancelFormatFinalize() {
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatFinalizing = false
}
// Caller holds mu or leaseMu; proof validation reads atomics only.
func (p *Publisher) formatReadProofError(proof FormatReadProof, replica string, epoch uint64, incarnation string) error {
if !p.requireFormatReadProofs || (p.formatLevel == 0 && !p.formatFinalizing) {
return nil
}
if !proof.current(replica, epoch, incarnation) {
return fmt.Errorf("workspace lease: node %q's process must report reading format level 1 before a grant or lease extension (binary_too_old or no current report)", proof.Server)
}
return nil
}
@@ -0,0 +1,240 @@
package authority
import (
"context"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"sync/atomic"
"testing"
"time"
)
// Both the abrupt exit and recovery lifetime are bounded by the parent.
func TestFormatFinalizeIntentDoesNotSurviveProcessExit(t *testing.T) {
if phase := os.Getenv("FORMAT_INTENT_CRASH_PHASE"); phase != "" {
disk, err := NewFileAuthorityStore(os.Getenv("FORMAT_INTENT_CRASH_STORE"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = disk.Close() })
clock := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, clock)
if phase == "crash" {
bindAndGrant(t, p, "v", "r")
clock.at(120)
if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 || !p.formatFinalizing || p.FormatLevel() != 0 {
t.Fatalf("before durable raise: intent=%v level=%d blockers=%v", p.formatFinalizing, p.FormatLevel(), blocked)
}
os.Exit(23) // no Close, no Cancel, no durable raise
}
p.RequireFormatReadProofs()
if p.FormatLevel() != 0 || p.formatFinalizing {
t.Fatalf("restart retained intent or raised level: intent=%v level=%d", p.formatFinalizing, p.FormatLevel())
}
clock.at(360)
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatalf("restart changed the level-0 regrant path: %v", err)
}
return
}
dir := t.TempDir()
for _, phase := range []string{"crash", "recover"} {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
cmd.Env = append(os.Environ(), "FORMAT_INTENT_CRASH_PHASE="+phase, "FORMAT_INTENT_CRASH_STORE="+dir)
out, err := cmd.CombinedOutput()
cancel()
if phase == "crash" {
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 23 {
t.Fatalf("intent child did not reach its own crash boundary: %v\n%s", err, out)
}
} else if err != nil {
t.Fatalf("bounded recovery: %v\n%s", err, out)
}
}
}
func TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen(t *testing.T) {
for _, otherGuardsPassed := range []bool{false, true} {
t.Run(fmt.Sprint(otherGuardsPassed), func(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, clock)
p.RequireFormatReadProofs()
if otherGuardsPassed {
bindAndGrant(t, p, "v", "r") // serving-report check fails
}
blocked := p.BeginFormatFinalize(nil, otherGuardsPassed)
if otherGuardsPassed && len(blocked) == 0 {
t.Fatal("unreported serving holder was not refused")
}
if p.formatFinalizing || p.FormatLevel() != 0 {
t.Fatal("failed check left an admission intent or raised the level")
}
if err := p.apply(AssignmentAsk{VolumeID: "fresh", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
t.Fatalf("failed finalize changed level-0 publication: %v", err)
}
})
}
}
func TestFormatFinalizeIntentRequiresRegrantReport(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, clock)
bindAndGrant(t, p, "v", "r")
p.RequireFormatReadProofs()
clock.at(120) // both the deadline and level-0 persisted horizon have ended
if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 {
t.Fatalf("ended lease blocks finalize: %v", blocked)
}
// The durable envelope has not yet been written: the actual level stays 0.
if got := p.FormatLevel(); got != 0 {
t.Fatalf("intent prematurely raised level=%d", got)
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "must report") {
t.Fatalf("regrant without report during durable raise: %v", err)
}
revision := &atomic.Uint64{}
proof := FormatReadProof{Server: "node", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
t.Fatalf("capable regrant during intent: %v", err)
}
clock.at(240)
revision.Add(1) // report changed after a proof was captured, before re-grant
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err == nil {
t.Fatal("stale process proof revived a lease")
}
proof.Version = revision.Load()
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
t.Fatalf("fresh proof did not retry: %v", err)
}
p.CancelFormatFinalize()
if p.formatFinalizing {
t.Fatal("failed raise kept the intent")
}
// Clearing a failed raise restores the level-0 path (no report required).
clock.at(360)
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatalf("level-0 retry after failed finalize: %v", err)
}
}
func TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases(t *testing.T) {
for _, state := range []string{"live", "released", "ended", "unserved"} {
t.Run(state, func(t *testing.T) {
clock := newTestClock()
disk, _ := newTempStore(t)
p := level0Publisher(t, disk, 30*time.Second, clock)
bindAndGrant(t, p, "v", "r")
switch state {
case "released":
ctx := context.Background()
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Gen: 7, Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
t.Fatal(err)
}
case "ended":
clock.at(120)
case "unserved":
// An authority line alone is not a grant: reconstruct its no-lease view.
p.mu.Lock()
p.workspace["v"] = &WorkspaceState{}
p.refreshLeaseViewLocked("v")
p.mu.Unlock()
}
blocked := p.BeginFormatFinalize(nil, true)
if (len(blocked) > 0) != (state == "live") {
t.Fatalf("%s: blockers=%v", state, blocked)
}
if state == "live" && (blocked[0].Volume != "v" || !strings.Contains(blocked[0].Detail, "serving")) {
t.Fatalf("unnamed live holder: %v", blocked)
}
})
}
}
func TestFormatFinalizeLiveRenewalChecksCurrentProcess(t *testing.T) {
disk, _ := newTempStore(t)
p := level0Publisher(t, disk, 30*time.Second, newTestClock())
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Incarnation: "capable", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
revision := &atomic.Uint64{}
proof := FormatReadProof{Server: "node", Process: "capable", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
if blocked := p.BeginFormatFinalize(map[string]FormatReadProof{"v": proof}, true); len(blocked) != 0 {
t.Fatal(blocked)
}
for _, phase := range []string{"intent", "complete"} {
if phase == "complete" {
p.FinalizeFormatLevel()
}
for _, invalid := range []string{"missing", "old", "replacement", "stale"} {
bad := proof
switch invalid {
case "missing":
bad.Reported = false
case "old":
bad.Reads = 0
case "replacement":
bad.Process = "replacement"
case "stale":
bad.Version++
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, bad); err == nil {
t.Fatalf("%s: %s report renewed a live lease", phase, invalid)
}
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
t.Fatalf("%s: current capable process could not renew: %v", phase, err)
}
}
}
func TestFormatFinalizeDeadlineProofSurvivesIntentCompletion(t *testing.T) {
for _, path := range []string{"first", "live", "regrant"} {
t.Run(path, func(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, clock)
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
if path != "first" {
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
}
if path == "regrant" {
clock.at(120)
}
revision := &atomic.Uint64{}
proof := FormatReadProof{Server: "node", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
if blocked := p.BeginFormatFinalize(map[string]FormatReadProof{"v": proof}, true); len(blocked) != 0 {
t.Fatal(blocked)
}
p.testBeforeGrantLock = func(site string) {
if site == "renewal" {
revision.Add(1) // captured before the process report changed
p.FinalizeFormatLevel()
}
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err == nil {
t.Fatal("stale proof crossed intent completion into a serving deadline")
}
p.testBeforeGrantLock = nil
proof.Version = revision.Load()
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
t.Fatalf("current capable proof did not retry after completion: %v", err)
}
})
}
}
-17
View File
@@ -14,10 +14,6 @@ type assignmentQueue struct {
items map[string]AssignmentAsk
order []string
wake chan struct{}
// taken is the volume of the ask the publisher took last and is still
// applying: it is cleared when the publisher asks for its next one (the
// publisher applies one ask at a time, between two calls of next).
taken string
}
func newAssignmentQueue() *assignmentQueue {
@@ -46,19 +42,7 @@ func (q *assignmentQueue) discard(volumeID string) {
delete(q.items, volumeID)
}
// pending reports whether volumeID's ask is queued or still being applied.
// A desired ask that is neither ended without a publication (lost).
func (q *assignmentQueue) pending(volumeID string) bool {
q.mu.Lock()
defer q.mu.Unlock()
_, queued := q.items[volumeID]
return queued || q.taken == volumeID
}
func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
q.mu.Lock()
q.taken = "" // the publisher is done with the ask it took last
q.mu.Unlock()
for {
q.mu.Lock()
if len(q.order) > 0 {
@@ -70,7 +54,6 @@ func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
continue
}
delete(q.items, vid)
q.taken = vid
q.mu.Unlock()
return ask, nil
}
@@ -58,6 +58,7 @@ func (p *Publisher) FinalizeFormatLevel() {
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatLevel = 1
p.formatFinalizing = false
}
// envelopeVersionLocked is the record envelope version the level writes:
@@ -18,6 +18,7 @@ var ErrWorkspaceRevoked = errors.New("workspace lease: revocation ACK is recorde
type leaseDerived struct {
bound bool // an authority line exists for the volume
replica string
incarnation string // current line's process identity; renewal reads only leaseMu
epoch uint64
ownerFromMove bool
issuedHost string // NewHost of the issued move that minted the line; "" if none
@@ -48,6 +49,7 @@ func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))}
if _, line, ok := p.workspaceLineLocked(volume); ok {
d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch
d.incarnation = line.info.Incarnation
d.issuedHost, d.ownerFromMove = line.info.ServerID, line.info.OwnerFromMove
}
if s := p.workspace[volume]; s != nil {
@@ -241,10 +243,14 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
// holder only once its restart floor (deadline restart + TTL, set at load)
// plus the skew bound has passed, so no durable horizon is needed. A first grant and an
// expired re-grant after the shared move barrier write synchronously.
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64, proofs ...FormatReadProof) (WorkspaceLease, error) {
if err := ctx.Err(); err != nil {
return WorkspaceLease{}, err
}
var proof FormatReadProof
if len(proofs) > 0 {
proof = proofs[0]
}
p.beforeWorkspaceGrantLock("renewal")
p.leaseMu.Lock()
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
@@ -268,7 +274,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
}
if !lv.d.leasePresent {
unlock() // never re-enter p.mu while holding the leaf
return p.firstWorkspaceGrant(ctx, volume, holder, epoch)
return p.firstWorkspaceGrant(ctx, volume, holder, epoch, proof)
}
if lv.d.revoking { // tell the host to drain; never extend
l := lv.d.lease
@@ -278,7 +284,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
}
if !now.Before(lv.deadline) || (p.formatLevel == 0 && now.UnixNano() >= lv.d.horizon) {
unlock()
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
return p.regrantWorkspaceLease(ctx, volume, holder, epoch, proof)
}
// Where the synchronous write used to refuse (persistWorkspaceLocked):
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
@@ -286,6 +292,13 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
}
// A live deadline does not prove that the caller is the capable process
// checked by finalize: a replacement may already have reported level 0.
// Validate its current report under this leaf lock, without I/O or mu.
if err := p.formatReadProofError(proof, holder, epoch, lv.d.incarnation); err != nil {
unlock()
return WorkspaceLease{}, err
}
if p.formatLevel == 0 {
return p.renewV100Locked(volume, holder, epoch, lv, now) // releases leaseMu
}
@@ -314,7 +327,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// its holder's lease. A host whose first renewal fails does not fence: it has
// no deadline yet and retries. The record's ExpiresAtNS is now+1.5*TTL, the
// form v1.0.x reads; this process's deadline is now+TTL.
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64, proof FormatReadProof) (WorkspaceLease, error) {
p.beforeWorkspaceGrantLock("first grant")
p.mu.Lock()
if p.deleteReserved[volume] {
@@ -326,6 +339,10 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
p.mu.Unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
}
if err := p.formatReadProofError(proof, holder, epoch, line.info.Incarnation); err != nil {
p.mu.Unlock()
return WorkspaceLease{}, err
}
s := cloneWorkspace(p.workspace[volume])
if s == nil {
s = &WorkspaceState{}
@@ -356,7 +373,7 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
// INV-WS-LEASE-REGRANT-001: serialize an expired re-grant with move issue,
// reusing the forced-move barrier so the old process's validity is past.
// The live renewal path releases leaseMu before entering this writer.
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64, proof FormatReadProof) (WorkspaceLease, error) {
p.beforeWorkspaceGrantLock("regrant")
// INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt;
// a returning process can retry after that writer has settled.
@@ -376,6 +393,9 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch {
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
}
if err := p.formatReadProofError(proof, holder, epoch, line.info.Incarnation); err != nil {
return WorkspaceLease{}, err
}
if s.Lease.Revoking || s.Ack != nil || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) {
return WorkspaceLease{}, fmt.Errorf("workspace lease: revocation or move pending")
}
@@ -0,0 +1,140 @@
package master
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
const finalizeSetupCheckpoint = "FINALIZE_SETUP_COMPLETE"
const finalizeFaultCheckpoint = "FINALIZE_POST_RENAME_FAULT"
const finalizeLogCheckpoint = "FINALIZE_LOG_ENTERED"
const finalizeWindowCheckpoint = "FINALIZE_INTENT_AND_GRANTS_CHECKED"
type blockedFinalizeLog struct{ check func() }
func (w blockedFinalizeLog) Write([]byte) (int, error) {
fmt.Fprintln(os.Stderr, finalizeLogCheckpoint)
w.check()
fmt.Fprintln(os.Stderr, finalizeWindowCheckpoint)
select {}
}
func qualifiedFinalizeFailure(out []byte, err, contextErr error, sink string) bool {
var exit *exec.ExitError
if contextErr != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
return false
}
for _, marker := range []string{finalizeSetupCheckpoint, finalizeFaultCheckpoint} {
if strings.Count(string(out), marker) != 1 {
return false
}
}
if sink == "blocked" {
return strings.Count(string(out), finalizeLogCheckpoint) == 1 && strings.Count(string(out), finalizeWindowCheckpoint) == 1
}
return strings.Contains(string(out), "ERROR") && strings.Contains(string(out), "supervisor restarts")
}
func TestFormatFinalizeUncertainWriteFailStops(t *testing.T) {
for _, sink := range []string{"normal", "blocked", "setup-failure", "setup-durability-failure"} {
t.Run(sink, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFormatFinalizeUncertainWriteChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "FINALIZE_FAILURE_CHILD="+sink)
out, err := cmd.CombinedOutput()
qualified := qualifiedFinalizeFailure(out, err, ctx.Err(), sink)
if sink == "setup-failure" || sink == "setup-durability-failure" {
expected := 1
if sink == "setup-durability-failure" {
expected = authority.ExitDurabilityUnknown
}
var exit *exec.ExitError
if qualified || ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != expected || !strings.Contains(string(out), "injected setup") {
t.Fatalf("setup failure was not distinguished: %v ctx=%v\n%s", err, ctx.Err(), out)
}
return
}
if !qualified {
t.Fatalf("fault/checkpoints did not qualify exit %d: %v ctx=%v\n%s", authority.ExitDurabilityUnknown, err, ctx.Err(), out)
}
})
}
}
func finalizeFailureRig(t *testing.T) *isolationRig {
t.Helper()
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatal(err)
}
return r
}
func TestFormatFinalizeUncertainWriteChild(t *testing.T) {
sink := os.Getenv("FINALIZE_FAILURE_CHILD")
if sink == "" {
t.Skip("bounded fault child")
}
if sink == "setup-durability-failure" {
fmt.Fprintln(os.Stderr, "ERROR injected setup durability failure; supervisor restarts")
os.Exit(authority.ExitDurabilityUnknown)
}
if sink == "setup-failure" {
t.Fatal("injected setup failure before checkpoints")
}
r := finalizeFailureRig(t)
fmt.Fprintln(os.Stderr, finalizeSetupCheckpoint)
r.m.log = log.New(os.Stderr, "", 0)
if sink == "blocked" {
r.m.log = log.New(blockedFinalizeLog{check: func() {
if !r.m.formatFinalizing.Load() || r.m.Publisher().FormatLevel() != 0 {
t.Fatal("host intent lost or level raised before recovery")
}
// At level 0, refusal without a report observes the publisher's intent.
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err == nil {
t.Fatal("publisher intent reopened an unreported serving deadline")
}
proof := r.m.formatReadProof("v", "r1", "node-b", 1)
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1, proof); err != nil {
t.Fatalf("capable live renewal blanket-refused while logging blocked: %v", err)
}
}}, "", 0)
}
syncAttestationDir = func(string) error {
onDisk, err := loadStoreAttestations(r.m.cfg.AuthorityStoreDir)
if err != nil || onDisk.level() != 1 {
t.Fatalf("fault did not follow the level-1 rename: %v", err)
}
fmt.Fprintln(os.Stderr, finalizeFaultCheckpoint)
return errors.New("injected post-rename directory barrier failure")
}
_, _, _ = r.m.FinalizeFormat(1)
os.Exit(42)
}
@@ -0,0 +1,191 @@
package master
import (
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func formatReviewLineRig(t *testing.T) *isolationRig {
t.Helper()
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
err = disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1,
EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0],
CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-v"})
if err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
r.createVolume(t, "sibling")
r.place(t, "sibling", "node-b")
r.m.Publisher().FinalizeFormatLevel()
r.m.format.v.Store(1)
return r
}
func TestFormatRefreshUsesItsOwnReportDespiteAnOldSibling(t *testing.T) {
if !finalizeServingChild(t) {
return
}
r := formatReviewLineRig(t)
if err := r.fgProcessHeartbeat("node-b", "old-sibling", "sibling", 0); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-v", "v", 1); err != nil {
t.Fatal(err)
}
line, ok := r.m.Publisher().VolumeAuthorityLine("v")
if !ok {
t.Fatal("missing existing line")
}
ask := authority.AssignmentAsk{VolumeID: "v", ReplicaID: line.ReplicaID,
DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr, Intent: authority.IntentRefreshEndpoint,
Incarnation: "new-v", ExpectCurrent: &authority.ExpectedLine{ReplicaID: line.ReplicaID,
Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}}
called := false
if err := r.m.admitWorkspacePublicationNow(ask, func() error { called = true; return nil }); err != nil || !called {
t.Fatalf("capable existing-holder refresh blocked by sibling: called=%v err=%v", called, err)
}
// A new placement still faces the server-wide known-old gate.
ask.Intent, ask.ExpectCurrent = authority.IntentBind, nil
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Error("new placement admitted"); return nil }); err == nil {
t.Fatal("new placement ignored the old sibling")
}
ask.Intent = authority.IntentRefreshEndpoint
ask.ExpectCurrent = &authority.ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch,
DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
if err := r.fgProcessHeartbeat("node-b", "old-v-replacement", "v", 0); err != nil {
t.Fatal(err)
}
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Error("old refresh admitted"); return nil }); err == nil {
t.Fatal("refresh ignored its own old report")
}
}
// A heal of the current holder and a failover to a replica's committed
// holder give no new placement to their server: an old sibling process there
// does not refuse them; the volume's own old process does.
func TestFormatReassignUsesItsOwnReportDespiteAnOldSibling(t *testing.T) {
if !finalizeServingChild(t) {
return
}
r := formatReviewLineRig(t)
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v", DesiredRF: 2, Candidates: []lifecycle.PlacementCandidate{
{VolumeID: "v", ServerID: "node-b", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica},
{VolumeID: "v", ServerID: "node-c", ReplicaID: "r2", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
for name, ask := range map[string]authority.AssignmentAsk{
"heal": {VolumeID: "v", ReplicaID: "r1", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Intent: authority.IntentReassign},
"failover": {VolumeID: "v", ReplicaID: "r2", DataAddr: hbPorts["node-c"][0], CtrlAddr: hbPorts["node-c"][1], Intent: authority.IntentReassign},
} {
server := map[string]string{"r1": "node-b", "r2": "node-c"}[ask.ReplicaID]
if err := r.fgProcessHeartbeat(server, "old-sibling", "sibling", 0); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat(server, "new-v", "v", 1); err != nil {
t.Fatal(err)
}
if err := r.m.admitWorkspacePublicationNow(ask, func() error { return nil }); err != nil {
t.Fatalf("%s of a capable holder refused by its old sibling: %v", name, err)
}
if err := r.fgProcessHeartbeat(server, "old-v", "v", 0); err != nil {
t.Fatal(err)
}
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Errorf("%s by an old process admitted", name); return nil }); err == nil {
t.Fatalf("%s ignored its own old report", name)
}
}
}
func TestFormatPlacedLineKeepsItsReportWait(t *testing.T) {
if !finalizeServingChild(t) {
return
}
r := formatReviewLineRig(t)
if err := r.fgProcessHeartbeat("node-b", "reported-sibling", "sibling", 1); err != nil {
t.Fatal(err)
}
start := time.Now()
waits := r.m.grantWaits(start)["node-b"]
if len(waits) != 1 || waits[0].volume != "v" {
t.Fatalf("placed unreported holder disappeared from waits: %+v", waits)
}
late := r.m.grantWaits(start.Add(r.m.grantStartupWindow() + time.Second))["node-b"]
if len(late) != 1 || late[0].volume != "v" || !late[0].late {
t.Fatalf("placed holder has no overdue warning: %+v", late)
}
if err := r.fgProcessHeartbeat("node-b", "reported-v", "v", 1); err != nil {
t.Fatal(err)
}
if waits := r.m.grantWaits(start)["node-b"]; len(waits) != 0 {
t.Fatalf("reported holder still waits: %+v", waits)
}
}
//go:noinline
func queuedReviewFinalize(h *Host, result chan<- error) {
_, _, err := h.FinalizeFormat(1)
result <- err
}
func TestQueuedFinalizeDoesNotHoldWorkspaceAdmission(t *testing.T) {
if !finalizeServingChild(t) {
return
}
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
r.m.finalizeMu.Lock() // the serializer the active durable finalize holds
release := sync.OnceFunc(r.m.finalizeMu.Unlock)
t.Cleanup(release)
done := make(chan error, 1)
go queuedReviewFinalize(r.m, done)
for {
stacks := make([]byte, 1<<20)
n := runtime.Stack(stacks, true)
waiting := false
for _, stack := range strings.Split(string(stacks[:n]), "\n\n") {
if strings.Contains(stack, "queuedReviewFinalize") && strings.Contains(stack, "sync.(*Mutex).lockSlow") {
waiting = true
}
}
if waiting {
break
}
select {
case <-r.ctx.Done():
t.Fatal("second finalize never waited on serialization")
default:
runtime.Gosched()
}
}
admitted := make(chan struct{})
go func() { r.m.workspaceMu.Lock(); r.m.workspaceMu.Unlock(); close(admitted) }()
select {
case <-admitted:
case <-r.ctx.Done():
t.Fatal("queued finalize holds workspace admission behind the durable write")
}
release()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-r.ctx.Done():
t.Fatal("queued finalize did not finish")
}
}
@@ -0,0 +1,209 @@
package master
import (
"context"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
)
// A held persistence callback and all Host teardown stay in a bounded child.
func finalizeServingChild(t *testing.T) bool {
t.Helper()
if os.Getenv("FINALIZE_SERVING_CHILD") == t.Name() {
return true
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
cmd.Env = append(os.Environ(), "FINALIZE_SERVING_CHILD="+t.Name())
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bounded finalize child: %v\n%s", err, out)
}
return false
}
func TestFinalizeRequiresTheGrantedHoldersReadReport(t *testing.T) {
if !finalizeServingChild(t) {
return
}
for _, tc := range []struct {
name string
reported bool
level uint32
}{
{"never-reported", false, 0}, {"stale-old", true, 0}, {"stale-capable", true, 1},
} {
t.Run(tc.name, func(t *testing.T) {
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
var now atomic.Int64
now.Store(time.Now().UnixNano())
r.m.reads.now = func() time.Time { return time.Unix(0, now.Load()) }
if tc.reported {
if err := r.fgProcessHeartbeat("node-b", "holder-v", "v", tc.level); err != nil {
t.Fatal(err)
}
}
// This is an actual level-0 grant, not just an unserved placement.
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatal(err)
}
now.Add(int64(time.Hour)) // old report remains tied to the serving volume
response, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if tc.level == 1 {
if err != nil || response.GetFormatLevel() != 1 {
t.Fatalf("reported capable holder: %v %v", response, err)
}
return
}
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(err.Error(), "node-b") || !strings.Contains(err.Error(), "volume v") {
t.Fatalf("serving holder without a level-1 report: response=%v error=%v, want typed refusal naming node-b / volume v", response, err)
}
if r.m.formatLevel() != 0 {
t.Fatal("refused finalize changed the level")
}
if err := r.fgProcessHeartbeat("node-b", "holder-v", "v", 1); err != nil {
t.Fatal(err)
}
if response, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil || response.GetFormatLevel() != 1 {
t.Fatalf("capable holder cannot finalize: %v %v", response, err)
}
})
}
}
func TestFinalizeSerializesTheLevelZeroPublicationBoundary(t *testing.T) {
if !finalizeServingChild(t) {
return
}
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatal(err)
}
r.createVolume(t, "fresh")
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
t.Fatal(err)
}
entered, release := make(chan struct{}), make(chan struct{})
releaseOnce := sync.OnceFunc(func() { close(release) })
previous := syncAttestationDir
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
t.Cleanup(func() { syncAttestationDir = previous })
t.Cleanup(releaseOnce)
finalized := make(chan error, 1)
go func() { _, _, err := r.m.FinalizeFormat(1); finalized <- err }()
select {
case <-entered:
case <-r.ctx.Done():
t.Fatal("finalize never reached its directory barrier")
}
// A valid renewal must complete while the actual durable raise is held.
renewCtx, cancelRenew := context.WithTimeout(r.ctx, time.Second)
_, renewErr := r.ws.RenewWorkspaceLease(renewCtx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"})
cancelRenew()
if renewErr != nil {
t.Fatalf("renewal blocked by durable finalize: %v", renewErr)
}
// The holder restarts on a level-0 binary after the finalize check.
if err := r.fgProcessHeartbeat("node-b", "old-v", "v", 0); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err == nil {
t.Fatal("replacement old process renewed the still-live lease during finalize")
}
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatalf("capable process could not resume memory-only renewal during finalize: %v", err)
}
if err := r.fgProcessHeartbeat("node-b", "old-v", "v", 0); err != nil {
t.Fatal(err)
}
if _, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}); reasonOf(err) != lifecycleclient.ReasonBinaryTooOld {
t.Fatalf("known-old placement bypassed finalize intent: %v", err)
}
preview, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "during-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
if err != nil || preview.GetAdmitted() || preview.GetReasonCode() != lifecycleclient.ReasonBinaryTooOld {
t.Fatalf("old guarded move bypassed finalize intent: %v %v", preview, err)
}
granted := make(chan error, 1)
var published atomic.Bool
go func() {
granted <- r.m.admitWorkspacePublication(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Intent: authority.IntentBind}, func() error { published.Store(true); return nil })
}()
// The intent must reject the old publication before the held write ends.
select {
case err := <-granted:
if err == nil || published.Load() || !strings.Contains(err.Error(), "binary_too_old") {
t.Fatalf("level-0 publication crossed the finalize barrier: published=%v error=%v", published.Load(), err)
}
case <-r.ctx.Done():
t.Fatal("publication waited for the durable write instead of checking the intent")
}
releaseOnce()
select {
case err := <-finalized:
if err != nil {
t.Fatal(err)
}
case <-r.ctx.Done():
t.Fatal("finalize did not finish")
}
// Completing the durable raise keeps the renewal proof gate. Unknown
// move targets remain placeable and still face the ordinary lease barrier.
r.m.reads.forget("node-b")
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err == nil {
t.Fatal("unreported process renewed after finalize completed")
}
preview, err = r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "after-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
if err != nil || !strings.Contains(preview.GetReason(), "lease expiry plus clock-skew") {
t.Fatalf("unreported guarded move did not reach its existing lease barrier: %v %v", preview, err)
}
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
preview, err = r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "after-finalize-capable", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
if err != nil || preview.GetReasonCode() == lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(preview.GetReason(), "lease expiry plus clock-skew") {
t.Fatalf("reported capable guarded move did not reach its existing lease barrier: %v %v", preview, err)
}
}
+139 -46
View File
@@ -4,12 +4,14 @@ import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
@@ -36,9 +38,10 @@ type readsLevels struct {
}
type procLevel struct {
level uint32
process string
seen time.Time
level uint32
process string
seen time.Time
revision *atomic.Uint64
}
func newReadsLevels(window time.Duration) *readsLevels {
@@ -52,13 +55,26 @@ func (r *readsLevels) note(server, volume, process string, level uint32) {
if r.procs[server] == nil {
r.procs[server] = map[string]procLevel{}
}
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now()}
previous, known := r.procs[server][volume]
revision := previous.revision
if revision == nil {
revision = &atomic.Uint64{}
}
if !known || previous.level != level || previous.process != process {
revision.Add(1)
}
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now(), revision: revision}
}
// forget drops every entry of server (a retired host).
func (r *readsLevels) forget(server string) {
r.mu.Lock()
defer r.mu.Unlock()
for _, e := range r.procs[server] {
if e.revision != nil {
e.revision.Add(1)
}
}
delete(r.procs, server)
}
@@ -69,6 +85,9 @@ func (r *readsLevels) liveLocked(server string, served map[string]bool) map[stri
cutoff := r.now().Add(-r.window)
for v, e := range r.procs[server] {
if e.seen.Before(cutoff) && !served[v] {
if e.revision != nil {
e.revision.Add(1)
}
delete(r.procs[server], v)
}
}
@@ -171,12 +190,21 @@ type formatLevelState struct{ v atomic.Uint32 }
// finalizes the v1.1 format.
func (h *Host) formatLevel() uint32 { return h.format.v.Load() }
// Admission follows the target level during the in-flight finalize; replies
// and persisted data still use the durable format level until it commits.
func (h *Host) admissionFormatLevel() uint32 {
if h.formatFinalizing.Load() {
return 1
}
return h.formatLevel()
}
// formatEligible reports whether server may be GRANTED work (an authority
// line published to it, and with it its lease) at the cluster's format
// level: its own report says its binary reads that level; no report means
// no grant (NoStrand holds at the grant). At level 0 every server is.
func (h *Host) formatEligible(server string) bool {
level := h.formatLevel()
level := h.admissionFormatLevel()
if level == 0 {
return true
}
@@ -203,7 +231,7 @@ func (h *Host) grantStartupWindow() time.Duration {
}
// grantWaitEntry is a placed volume whose holder process on a server has
// not reported (no grant before its report) and that has no line yet.
// not reported (no serving grant before its report), even if a line was placed.
type grantWaitEntry struct {
volume string
waited time.Duration
@@ -212,9 +240,10 @@ type grantWaitEntry struct {
// grantWaits computes, once per status snapshot, the complete set of
// (server, volume) grant waits at a level above 0: every placed slot without
// an authority line whose own process on its server has not reported. The
// a report from its own process on its server. A placed line is not a serving grant;
// it waits on the line's owner only (a move leaves the placement). The
// first-seen times are reconciled against that one set: an entry that left
// it (granted, reported, unplaced, removed) is dropped, a new one starts
// it (reported, moved, unplaced, removed) is dropped, a new one starts
// now. The key is server and volume, so waits on different servers never
// reset each other.
func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
@@ -239,17 +268,23 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
if h.formatLevel() > 0 {
window := h.grantStartupWindow()
for _, p := range placements {
if _, granted := h.Publisher().VolumeAuthorityLine(p.VolumeID); granted {
continue
var servers []string
if line, ok := h.Publisher().PublishedAuthorityLine(p.VolumeID); ok {
// A move does not rewrite the placement: a line waits on its owner.
servers = []string{h.workspaceLineOwner(line, p.VolumeID, line.ReplicaID, line.Epoch)}
} else {
for _, slot := range p.Slots {
servers = append(servers, slot.ServerID)
}
}
for _, slot := range p.Slots {
if slot.ServerID == "" {
for _, server := range servers {
if server == "" {
continue
}
if _, reported := h.reads.entry(slot.ServerID, p.VolumeID, h.servedBy(slot.ServerID)); reported {
if _, reported := h.reads.entry(server, p.VolumeID, h.servedBy(server)); reported {
continue
}
key := slot.ServerID + "\x00" + p.VolumeID
key := server + "\x00" + p.VolumeID
live[key] = true
first, seen := h.grantWait[key]
if !seen {
@@ -260,7 +295,7 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
if waited < 0 { // a caller's now taken before another snapshot started this wait
waited = 0
}
out[slot.ServerID] = append(out[slot.ServerID], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window})
out[server] = append(out[server], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window})
}
}
}
@@ -279,9 +314,9 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
// (create, move, restore target, a failover candidate), or "" when it may:
// only a KNOWN-old report refuses. An unknown server is placeable,
// since with one process per volume and create-then-start a placement target
// cannot have reported yet; the grant (formatTooOld) still needs its report.
// cannot have reported yet; a serving deadline still needs its own report.
func (h *Host) placementTooOld(server string) string {
level := h.formatLevel()
level := h.admissionFormatLevel()
if level == 0 {
return ""
}
@@ -304,26 +339,6 @@ func (h *Host) formatRefusal(prefix, server string) error {
return lifecycleclient.WithReason(status.New(codes.FailedPrecondition, prefix+why), lifecycleclient.ReasonBinaryTooOld).Err()
}
// grantTooOld names why the process that will serve volume on server may not
// be granted its line, or "" when it may: the grant reads that process's own
// report (the (server, volume) entry), never a sibling process's, since
// with one process per volume a sibling's report says nothing about this
// one's binary. No report means no grant; a lower one is binary_too_old.
func (h *Host) grantTooOld(server, volume string) string {
level := h.formatLevel()
if level == 0 {
return ""
}
reads, ok := h.reads.entry(server, volume, h.servedBy(server))
if !ok {
return fmt.Sprintf("node %q has not reported the format read level of its process for volume %q; the cluster's format level is %d (no grant before that process's report)", server, volume, level)
}
if reads < level {
return fmt.Sprintf("node %q's process for volume %q reads format level %d; the cluster's format level is %d (binary_too_old)", server, volume, reads, level)
}
return ""
}
// formatTooOld names why server is not format-eligible, or "" when it is.
func (h *Host) formatTooOld(server string) string {
if h.formatEligible(server) {
@@ -432,7 +447,7 @@ func (e errFormatHostsTooOld) Error() string {
for i, b := range e.hosts {
named[i] = fmt.Sprintf("%s (%s)", b.server, b.detail)
}
return fmt.Sprintf("format finalize refused: processes holding volumes report a level below 1: %s; upgrade each one, or move its volumes (sw-block ops workspace move)", strings.Join(named, ", "))
return fmt.Sprintf("format finalize refused: processes holding volumes have not reported reading level 1: %s; have each current process report reading level 1, or move/release its volumes, then retry", strings.Join(named, ", "))
}
// metadata keys each refused host, and each host not confirmed, for the
@@ -474,9 +489,10 @@ func (e errHostHoldsWork) metadata() map[string]string {
}
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
// Finalize; FormatGateMaster: the one durable step). It is refused only while
// a process that holds work reports a lower level (finalizeCheck); the hosts
// it cannot confirm are answered, not blocking. Otherwise, in order: the
// Finalize; FormatGateMaster: the one durable step). The existing known-old
// work check remains; a possibly-serving current lease also needs its own
// level-1 report. An admission intent closes level-0 grants during the store
// write without holding either publisher grant lock. Otherwise, in order: the
// attestation envelope is written durably (the level, and the fence against
// v1.0.x masters, in one write); the publisher switches to level 1 under its
// locks; then the answer. At level 1 it writes nothing (already).
@@ -484,24 +500,72 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel
if level != 1 {
return false, nil, fmt.Errorf("format finalize: level %d; the only level to finalize is 1", level)
}
// Match RetireHost's lock order. Wait for serialization without holding
// workspaceMu, so another finalize cannot block publications over this I/O.
// Release workspaceMu before the store
// write; the intent then makes every serving deadline use the level-1 gate.
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
h.workspaceMu.Lock()
if h.formatLevel() >= 1 {
h.workspaceMu.Unlock()
return true, nil, nil
}
blocking, unconfirmed := h.finalizeCheck(1)
byServer := map[string][]string{}
for _, b := range h.Publisher().BeginFormatFinalize(h.finalizeReadProofs(), len(blocking) == 0) {
byServer[b.Server] = append(byServer[b.Server], b.Detail)
}
servers := make([]string, 0, len(byServer))
for server := range byServer {
servers = append(servers, server)
}
sort.Strings(servers)
for _, server := range servers {
merged := false
for i := range blocking {
if blocking[i].server == server {
blocking[i].detail += "; " + strings.Join(byServer[server], "; ")
merged = true
break
}
}
if !merged {
blocking = append(blocking, hostBelow{server, strings.Join(byServer[server], "; ")})
}
}
sort.Slice(blocking, func(i, j int) bool { return blocking[i].server < blocking[j].server })
if len(blocking) > 0 {
h.workspaceMu.Unlock()
return false, unconfirmed, errFormatHostsTooOld{hosts: blocking, unconfirmed: unconfirmed}
}
h.formatFinalizing.Store(true)
h.workspaceMu.Unlock()
if _, err := h.attest.finalize(); err != nil {
var uncertain *attestationWriteUncertain
if errors.As(err, &uncertain) {
h.failUncertainFormatFinalize(err)
}
h.Publisher().CancelFormatFinalize()
h.formatFinalizing.Store(false)
return false, unconfirmed, fmt.Errorf("format finalize: %w", err)
}
h.Publisher().FinalizeFormatLevel()
h.format.v.Store(1)
h.formatFinalizing.Store(false)
h.log.Printf("blockmaster: cluster format level finalized at 1 (%d hosts unconfirmed, not blocking)", len(unconfirmed))
return false, unconfirmed, nil
}
// failUncertainFormatFinalize never reopens level-0 grants over a file whose
// rename may already have raised the durable level. Arm exit before logging:
// diagnostic delivery is best effort if the sink or its output lock is blocked.
func (h *Host) failUncertainFormatFinalize(err error) {
time.AfterFunc(time.Second, func() { os.Exit(authority.ExitDurabilityUnknown) })
h.log.Printf("ERROR format finalize persistence failure store=%q error=%q; exiting so the supervisor restarts from durable state", h.attest.path, err)
os.Exit(authority.ExitDurabilityUnknown)
}
// RetireHost removes server from the node inventory, so it no longer counts
// for the format finalize or for placement. It is refused while server
// holds a lease or an assignment for any volume (FormatGate r2: a retire
@@ -516,6 +580,8 @@ func (h *Host) RetireHost(server, confirm string) error {
}
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
h.workspaceMu.Lock()
defer h.workspaceMu.Unlock()
if _, ok := h.lifecycle.Nodes.GetNode(server); !ok {
return fmt.Errorf("retire refused: host %q is not registered", server)
}
@@ -570,9 +636,8 @@ func (s *services) FormatLevel(ctx context.Context, _ *control.FormatLevelReques
return &control.FormatLevelResponse{FormatLevel: s.host.formatLevel()}, nil
}
// RetireHost is the RPC of Host.RetireHost. It holds the workspace lock, as
// a placement does, so no placement onto the host lands between its check
// and the removal.
// RetireHost is the RPC of Host.RetireHost. The host method holds the workspace
// lock across its check and removal, after acquiring finalize serialization.
func (s *services) RetireHost(ctx context.Context, req *control.RetireHostRequest) (*control.RetireHostResponse, error) {
if err := ctx.Err(); err != nil {
return nil, err
@@ -582,8 +647,6 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
return nil, workspaceError(err)
}
}
s.host.workspaceMu.Lock()
defer s.host.workspaceMu.Unlock()
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
var holds errHostHoldsWork
var storage errRetireStorage
@@ -597,3 +660,33 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
}
return &control.RetireHostResponse{ServerId: req.GetServerId()}, nil
}
// formatReadProof is captured before the publisher's grant locks. A concurrent
// process/read-level change invalidates it through the atomic revision.
func (h *Host) formatReadProof(volume, replica, server string, epoch uint64) authority.FormatReadProof {
h.reads.mu.Lock()
defer h.reads.mu.Unlock()
entry, ok := h.reads.procs[server][volume]
return authority.FormatReadProof{Server: server, Process: entry.process, Replica: replica, Epoch: epoch, Reads: entry.level, Reported: ok, Revision: entry.revision, Version: formatReportVersion(entry)}
}
func (h *Host) finalizeReadProofs() map[string]authority.FormatReadProof {
out := map[string]authority.FormatReadProof{}
// workspaceMu is held, so placement and line-owner changes cannot race this
// projection. Publisher validates the current line and lease under its locks.
h.reads.mu.Lock()
defer h.reads.mu.Unlock()
for volume, line := range h.Publisher().PublishedAuthorityLines() {
server := h.workspaceLineOwner(line, volume, line.ReplicaID, line.Epoch)
e, ok := h.reads.procs[server][volume]
out[volume] = authority.FormatReadProof{Server: server, Process: e.process, Replica: line.ReplicaID, Epoch: line.Epoch, Reads: e.level, Reported: ok, Revision: e.revision, Version: formatReportVersion(e)}
}
return out
}
func formatReportVersion(e procLevel) uint64 {
if e.revision == nil {
return 0
}
return e.revision.Load()
}
@@ -49,7 +49,7 @@ func binaryTooOld(err error) bool {
// Every binary's heartbeat is taken and its read level recorded, at level 0
// and at level 1 alike (the refusal is at the grant, never at the
// heartbeat); at level 1 a host whose process reads only level 0 is then
// known old, so placement skips it (its grant is refused at the publication
// known old, so placement skips it (publication is refused at the admission
// boundary: TestThePublicationBoundaryRefusesAnAskForAnOldServer).
func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
@@ -69,8 +69,9 @@ func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
}
// At level 1 no new work goes to a host that does not read it: a workspace
// placement and a move onto an old host (or one that never reported) are
// refused; at level 0 they are not refused for the format (FormatGate:
// placement and a move onto a known-old host are
// refused; an unreported target is allowed. At level 0 neither is refused
// for the format (FormatGate:
// Assign, NoStrand).
func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
for _, level := range []uint32{1, 0} {
@@ -93,10 +94,15 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
if level == 0 || !reported {
// level 0, or an unknown (silent) host at level 1: placeable
// (placement refuses only a known-old report; the
// grant needs the holder's report).
if level == 1 && !reported {
// Neither placement nor a move record grants a serving deadline.
// An unreported target may pass this placement check.
if placeErr != nil || (moveErr != nil && strings.Contains(moveErr.Error(), "format")) {
t.Fatalf("silent target: placement=%v move=%v", placeErr, moveErr)
}
return
}
if level == 0 {
if placeErr != nil {
t.Fatalf("%s: placement refused: %v", name, placeErr)
}
@@ -376,24 +382,32 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
}
}
// A finalize whose durable write fails changes no level: the publisher and
// the master stay at 0 (the switch follows the write; FormatGateMaster
// finalize_not_atomic).
// A failure before the rename leaves both levels at 0, reopens admission,
// and permits a later finalize retry once the obstruction is removed.
func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
for _, s := range []string{"node-a", "node-b"} {
if err := r.fgHeartbeat(s, 1); err != nil {
t.Fatal(err)
}
if !finalizeServingChild(t) {
return
}
r := finalizeFailureRig(t)
obstruction := r.m.attest.path + ".tmp"
if err := os.Mkdir(obstruction, 0o700); err != nil {
t.Fatal(err)
}
saved := syncAttestationDir
t.Cleanup(func() { syncAttestationDir = saved })
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); status.Code(err) != codes.Internal {
t.Fatalf("a finalize whose envelope write failed: %v, want Internal (a failure, not a transient answer)", err)
t.Fatalf("pre-rename failure: %v, want Internal", err)
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 || r.m.formatFinalizing.Load() {
t.Fatal("pre-rename failure changed level or left host intent set")
}
// A no-report level-0 deadline proves the publisher intent is clear too.
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err != nil {
t.Fatalf("publisher intent was not cleared after pre-rename failure: %v", err)
}
if err := os.Remove(obstruction); err != nil {
t.Fatal(err)
}
if _, _, err := r.m.FinalizeFormat(1); err != nil || r.m.formatLevel() != 1 || r.m.Publisher().FormatLevel() != 1 || r.m.formatFinalizing.Load() {
t.Fatalf("finalize could not retry after removing obstruction: %v", err)
}
}
@@ -516,8 +530,7 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
for _, tc := range []struct {
name string
old, silent bool
}{{"old-process", true, false}, {"silent (no report: no grant)", false, true}, {"control", false, false}} {
old := tc.old || tc.silent
}{{"old-process", true, false}, {"silent (placement only)", false, true}, {"control", false, false}} {
t.Run(tc.name, func(t *testing.T) {
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
r.createVolume(t, "v")
@@ -538,10 +551,7 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
if tc.old && (err == nil || published || !strings.Contains(err.Error(), "binary_too_old")) {
t.Fatalf("level 1, node-b's process reads 0: err %v, published %v; want refused before the publish", err, published)
}
if tc.silent && (err == nil || published || !strings.Contains(err.Error(), "has not reported")) {
t.Fatalf("level 1, node-b never reported: err %v, published %v; want no grant (refused before the publish)", err, published)
}
if !old && (err != nil || !published) {
if !tc.old && (err != nil || !published) {
t.Fatalf("control: err %v, published %v; want published", err, published)
}
})
@@ -576,8 +586,8 @@ func TestEveryVolumeOfAHeartbeatKeepsItsLevel(t *testing.T) {
t.Fatal(err)
}
r.m.format.v.Store(1)
if why := r.m.grantTooOld("node-b", "vb"); !strings.Contains(why, "binary_too_old") {
t.Fatalf("level 1: the grant for vb, held by the silent old process: %q, want binary_too_old", why)
if proof := r.m.formatReadProof("vb", "r-b", "node-b", 1); !proof.Reported || proof.Reads != 0 || proof.Process != "old-proc" {
t.Fatalf("the grant proof lost vb's own stale old report: %+v", proof)
}
r.m.format.v.Store(0)
resp, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
@@ -841,7 +851,7 @@ func upgradedStoreDir(t *testing.T) string {
// two servers report the same volume and replica at different endpoints, one
// process reading level 1 and one reading level 0; the ask at the first's
// endpoints is published, the ask at the second's is refused binary_too_old,
// and an ask at endpoints nobody reports is not granted (no report).
// and an ask at unreported endpoints may publish, but grants no deadline.
func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if r.m.formatLevel() != 1 {
@@ -865,8 +875,8 @@ func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) {
if published, err := grant("127.0.0.1:19601", "127.0.0.1:19602"); err == nil || published || !strings.Contains(err.Error(), "binary_too_old") {
t.Fatalf("the ask at node-c's endpoints (its process reads 0): err %v, published %v; want refused binary_too_old", err, published)
}
if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err == nil || published || !strings.Contains(err.Error(), "has not reported") {
t.Fatalf("the ask at endpoints no server reports: err %v, published %v; want no grant", err, published)
if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err != nil || !published {
t.Fatalf("the ask at unreported endpoints: err %v, published %v; want placement accepted", err, published)
}
if published, err := grant("127.0.0.1:19501", "127.0.0.1:19502"); err != nil || !published {
t.Fatalf("the ask at node-b's endpoints (its process reads 1): err %v, published %v; want granted", err, published)
@@ -0,0 +1,119 @@
package master
import (
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/types/known/timestamppb"
)
// fgV100Heartbeat sends a heartbeat shaped as a v1.0 holder sends it: a slot
// with no incarnation and no reads level.
func (r *isolationRig) fgV100Heartbeat(server, vol string) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
return err
}
// v100IdentityRig is a level-1 cluster whose volume v is held on node-b by a
// capable process (its own report reads 1) with a live lease.
func v100IdentityRig(t *testing.T) *isolationRig {
t.Helper()
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatal(err)
}
return r
}
// Identity check (2) of the v1.1.2 bound: a v1.0-shaped heartbeat from a new
// process on the holder's server supersedes the cached report of the capable
// predecessor (as unreported or level 0), so that process's renewals are
// refused at level 1 and during the finalize intent; it never renews on its
// predecessor's proof. The capable process's next report renews again (twin).
func TestAV100HeartbeatSupersedesTheCachedReportSoItsRenewalsAreRefused(t *testing.T) {
if !finalizeServingChild(t) {
return
}
for _, phase := range []string{"level-1", "finalize-intent"} {
t.Run(phase, func(t *testing.T) {
r := v100IdentityRig(t)
renew := func() error {
_, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"})
return err
}
switch phase {
case "level-1":
if _, _, err := r.m.FinalizeFormat(1); err != nil || r.m.formatLevel() != 1 {
t.Fatalf("finalize: level %d, %v", r.m.formatLevel(), err)
}
case "finalize-intent":
// A real finalize, held at its durable barrier: the intent is
// open (the publisher's own flag set by BeginFormatFinalize),
// the level still 0 on disk.
entered, release := make(chan struct{}), make(chan struct{})
releaseOnce := sync.OnceFunc(func() { close(release) })
previous := syncAttestationDir
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
t.Cleanup(func() { syncAttestationDir = previous })
finalized := make(chan error, 1)
go func() { _, _, err := r.m.FinalizeFormat(1); finalized <- err }()
t.Cleanup(func() {
releaseOnce()
select {
case <-finalized:
case <-time.After(10 * time.Second):
t.Error("finalize did not finish")
}
})
select {
case <-entered:
case <-r.ctx.Done():
t.Fatal("finalize never reached its durable barrier")
}
if r.m.formatLevel() != 0 || !r.m.formatFinalizing.Load() {
t.Fatalf("not in the intent: level %d finalizing %v", r.m.formatLevel(), r.m.formatFinalizing.Load())
}
}
if err := renew(); err != nil {
t.Fatalf("the capable holder could not renew: %v", err)
}
// A replacement process on a v1.0 binary reports before renewing.
if err := r.fgV100Heartbeat("node-b", "v"); err != nil {
t.Fatal(err)
}
if reads, reported := r.m.reads.entry("node-b", "v", r.m.servedBy("node-b")); reported && reads >= 1 {
t.Fatalf("the v1.0-shaped heartbeat left the predecessor's report (reads %d) for the volume", reads)
}
if err := renew(); err == nil {
t.Fatal("a v1.0 replacement renewed on its predecessor's proof")
}
// Twin: the capable process reports again and renews.
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if err := renew(); err != nil {
t.Fatalf("the capable process could not renew after reporting again: %v", err)
}
})
}
}
@@ -72,8 +72,8 @@ func TestANewClusterStartsAtTheCurrentFormatLevel(t *testing.T) {
// On a new cluster (level 1) a node that has not reported is placeable (one
// process per volume, created then started, cannot have reported at its
// placement) and shows as awaiting report; it is not granted until its own
// report: the publication of its line is refused and its publish never runs;
// after its first heartbeat (reads level 1) the line is published and the
// report: publication alone grants no serving deadline; after its own first
// heartbeat (reads level 1), its lease renewal grants a deadline and the
// condition is gone.
func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
@@ -109,14 +109,22 @@ func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T)
func() error { published = true; return nil })
return published, err
}
if published, err := grant(); err == nil || published {
t.Fatalf("the grant before node-b's report: err %v, published %v; want no grant", err, published)
if published, err := grant(); err != nil || !published {
t.Fatalf("publication before node-b's report: err %v, published %v; want placed", err, published)
}
if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "fresh", ReplicaID: "r1", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322", Intent: authority.IntentBind}); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, r.m.Publisher(), "fresh")
id := &control.WorkspaceIdentity{VolumeId: "fresh", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil {
t.Fatal("unreported process obtained its first serving deadline")
}
if err := r.fgProcessHeartbeat("node-b", "proc-b", "fresh", 1); err != nil {
t.Fatal(err)
}
if published, err := grant(); err != nil || !published {
t.Fatalf("the grant after node-b's report: err %v, published %v; want granted", err, published)
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("first deadline after node-b's report: %v", err)
}
if awaiting() {
t.Fatal("node-b still shows awaiting report after its first heartbeat")
@@ -175,7 +183,7 @@ func TestAnEmptyAuthorityStoreOverAnExistingInventoryStartsAtLevel0(t *testing.T
// The grant reads the holder's own report: on a server whose process for
// volume u reported level 1, a new process for volume v that has not
// reported yet is not granted v's line; once v's own process reports level
// reported yet receives no serving deadline; once v's own process reports level
// 1 it is (a sibling's report says nothing about this process's binary).
func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
@@ -192,14 +200,22 @@ func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) {
func() error { published = true; return nil })
return published, err
}
if published, err := grant(); err == nil || published {
t.Fatalf("v's grant on u's report only: err %v, published %v; want no grant", err, published)
if published, err := grant(); err != nil || !published {
t.Fatalf("v's placement on an unreported process: err %v, published %v", err, published)
}
if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: "127.0.0.1:19331", CtrlAddr: "127.0.0.1:19332", Intent: authority.IntentBind}); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, r.m.Publisher(), "v")
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil {
t.Fatal("v's first deadline used u's report")
}
if err := r.fgProcessHeartbeat("node-b", "proc-v", "v", 1); err != nil {
t.Fatal(err)
}
if published, err := grant(); err != nil || !published {
t.Fatalf("v's grant after v's own report: err %v, published %v; want granted", err, published)
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("v's first deadline after its own report: %v", err)
}
}
@@ -298,6 +314,40 @@ func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) {
}
}
// A move does not rewrite the placement: the moved line waits on its new
// holder until that process reports, and the former host's slot never waits
// once its report for the volume expired.
func TestAMovedLineWaitsOnItsNewHolderOnly(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.issueMove(t, "v", "m1")
r.m.reads.forget("node-b")
r.m.format.v.Store(1)
now := time.Now().Add(r.m.reads.window + time.Second)
r.m.reads.now = func() time.Time { return now }
if _, ok := r.m.reads.entry("node-a", "v", r.m.servedBy("node-a")); ok {
t.Fatal("fixture: node-a's report for the moved volume is still live")
}
late := now.Add(r.m.grantStartupWindow() + time.Second)
waiting := func(at time.Time, server string) bool {
for _, w := range r.m.grantWaits(at)[server] {
if w.volume == "v" {
return true
}
}
return false
}
if waiting(now, "node-a") || waiting(late, "node-a") {
t.Fatal("the former host waits for the moved volume's report")
}
if !waiting(now, "node-b") {
t.Fatal("the moved line's unreported holder shows no wait")
}
r.m.reads.note("node-b", "v", "proc-v", 1)
if waiting(late, "node-a") || waiting(late, "node-b") {
t.Fatal("a wait outlived the new holder's report")
}
}
// A status snapshot that read the placements before a newer one never
// reconciles after it: snapshot A holds its read (no placement yet) while
// vb is placed on an unreported node and snapshot B is started; B must wait
@@ -0,0 +1,117 @@
package master
import (
"context"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/host/volume"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// The move's stored lease is a reservation, not the target's permission to
// serve. Only an accepted renewal reply can open the production lease guard.
func TestFormatMoveRecordCannotServeBeforeReportedRenewal(t *testing.T) {
if !finalizeServingChild(t) {
return
}
for _, phase := range []string{"intent", "committed"} {
t.Run(phase, func(t *testing.T) { formatMoveRecordCannotServe(t, phase) })
}
}
func formatMoveRecordCannotServe(t *testing.T, phase string) {
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
r.createVolume(t, "moved")
r.place(t, "moved", "node-a")
if err := ingestV11(r.m, authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(),
Slots: []authority.SlotFact{{VolumeID: "moved", ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil {
t.Fatal(err)
}
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
waitAuthorityLine(t, r.m.Publisher(), "moved")
source := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "moved", ReplicaId: "r1", Epoch: 1}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, source); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RevokeWorkspace(r.ctx, source); err != nil {
t.Fatal(err)
}
if _, err := r.ws.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: source, HeadGen: 9}); err != nil {
t.Fatal(err)
}
entered, release := make(chan struct{}), make(chan struct{})
releaseOnce := sync.OnceFunc(func() { close(release) })
previous := syncAttestationDir
if phase == "intent" {
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
t.Cleanup(func() { syncAttestationDir = previous })
}
finished := make(chan error, 1)
go func() { _, _, err := r.m.FinalizeFormat(1); finished <- err }()
joined := false
t.Cleanup(func() {
releaseOnce()
if !joined {
<-finished // the entire scenario is isolated in a bounded child
}
})
if phase == "intent" {
select {
case <-entered:
case <-r.ctx.Done():
t.Fatal("finalize did not reach the held write")
}
} else {
if err := <-finished; err != nil {
t.Fatal(err)
}
joined = true
}
// This target has never reported. Publication/move is Place, not a
// serving deadline; both the intent and level 1 must allow the move.
moved, err := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "lease-record-only", VolumeId: "moved", ExpectedReplicaId: "r1", ExpectedEpoch: 1,
TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
if err != nil || !moved.GetIssued() {
t.Fatalf("unreported target move refused during %s: %v %v", phase, moved, err)
}
ws, err := r.ws.QueryWorkspace(r.ctx, &control.WorkspaceVolume{VolumeId: "moved"})
if err != nil || ws.GetLease().GetEpoch() != moved.GetNewEpoch() || ws.GetLease().GetExpiresAtNs() <= time.Now().UnixNano() {
t.Fatalf("move did not issue a possibly-live lease record: %v %v", ws, err)
}
// The issued move and its positive lease record exist, but no renewal
// reply has reached the guard, and the target still has no report.
id := &control.WorkspaceIdentity{VolumeId: "moved", ReplicaId: "r1", ServerId: "node-b", Epoch: moved.GetNewEpoch()}
guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "moved", ReplicaID: "r1", Epoch: moved.GetNewEpoch(), Healthy: true}}, r.ws, id,
func(context.Context) (uint64, error) {
t.Fatal("a refused first renewal must not drain an ungranted guard")
return 0, nil
}, time.Now)
if err != nil {
t.Fatal(err)
}
if guard.Held() || guard.Projection().Healthy {
t.Fatal("issued move record opened serving before a renewal reply")
}
if err := guard.Refresh(r.ctx); err == nil || guard.Held() || guard.Projection().Healthy {
t.Fatalf("unreported target obtained serving from the issued record: %v", err)
}
if err := r.fgProcessHeartbeat("node-b", "", "moved", 1); err != nil {
t.Fatal(err)
}
if err := guard.Refresh(r.ctx); err != nil || !guard.Held() || !guard.Projection().Healthy {
t.Fatalf("reported target did not serve after an accepted renewal: %v", err)
}
releaseOnce()
if !joined {
if err := <-finished; err != nil {
t.Fatal(err)
}
joined = true
}
}
@@ -1,72 +0,0 @@
package master
import (
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// bindingFailingProbe is switchProbe whose fencing round first makes the
// master's workspace binding store fail a write (its file replaced by a
// directory, so the write's rename fails), which latches the store
// uncertain: every later read answers restart-required. It does this once.
type bindingFailingProbe struct {
*switchProbe
once sync.Once
fault func()
}
func (p *bindingFailingProbe) FencePromotionCandidates(volume string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
p.once.Do(p.fault)
return p.switchProbe.FencePromotionCandidates(volume, current, survivors)
}
// A binding store that turns uncertain while the gate probes (the probe runs
// without the workspace lock) makes the tick's post-probe binding read fail.
// The tick returns the error and its replace decision is reported as not
// submitted, with the error, instead of vanishing with the tick.
func TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted(t *testing.T) {
buf := &lockedBuffer{}
dir := t.TempDir()
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0), LifecycleStoreDir: dir})
defer closeTestMaster(t, h)
base, ok := h.promotionProber.(*switchProbe)
if !ok {
t.Fatalf("fixture: the master's prober is %T, want *switchProbe", h.promotionProber)
}
var faultErr error
h.SetPromotionEvidenceProvider(&bindingFailingProbe{switchProbe: base, fault: func() {
file := filepath.Join(dir, "workspace-bindings", "bindings.json")
if err := os.RemoveAll(file); err != nil {
faultErr = err
return
}
if err := os.MkdirAll(file, 0o755); err != nil {
faultErr = err
return
}
if err := h.lifecycle.WorkspaceBindings.Retire("vol-other", "node-x", 1); err == nil {
faultErr = os.ErrInvalid // the write was expected to fail
}
}})
ineligible := restarting
ineligible.eligible = false
ingestRF3Incarnations(t, h, ineligible, readySlot("r2-a"), readySlot("r3-a"))
_, err := h.RunLifecycleProductTick()
if faultErr != nil {
t.Fatalf("fixture: the binding store did not fail its write: %v", faultErr)
}
if err == nil || !strings.Contains(err.Error(), "restart required") {
t.Fatalf("tick error %v, want the binding store's restart-required error", err)
}
pattern := `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) not submitted: the workspace bindings could not be read after the probe: .*restart required`
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
@@ -1,150 +0,0 @@
package master
import (
"log"
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// A replace decision of the promotion gate is followed, on the master's
// log, by what became of it: the ask the controller enqueued, why it
// enqueued none, or that it was not submitted. A replace the controller
// does not act on is otherwise silent until the volume fails to fail over.
func TestAReplaceDecisionLogsWhatTheControllerDidWithIt(t *testing.T) {
// The gate's replace of the lost r1, fed to a controller bound to r1@1.
replaced := func(t *testing.T) (*Host, *lockedBuffer, *authority.TopologyController, authority.ClusterSnapshot) {
t.Helper()
ctrl, pub, stop := lossCluster(t, authority.TopologyControllerConfig{})
stop() // the enqueued ask stays queued: the outcome is the controller's alone
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
snap := lossTicks(h)
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
return h, buf, ctrl, snap
}
submit := func(t *testing.T, h *Host, ctrl *authority.TopologyController, snap authority.ClusterSnapshot) {
t.Helper()
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
want := func(t *testing.T, buf *lockedBuffer, pattern string) {
t.Helper()
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
t.Run("enqueued", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
want(t, buf, `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
})
t.Run("the same decision again: already desired", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.noteGateReplace("vol-rf3", "replace(fenced_at=2)") // the next tick decides the same
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: already desired since \S+: Reassign r[23] \(failover\)`)
})
t.Run("not acted on: says why", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
for i := range snap.Volumes[0].Slots {
snap.Volumes[0].Slots[i].PromotionEvidence = adapter.PrimaryEvidence{}
}
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: no ask: failover target r[23] has no promotion evidence`)
})
t.Run("not submitted", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
want(t, buf, `decision=replace\(fenced_at=2\) not submitted: the placements changed during the probe`)
})
t.Run("an intake after the submission does not change its report", func(t *testing.T) {
// The background observation host shares the controller: its intake
// may land between the tick's submit and the report.
h, buf, ctrl, snap := replaced(t)
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
stale := snap
stale.Volumes = append([]authority.VolumeTopologySnapshot(nil), snap.Volumes...)
stale.Volumes[0].Authority.Epoch++ // a basis the publisher does not hold
if err := ctrl.SubmitClusterSnapshot(stale); err != nil {
t.Fatal(err)
}
if o := ctrl.LastOutcome("vol-rf3"); !strings.HasPrefix(o, "no ask: stale snapshot basis") {
t.Fatalf("fixture: the intervening intake did not record its own outcome: %q", o)
}
h.reportReplaces("", nil, outcomes)
want(t, buf, `decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
if strings.Contains(buf.String(), "decision=replace(fenced_at=2) controller: no ask: stale") {
t.Fatalf("the report took the later intake's outcome:\n%s", buf.String())
}
})
t.Run("a submission that did not carry the volume", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("", nil, map[string]string{})
want(t, buf, `decision=replace\(fenced_at=2\) controller: no outcome \(the submission did not carry the volume\)`)
})
t.Run("one report per decision", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.reportReplaces("", nil, nil) // nothing decided since: nothing to report
if n := strings.Count(buf.String(), "decision=replace(fenced_at=2) controller:"); n != 1 {
t.Fatalf("%d reports of one decision:\n%s", n, buf.String())
}
})
}
// The same through the production tick on the supported gate: an
// established volume whose primary turns ineligible is replaced by a fencing
// round; the gate's replace is reported with the controller's enqueued
// failover, and the publication is logged. The publication line comes from
// the publisher's observer after the line is visible, so it is waited for
// (bounded); the two lines are not ordered against each other.
func TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication(t *testing.T) {
buf := &lockedBuffer{}
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0)})
defer closeTestMaster(t, h)
ineligible := restarting
ineligible.eligible = false
supportedCreatingTick(t, h, ineligible)
expectFailoverToR2(t, h, "fenced survivors")
for _, pattern := range []string{
`promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r2 \(failover\)`,
`blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 \(Reassign\)`,
} {
waitLogLine(t, buf, pattern, 5*time.Second)
}
}
// waitLogLine waits up to limit for a line of buf matching pattern.
func waitLogLine(t *testing.T, buf *lockedBuffer, pattern string, limit time.Duration) {
t.Helper()
re := regexp.MustCompile(pattern)
for end := time.Now().Add(limit); !re.MatchString(buf.String()); time.Sleep(10 * time.Millisecond) {
if time.Now().After(end) {
t.Fatalf("no log line matching %q within %v:\n%s", pattern, limit, buf.String())
}
}
}
// Every publication is on the master's log, with or without an event log.
func TestAPublicationIsLogged(t *testing.T) {
h, buf := lossMaster(t, &fenceProbe{})
h.recordAuthorityPublishedEvent(authority.PublishEvent{
Info: adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1},
Ask: authority.AssignmentAsk{VolumeID: "vol-rf3", ReplicaID: "r2", Intent: authority.IntentReassign},
})
if !strings.Contains(buf.String(), "blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 (Reassign)") {
t.Fatalf("publication not logged:\n%s", buf.String())
}
}
@@ -1,60 +0,0 @@
package master
import (
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
)
// A fenced replace decided by the gate reaches the controller as a failover
// whatever the gate's reason. Here the gate replaces a primary only it reads
// as unacceptable: its node reads format level 0 on a level-1 cluster (not
// placement-eligible), while the primary's own slot flags still read
// reachable and ready, and it still reports (no loss is recorded). The
// controller judges acceptability by those flags alone, so unless the gate
// marks the replaced primary unacceptable in what it submits, the controller
// answers "the current primary is acceptable" on every tick and the fenced
// decision never publishes.
func TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign(t *testing.T) {
ctrl, pub, _ := lossCluster(t, authority.TopologyControllerConfig{})
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
h.boot = &bootstrap.DurableAuthorityBootstrap{Publisher: pub}
h.reads = newReadsLevels(time.Hour)
h.reads.note("s1", "vol-rf3", "p-r1", 0) // the primary's node reads the old level
h.reads.note("s2", "vol-rf3", "p-r2", 1)
h.reads.note("s3", "vol-rf3", "p-r3", 1)
h.format.v.Store(1)
t0 := time.Date(2026, 12, 5, 8, 0, 0, 0, time.UTC)
for tick := range 3 {
now := t0.Add(time.Duration(tick) * time.Second)
snap := silentPrimary() // r1's flags read reachable and ready
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
if snap.Volumes[0].Authority.Epoch != 1 {
break // published
}
heard := map[string]time.Time{"r1": now, "r2": now, "r3": now} // r1 still reports: no loss
h.notePrimaryLosses(rx(heard, now), &snap)
h.takeGateReplaces()
h.applyPromotionEvidenceGate(&snap)
if l := gateLine(t, buf.String(), "vol-rf3"); !regexp.MustCompile(`primary_lost=false decision=replace\(fenced_at=2\)$`).MatchString(l) {
t.Fatalf("tick %d: gate line %q; want a fenced replace with no loss recorded", tick, l)
}
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
if strings.Contains(buf.String(), "controller: no ask: the current primary is acceptable") {
t.Fatalf("the controller kept a primary the gate replaced:\n%s", buf.String())
}
if !regexp.MustCompile(`decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`).MatchString(buf.String()) {
t.Fatalf("the fenced replace was not enqueued as a failover:\n%s", buf.String())
}
waitLossLine(t, pub, "vol-rf3", func(l authority.AuthorityBasis) bool { return l.Epoch == 2 && l.ReplicaID != "r1" })
}
@@ -276,8 +276,8 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := s.finalize(); err == nil || s.level() != 0 {
t.Fatalf("a failed directory fsync of the finalize's envelope: err=%v level=%d (want an error, level 0)", err, s.level())
if _, err := s.finalize(); err == nil || s.level() != 1 {
t.Fatalf("a failed directory fsync keeps the possibly-written envelope selected until fail-stop: err=%v level=%d", err, s.level())
}
// The process restarts: the envelope is on disk (the rename happened).
s, err = loadStoreAttestations(dir)
+3 -2
View File
@@ -152,9 +152,8 @@ type Host struct {
attest *storeAttestations // primaries' attested write-ACK stores
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
log *log.Logger
gateNoteMu sync.Mutex // guards gateNoteLast and gateReplaces
gateNoteMu sync.Mutex // guards gateNoteLast
gateNoteLast map[string]string // per kind, the last skip or drop a product-loop tick logged (noteGate)
gateReplaces []gateReplace // this tick's replace decisions, reported after the submit (reportReplaces)
primaryLossMu sync.Mutex // guards primaryLoss
primaryLoss primaryLosses // per volume, the recorded loss of the current primary (primary_loss.go)
boot *bootstrap.DurableAuthorityBootstrap
@@ -170,6 +169,7 @@ type Host struct {
grantWaitMu sync.Mutex // one status snapshot reads and reconciles the grant waits at a time
grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits)
format formatLevelState // the cluster's format level (format_gate.go)
formatFinalizing atomic.Bool // admission intent while durable format raise is in flight
finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go)
// testGrantWaitsRead, when a test sets it, runs after a status snapshot
// has read its placements, still holding grantWaitMu.
@@ -321,6 +321,7 @@ func New(cfg Config) (*Host, error) {
return nil, fmt.Errorf("master.New: Bootstrap: %w", err)
}
holder.set(boot.Publisher)
boot.Publisher.RequireFormatReadProofs()
// Bootstrap creates a fresh store directory: sample its file system only
// now, or a first start would compare against an unknown device forever.
// An unknown identity (stat error, unsupported platform) never matches.
@@ -52,6 +52,7 @@ func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.
}
q := &control.WorkspaceMove{RequestId: requestID, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}
r.m.reads.note("node-b", vol, "", 1) // the move target reports before its grant
grant, err := r.ws.MoveWorkspace(r.ctx, q)
if err != nil {
t.Fatal(err)
@@ -6,7 +6,6 @@ import (
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -16,11 +15,11 @@ func lifecycleFailStop(logger *log.Logger) lifecycle.PersistenceFailureHandler {
once.Do(func() {
// Arm termination before touching the logger: its writer or output
// mutex may be blocked. ERROR delivery is best effort in that case.
time.AfterFunc(time.Second, func() { os.Exit(authority.ExitDurabilityUnknown) })
logger.Printf("ERROR reason=lifecycle_persist_failed lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
time.AfterFunc(time.Second, func() { os.Exit(1) })
logger.Printf("ERROR lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
// A graceful close can wait on the writer that discovered the error.
// The supervisor restarts; Open establishes the recovery barriers.
os.Exit(authority.ExitDurabilityUnknown)
os.Exit(1)
})
}
}
@@ -20,7 +20,6 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
@@ -34,15 +33,15 @@ func TestLifecyclePersistenceFailureStopsTheProcess(t *testing.T) {
cmd.Env = append(os.Environ(), "LIFECYCLE_EXIT_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("master failed to exit74: %v context=%v\n%s", err, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master failed to exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
text := string(out)
record := "new.json"
if kind == "volumes" {
record = "kept.json"
}
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
t.Fatalf("missing single record/store/error line: %s", text)
}
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceRecoveryChild$", "-test.timeout=8s")
@@ -135,8 +134,8 @@ func TestLifecycleFailStopExitsWithBlockedLogger(t *testing.T) {
out, err := cmd.CombinedOutput()
exited := time.Now()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("blocked logger prevented own exit74: %v context=%v\n%s", err, ctx.Err(), out)
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("blocked logger prevented own exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
var triggered int64
for _, line := range strings.Split(string(out), "\n") {
@@ -31,7 +31,7 @@ func TestObservationReportsACleanlyStoppedVolumeStopped(t *testing.T) {
h, c, ctx := reviewBindingHost(t)
reviewLegacyBind(t, h, c, ctx, "vs")
p := h.Publisher()
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1); err != nil {
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1, h.formatReadProof("vs", "r1", "node-a", 1)); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "vs", "r1", 1); err != nil {
@@ -58,6 +58,7 @@ func TestObservationReportsACleanlyStoppedVolumeStopped(t *testing.T) {
if err := h.lifecycle.WorkspaceBindings.Register(target); err != nil {
t.Fatal(err)
}
h.reads.note("node-b", "vs", "", 1) // capable target process, before move grant
moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "move-1", VolumeID: "vs", ExpectedReplicaID: "r1", ExpectedHost: "node-a", ExpectedEpoch: 1, TargetReplicaID: "r1", TargetHost: target.ServerID, TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"}, head)
if err != nil || !moved.Issued {
t.Fatalf("move: %+v %v", moved, err)
@@ -79,7 +80,7 @@ func TestObservationDeletionOutranksStoppedAndRetiredTopology(t *testing.T) {
})
reviewLegacyBind(t, h, c, ctx, "vs")
p := h.Publisher()
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1); err != nil {
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1, h.formatReadProof("vs", "r1", "node-a", 1)); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "vs", "r1", 1); err != nil {
+7 -72
View File
@@ -263,7 +263,6 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
receipts := h.obs.Store().Snapshot()
build := authority.BuildSnapshot(receipts, topology, h.Publisher())
h.notePrimaryLosses(receipts, &build.Snapshot)
h.takeGateReplaces() // only this tick's decisions are reported
probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot)
supported := supportedSnapshotVolumes(build.Snapshot)
unsupportedProbeCount, unsupportedBlockedCount, unsupportedDirectAsks := h.applyUnsupportedPromotionEvidenceGate(placements, build.Report, supported)
@@ -276,16 +275,13 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
defer h.workspaceMu.Unlock()
if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) {
h.noteGate(gateNoteTick, "decisions not submitted: the placements changed during the probe")
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
for _, p := range placements {
if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil {
h.reportReplaces("not submitted: the workspace bindings could not be read after the probe: "+err.Error(), nil, nil)
return false, probeCount, blockedCount, nil, err
} else if bound {
h.noteGate(gateNoteTick, "decisions not submitted: volume "+p.VolumeID+" got a workspace binding during the probe")
h.reportReplaces("not submitted: volume "+p.VolumeID+" got a workspace binding during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
@@ -293,58 +289,12 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
for _, slot := range v.Slots {
if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil {
h.noteGate(gateNoteTick, fmt.Sprintf("decisions not submitted: volume %s replica %s endpoints are bound elsewhere: %v", v.VolumeID, slot.ReplicaID, err))
h.reportReplaces(fmt.Sprintf("not submitted: volume %s replica %s endpoints are bound elsewhere", v.VolumeID, slot.ReplicaID), nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
}
h.noteGate(gateNoteTick, "")
// The outcomes are this submission's own, read under the controller's
// lock: the background observation host may submit right after it.
outcomes, err := h.ctrl.SubmitObservedStateOutcomes(build.Snapshot, build.Report)
h.reportReplaces("", err, outcomes)
return true, probeCount, blockedCount, directAsks, err
}
// gateReplace is one replace decision of a tick's promotion gate.
type gateReplace struct{ volumeID, decision string }
func (h *Host) noteGateReplace(volumeID, decision string) {
h.gateNoteMu.Lock()
h.gateReplaces = append(h.gateReplaces, gateReplace{volumeID, decision})
h.gateNoteMu.Unlock()
}
func (h *Host) takeGateReplaces() []gateReplace {
h.gateNoteMu.Lock()
defer h.gateNoteMu.Unlock()
out := h.gateReplaces
h.gateReplaces = nil
return out
}
// reportReplaces logs what became of each replace decision of this tick:
// not submitted (notSubmitted says why), a failed submit, or what the
// controller did with the volume (an enqueued ask, or why none). A decision
// the controller does not act on is otherwise silent until the volume is
// seen not to fail over.
func (h *Host) reportReplaces(notSubmitted string, submitErr error, outcomes map[string]string) {
for _, d := range h.takeGateReplaces() {
outcome := ""
switch {
case notSubmitted != "":
outcome = notSubmitted
case submitErr != nil:
outcome = "submit failed: " + submitErr.Error()
default:
if o, ok := outcomes[d.volumeID]; ok {
outcome = "controller: " + o
} else {
outcome = "controller: no outcome (the submission did not carry the volume)"
}
}
h.log.Printf("blockmaster: promotion gate volume=%s decision=%s %s", d.volumeID, d.decision, outcome)
}
return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report)
}
func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) {
@@ -426,7 +376,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
// decision names, on the gate's line, the branch this tick took, so a
// volume that keeps a lost primary says why.
decision := ""
replaceDecided := false // the gate decided to replace the primary (reported after the submit)
switch {
case !replaceWanted:
decision = "keep_current(" + gateAcceptance(vol.Slots[currentIdx], serverIndex, h.placementEligible(vol.Slots[currentIdx].ServerID)) + ")"
@@ -453,7 +402,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
} else if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
fencedReplace = len(allowed) > 0
replaceDecided = true
decision = fmt.Sprintf("replace(fenced_at=%d)", vol.Authority.Epoch+1)
if len(allowed) == 0 {
decision = "replace(fencing_round_published_nothing)"
@@ -469,12 +417,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
}
}
if decision == "" && replacing {
replaceDecided = true
decision = "replace(no_candidate_to_fence)"
}
if replaceDecided {
h.noteGateReplace(vol.VolumeID, decision)
}
if ok {
h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v primary_lost=%t decision=%s",
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed, lost, decision)
@@ -500,15 +444,12 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
slot.PlannedMoveAllowed = false
}
}
// A fenced replacement reaches the controller as a failover,
// whatever the gate's reason (a recorded loss, or a primary only
// the gate reads as unacceptable, such as one on a node below the
// cluster's format level): its slot no longer reads acceptable, so
// the controller publishes the fenced target with its fenced
// evidence (the line is minted only at the fenced epoch), never
// keeping the old line by its own acceptability predicate nor
// A fenced replacement of a lost primary reaches the controller as
// a failover: its slot no longer reads acceptable, so the controller
// publishes the fenced target with its fenced evidence (the line is
// minted only at the fenced epoch), never keeping the old line nor
// routing the target as a planned rebalance without that epoch.
if fencedReplace {
if lost && fencedReplace {
current := &vol.Slots[currentIdx]
current.Reachable, current.ReadyForPrimary = false, false
}
@@ -1016,19 +957,13 @@ func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) {
}
func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) {
if h == nil {
if h == nil || h.events == nil {
return
}
message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
if event.Ask.Intent == authority.IntentReassign {
message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
}
if h.log != nil {
h.log.Printf("blockmaster: volume=%s %s (%s)", event.Info.VolumeID, message, event.Ask.Intent)
}
if h.events == nil {
return
}
h.events.append(ops.ClusterEvent{
VolumeID: event.Info.VolumeID,
ReplicaID: event.Info.ReplicaID,
@@ -191,6 +191,7 @@ func TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied(t *testing.T) {
if _, err = ws.RegisterWorkspaceBinding(ctx, dst); err != nil {
t.Fatal(err)
}
h.reads.note("node-b", "rt", "", 1) // target report precedes move grant
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "rt", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch,
TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"})
if err != nil || !grant.Issued {
@@ -72,6 +72,7 @@ func TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot(t *testing.T) {
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
m.reads.note("node-a", "a2", "", 1) // target report precedes move grant
g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "to-a", VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch,
TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: "127.0.0.1:19111", TargetCtrlAddr: "127.0.0.1:19112", Kind: "clean"})
if err != nil || !g.Issued || g.NewHost != "node-a" {
@@ -205,7 +205,10 @@ func (s *storeAttestations) finalize() (already bool, err error) {
}
s.enveloped = true
if err := s.persist(s.vols); err != nil {
s.enveloped = false
var uncertain *attestationWriteUncertain
if !errors.As(err, &uncertain) {
s.enveloped = false
}
return false, err
}
return false, nil
@@ -537,9 +540,17 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
_ = os.Remove(temp)
return fmt.Errorf("store attestations: %w", werr)
}
return syncAttestationDir(filepath.Dir(s.path))
if err := syncAttestationDir(filepath.Dir(s.path)); err != nil {
return &attestationWriteUncertain{err}
}
return nil
}
// attestationWriteUncertain means the rename landed but its durability is unknown.
type attestationWriteUncertain struct{ error }
func (e *attestationWriteUncertain) Unwrap() error { return e.error }
// ingestStoreAttestation records a heartbeat's attestation when the
// reporting server holds the volume's published primary line at the
// attested epoch (the line's replica and owner). Anything else is not a
@@ -126,7 +126,7 @@ func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T)
h, conn, ctx := reviewBindingHost(t)
reviewLegacyBind(t, h, conn, ctx, "live-delete")
establishVolume(t, h, "live-delete") // a volume past creation keeps the live-lease refusal
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil {
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1, h.formatReadProof("live-delete", "r1", "node-a", 1)); err != nil {
t.Fatal(err)
}
lc := control.NewLifecycleServiceClient(conn)
@@ -136,7 +136,7 @@ func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T)
if h.lifecycle.Deletions.Reserved("live-delete") {
t.Fatal("refusal persisted a reservation")
}
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil {
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1, h.formatReadProof("live-delete", "r1", "node-a", 1)); err != nil {
t.Fatalf("refused delete interrupted renewal: %v", err)
}
}
@@ -281,18 +281,40 @@ func (h *Host) admitWorkspacePublicationNow(ask authority.AssignmentAsk, publish
epoch = line.Epoch
}
server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch)
// The format gate at the grant: an authority line is published
// only to a server whose own report reads the cluster's level; no report
// means no grant (the ask waits for it), and an ask decided on
// observations taken before its server reported a lower level is not
// published.
// A line with no recorded owner (a static topology's) goes to the process
// the facts show at the ask's endpoints; its server is the one judged.
grantServer := server
if grantServer == "" && h.obs != nil {
grantServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr)
// Publication places an authority line; only a renewal reply authorizes
// serving. During finalize and at level 1, place only refuses known-old
// targets. Resolve the target at the ask's endpoints, not another source.
placeServer := ""
if h.obs != nil {
placeServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr)
}
if why := h.grantTooOld(grantServer, ask.VolumeID); why != "" {
if placeServer == "" {
placeServer = server
}
why := h.placementTooOld(placeServer)
// A same-owner endpoint refresh, or a reassign (heal, failover) to the
// replica's committed holder, gives no new placement to this server.
// Judge this volume's process rather than an unrelated sibling process.
// Publisher still checks ExpectCurrent atomically before changing the line.
line, ok := h.Publisher().VolumeAuthorityLine(ask.VolumeID)
held := ok && line.Assigned && h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, line.Epoch) == placeServer
if ask.Intent == authority.IntentRefreshEndpoint && ask.ExpectCurrent != nil {
expected := ask.ExpectCurrent
held = held && line.ReplicaID == ask.ReplicaID &&
line.Epoch == expected.Epoch && line.ReplicaID == expected.ReplicaID &&
line.DataAddr == ask.DataAddr && line.CtrlAddr == ask.CtrlAddr &&
line.DataAddr == expected.DataAddr && line.CtrlAddr == expected.CtrlAddr
} else if ask.Intent != authority.IntentReassign {
held = false
}
if held {
reads, reported := h.reads.entry(placeServer, ask.VolumeID, h.servedBy(placeServer))
why = ""
if reported && reads < h.admissionFormatLevel() {
why = fmt.Sprintf("node %q's process for volume %q reads format level %d (binary_too_old)", placeServer, ask.VolumeID, reads)
}
}
if why != "" {
return fmt.Errorf("workspace publication: %s", why)
}
b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}
@@ -71,7 +71,8 @@ func bindingReconcileHistory(t *testing.T, legacySource bool) *Host {
p := h.Publisher()
ack := func(epoch uint64, server string) authority.WorkspaceHead {
t.Helper()
if _, err := p.RenewWorkspaceLease(ctx, "recover", "r1", epoch); err != nil {
h.reads.note(server, "recover", "history-"+server, 1)
if _, err := p.RenewWorkspaceLease(ctx, "recover", "r1", epoch, h.formatReadProof("recover", "r1", server, epoch)); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "recover", "r1", epoch); err != nil {
@@ -89,6 +90,7 @@ func bindingReconcileHistory(t *testing.T, legacySource bool) *Host {
epoch := uint64(i + 1)
source := []string{"node-a", "node-b", "node-c"}[i]
head := ack(epoch, source)
h.reads.note(target.ServerID, "recover", "history-"+target.ServerID, 1)
moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: fmt.Sprintf("move-%d", i), VolumeID: "recover", ExpectedReplicaID: "r1", ExpectedHost: source, ExpectedEpoch: epoch, TargetReplicaID: "r1", TargetHost: target.ServerID, TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"}, head)
if err != nil || !moved.Issued || moved.NewEpoch != epoch+1 {
t.Fatalf("history move: %+v %v", moved, err)
@@ -167,6 +167,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) {
if _, err = client.MoveWorkspace(ctx, q); err == nil {
t.Fatal("explicit volume fell back to legacy node pair")
}
h.reads.note("node-b", vol, "", 1) // prepared target reports before the grant
q.RequestId = vol + "-move"
q.TargetDataAddr = target.DataAddr
q.TargetCtrlAddr = target.CtrlAddr
@@ -138,6 +138,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-early"}); err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") {
t.Fatalf("delete under the exited holder's live authority: %v; want the clean revocation ACK refusal", err)
}
m.reads.note("node-b", "vol-a", "", 1) // target report before the move grant
move := &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}
if _, err := ws.MoveWorkspace(ctx, move); err == nil {
@@ -161,6 +162,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
case <-ctx.Done():
t.Fatal(ctx.Err())
}
m.reads.note("node-b", "vol-a", "", 1) // unserved target keeps reporting across the lease wait
grant, err := ws.MoveWorkspace(ctx, move)
if err != nil {
t.Fatal("forced move after the horizon:", err)
@@ -26,6 +26,7 @@ func TestWorkspaceLineOwnerIssuedAndHistorical(t *testing.T) {
if _, err := ws.RegisterWorkspaceBinding(ctx, target); err != nil {
t.Fatal(err)
}
h.reads.note("node-b", "v", "", 1) // target report before the move grant
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "owner-move", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"})
if err != nil {
t.Fatal(err)
@@ -99,6 +99,7 @@ func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceS
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
t.Fatal(err)
}
h.reads.note("node-b", "vol-f", "", 1) // capable target before the move grant
return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "forced", Force: true}
}
@@ -165,6 +166,7 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) {
case <-ctx.Done():
t.Fatal(ctx.Err())
}
h.reads.note("node-b", "vol-f", "", 1) // unserved target keeps reporting across the lease wait
pv2, err := client.PreviewWorkspaceMove(ctx, move)
if err != nil {
t.Fatal(err)
@@ -120,6 +120,7 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) {
}
// Slot-0 and slot-1 targets on the node's host pass these preconditions
// (they fail later, at the clean-move ACK check, for a different reason).
m.reads.note("node-b", "placed", "", 1) // isolate the endpoint and clean-ACK checks
for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} {
_, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312"))
if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") {
@@ -85,6 +85,7 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) {
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
m.reads.note("node-a", "a2", "", 1) // isolate target endpoint/collision checks
move := func(req, data, ctrl string) *control.WorkspaceMove {
return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1",
TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"}
@@ -171,7 +171,7 @@ func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.Workspace
}
return nil, status.Error(codes.FailedPrecondition, text)
}
l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch())
l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch(), s.host.formatReadProof(q.GetVolumeId(), q.GetReplicaId(), q.GetServerId(), q.GetEpoch()))
if errors.Is(err, authority.ErrWorkspaceRevoked) {
return nil, leaseRefusal(fmt.Sprintf("volume %s was moved or revoked; inspect sw-block ops workspace show --master MASTER --volume %s, complete the intended move, and leave this old unit stopped", q.GetVolumeId(), q.GetVolumeId()), control.WorkspaceLeaseRefusal_FINAL, 0)
}
@@ -465,7 +465,7 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho
refusal.text = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
case !replay && s.host.placementTooOld(target.ServerID) != "":
// Only a known-old report refuses a move target; the
// target's line is granted only after its own report.
// target receives a serving deadline only after its own report.
refusal = moveRefusal{"move target " + s.host.placementTooOld(target.ServerID), s.host.formatTooOldReason(target.ServerID)}
case !matched:
refusal.text = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
@@ -142,6 +142,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
if err != nil || len(unchanged.GetMoves()) != 0 || unchanged.GetRevocationAck().GetHeadGen() != 9 {
t.Fatal("refusal consumed ACK or wrote a move", unchanged, err)
}
h.reads.note("node-b", "vol-a", "", 1) // target process report before the grant
q.TargetReplicaId = "r2"
generation.Store(10) // operator metadata changed after the recorded ACK
grant, err := client.MoveWorkspace(ctx, q)
@@ -50,7 +50,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) {
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
})
reviewLegacyBind(t, h, c, ctx, "v")
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1); err != nil {
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1, h.formatReadProof("v", "r1", "node-a", 1)); err != nil {
t.Fatal(err)
}
client := control.NewWorkspaceServiceClient(c)
@@ -105,6 +105,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
if _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: oldID, HeadGen: seed.Gen}); err != nil {
t.Fatal(err)
}
m.reads.note("node-b", "vol-a", "", 1) // target process report before the grant
clean, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"})
if err != nil {
@@ -125,6 +126,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
// node-b dies before renewing or claiming. Before expiry plus skew the
// forced move is refused, and HEAD is not read for it.
m.reads.note("node-c", "vol-a", "", 1) // target process report before the forced grant
forced := &control.WorkspaceMove{RequestId: "forced-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: grantee, TargetReplicaId: "r1",
TargetServerId: "node-c", TargetDataAddr: third.DataAddr, TargetCtrlAddr: third.CtrlAddr, Kind: "forced", Force: true}
before := reads.Load()
@@ -140,6 +142,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
case <-ctx.Done():
t.Fatal(ctx.Err())
}
m.reads.note("node-c", "vol-a", "", 1) // unserved target keeps reporting across the lease wait
grant, err := ws.MoveWorkspace(ctx, forced)
if err != nil {
t.Fatal("forced move after the issued lease expired:", err)
+11
View File
@@ -227,6 +227,12 @@ type Host struct {
cancel context.CancelFunc
wg sync.WaitGroup
started atomic.Bool
// heartbeatAnswered closes when the master first answers this process's
// heartbeat (which names its incarnation): until then the master holds
// only a predecessor's report for the volume, so the lease runtime does
// not renew before it (identity check (1) of the format finalize bound).
heartbeatAnswered chan struct{}
heartbeatAnsweredOnce sync.Once
workspaceLeaseStarted atomic.Bool
// Guard installation and terminal host fencing share this lock. Order:
@@ -354,6 +360,8 @@ func New(cfg Config) (*Host, error) {
conn: conn,
obsCli: control.NewObservationServiceClient(conn),
asnCli: control.NewAssignmentServiceClient(conn),
heartbeatAnswered: make(chan struct{}),
}
h.incarnation = newIncarnation()
h.mw = newMasterWait(nil, lg.Printf)
@@ -792,6 +800,9 @@ func (h *Host) runHeartbeat(ctx context.Context) {
rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_, err := h.obsCli.ReportHeartbeat(rpcCtx, h.buildReport())
if err == nil {
h.heartbeatAnsweredOnce.Do(func() { close(h.heartbeatAnswered) })
}
if ctx.Err() == nil {
h.mw.call(err)
// The wait's reason reaches the journal on a change and every
@@ -0,0 +1,264 @@
package volume
import (
"context"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
)
// orderServer is a master's two holder-facing services on one listener: it
// records the order in which a holder's heartbeats and lease renewals
// arrive, and holds the FIRST heartbeat open until released (a slow first
// report, as after a master restart or a congested link). entered closes
// when that first heartbeat is inside the handler: from then on the
// heartbeat is in flight and not yet answered.
type orderServer struct {
control.UnimplementedObservationServiceServer
control.UnimplementedWorkspaceServiceServer
mu sync.Mutex
events []string
heartbeat int
entered chan struct{}
release chan struct{}
}
func newOrderServer() *orderServer {
return &orderServer{entered: make(chan struct{}), release: make(chan struct{})}
}
func (s *orderServer) record(e string) {
s.mu.Lock()
s.events = append(s.events, e)
s.mu.Unlock()
}
func (s *orderServer) ReportHeartbeat(ctx context.Context, r *control.HeartbeatReport) (*control.HeartbeatAck, error) {
s.mu.Lock()
s.heartbeat++
first := s.heartbeat == 1
s.mu.Unlock()
if first {
close(s.entered)
select {
case <-s.release:
case <-ctx.Done():
return nil, ctx.Err()
}
}
incarnation := ""
if slots := r.GetSlots(); len(slots) > 0 {
incarnation = slots[0].GetIncarnation()
}
s.record("heartbeat incarnation=" + incarnation)
return &control.HeartbeatAck{}, nil
}
func (s *orderServer) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
s.record("renewal")
ttl := 5 * time.Second
return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(ttl), ExpiresAtNs: time.Now().Add(ttl).UnixNano()}, nil
}
func (s *orderServer) snapshot() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.events...)
}
func (s *orderServer) renewed() bool {
for _, e := range s.snapshot() {
if e == "renewal" {
return true
}
}
return false
}
// firstHeartbeatRig starts an already-assigned holder (epoch 3, so the lease
// runtime may start at once) against s: its heartbeat loop and its lease
// runtime. started is when the lease runtime was started; done closes when it
// returns (any number of readers). Cleanup cancels the runtime and joins it
// within a bound, before the host and the server close; a failed join stops
// the test binary (joinOrFailStop), so nothing is torn down under it.
func firstHeartbeatRig(t *testing.T, s *orderServer) (h *Host, started time.Time, done <-chan struct{}) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
control.RegisterObservationServiceServer(srv, s)
control.RegisterWorkspaceServiceServer(srv, s)
go srv.Serve(ln)
t.Cleanup(srv.Stop)
h = workspaceRuntimeHost(t, ln.Addr().String(), true) // its cleanup closes the host (joins the heartbeat loop)
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan struct{})
h.Start()
started = time.Now()
go func() {
defer close(ch)
_ = h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 0, nil })
}()
t.Cleanup(func() {
cancel()
joinOrFailStop(ch, 10*time.Second)
})
return h, started, ch
}
// joinOrFailStop waits for done within bound. On timeout it ends the test
// binary at once (os.Exit, no unwinding): a panic would still run the
// cleanups after it (testing runs the rest when one panics), which close the
// host and the server and restore shared settings under a lease runtime
// that is still running.
func joinOrFailStop(done <-chan struct{}, bound time.Duration) {
select {
case <-done:
case <-time.After(bound):
fmt.Fprintln(os.Stderr, "the lease runtime did not return within "+bound.String()+" of its cancellation; refusing teardown under a live worker")
os.Exit(3)
}
}
// The rig's join fail-stops before teardown. A child test binary registers a
// teardown cleanup (it writes a marker file) and, after it, the join: with a
// worker that never returns the child exits with status 3 and the marker is
// absent (no teardown ran); with a worker that returned it passes and the
// marker is present.
func TestAFailedRuntimeJoinFailStopsBeforeTeardown(t *testing.T) {
if marker := os.Getenv("JOIN_FAILSTOP_MARKER"); marker != "" {
t.Cleanup(func() { _ = os.WriteFile(marker, []byte("teardown ran"), 0o644) }) // the later teardown
done := make(chan struct{})
if os.Getenv("JOIN_FAILSTOP_JOINED") == "true" {
close(done)
}
t.Cleanup(func() { joinOrFailStop(done, 50*time.Millisecond) }) // runs first
return
}
for _, joined := range []bool{false, true} {
marker := filepath.Join(t.TempDir(), "teardown-ran")
// The child is bounded: a join that hangs is killed at the deadline
// and fails here as a timeout, never as the expected exit 3.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.timeout=20s")
cmd.WaitDelay = 5 * time.Second
cmd.Env = append(os.Environ(), "JOIN_FAILSTOP_MARKER="+marker, "JOIN_FAILSTOP_JOINED="+strconv.FormatBool(joined))
out, err := cmd.CombinedOutput() // returns only after the child is reaped (killed at the deadline if need be)
timedOut := ctx.Err() != nil
cancel()
if timedOut {
t.Fatalf("joined=%v: the child did not finish within 30s (killed): %v\n%s", joined, err, out)
}
_, statErr := os.Stat(marker)
var exit *exec.ExitError
switch {
case joined && (err != nil || statErr != nil):
t.Fatalf("a returned worker: child %v, teardown marker %v\n%s", err, statErr, out)
case !joined && !(errors.As(err, &exit) && exit.ExitCode() == 3):
t.Fatalf("a worker that never returned: child %v, want exit status 3\n%s", err, out)
case !joined && statErr == nil:
t.Fatalf("a worker that never returned: the later teardown ran\n%s", out)
case !joined && !strings.Contains(string(out), "refusing teardown under a live worker"):
t.Fatalf("a worker that never returned: no cause in the output\n%s", out)
}
}
}
// Identity check (1) of the v1.1.2 bound: a v1.1 holder's first lease
// renewal on start follows its first ANSWERED heartbeat, which names its
// incarnation. Until then the master holds only its predecessor's report for
// the volume, and a renewal would be judged on that report. The window is
// witnessed open: the first heartbeat is inside the master's handler, held
// there, while the lease runtime has every chance to renew; once it is
// answered, a renewal follows.
func TestAHolderRenewsOnlyAfterItsFirstHeartbeatWithItsIncarnation(t *testing.T) {
s := newOrderServer()
h, _, _ := firstHeartbeatRig(t, s)
select {
case <-s.entered:
case <-time.After(5 * time.Second):
t.Fatal("the holder's first heartbeat never reached the master")
}
// The heartbeat is in flight and unanswered: the window is open.
time.Sleep(500 * time.Millisecond)
if s.renewed() {
t.Fatalf("the holder renewed its lease while its first heartbeat was in flight: %v", s.snapshot())
}
close(s.release)
runtimeAwait(t, "a renewal after the first heartbeat", s.renewed)
events := s.snapshot()
if len(events) == 0 || events[0] == "renewal" {
t.Fatalf("first event %v, want the first heartbeat", events)
}
if events[0] != "heartbeat incarnation="+h.incarnation || h.incarnation == "" {
t.Fatalf("the first heartbeat %q does not name this process's incarnation %q", events[0], h.incarnation)
}
}
// A holder whose first heartbeat is never answered does not renew and does
// not serve: the lease runtime waits the configured bound (one lease
// validity; shortened here), no less and not much more, then installs its
// guard fenced and returns. The wait is measured from its own start (a test
// hook), to its return; the tolerance covers the runtime's 50 ms poll and
// the fenced guard's install and drain.
func TestAHolderWhoseHeartbeatIsNeverAnsweredFencesRatherThanServes(t *testing.T) {
const bound, tolerance = 300 * time.Millisecond, 500 * time.Millisecond
previous, previousHook := firstHeartbeatWait, firstHeartbeatWaitStarted
waitStarted := make(chan time.Time, 1)
firstHeartbeatWait = bound
firstHeartbeatWaitStarted = func(at time.Time) {
select {
case waitStarted <- at:
default:
}
}
t.Cleanup(func() { firstHeartbeatWait, firstHeartbeatWaitStarted = previous, previousHook })
s := newOrderServer() // never released
h, _, done := firstHeartbeatRig(t, s)
select {
case <-s.entered:
case <-time.After(5 * time.Second):
t.Fatal("the holder's first heartbeat never reached the master")
}
var start time.Time
select {
case start = <-waitStarted:
case <-time.After(5 * time.Second):
t.Fatal("the lease runtime never started waiting for the first answered heartbeat")
}
select { // suite protection only; the bound is checked below
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("the lease runtime kept waiting past the bound instead of fencing")
}
switch waited := time.Since(start); {
case waited < bound:
t.Fatalf("the lease runtime fenced after %s, before its %s bound", waited, bound)
case waited > bound+tolerance:
t.Fatalf("the lease runtime fenced after %s, past its %s bound plus %s", waited, bound, tolerance)
}
if s.renewed() {
t.Fatalf("a holder with no answered heartbeat renewed: %v", s.snapshot())
}
guard := h.view.workspaceGuard.Load()
if guard == nil || !strings.Contains(guard.FenceCause(), "no heartbeat of this process answered within "+bound.String()) {
t.Fatalf("the guard was not installed fenced with the unanswered-heartbeat cause and its bound: %v", guard)
}
if h.ProjectionView().Projection().Healthy {
t.Fatal("a holder with no answered heartbeat serves")
}
}
@@ -26,12 +26,28 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
}
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
var heartbeatWaitStart time.Time
for {
if err := ctx.Err(); err != nil {
return err
}
p := h.view.Projection()
if p.Epoch > 0 {
// The first renewal waits for this process's first answered heartbeat,
// at most one lease validity: past that the guard is installed fenced
// (no renewal, no serving) rather than waiting for ever.
unanswered := ""
if p.Epoch > 0 && !h.firstHeartbeatAnswered() {
if heartbeatWaitStart.IsZero() {
heartbeatWaitStart = time.Now()
if hook := firstHeartbeatWaitStarted; hook != nil {
hook(heartbeatWaitStart)
}
}
if time.Since(heartbeatWaitStart) >= firstHeartbeatWait {
unanswered = fmt.Sprintf("no heartbeat of this process answered within %s; a renewal would be judged on another process's report", firstHeartbeatWait)
}
}
if p.Epoch > 0 && (unanswered != "" || h.firstHeartbeatAnswered()) {
id := &control.WorkspaceIdentity{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, ServerId: h.cfg.ServerID, Epoch: p.Epoch}
guard, err := NewWorkspaceLeaseGuard(h.view, control.NewWorkspaceServiceClient(h.conn), id, func(c context.Context) (uint64, error) { return stop(c, id) }, nil)
if err != nil {
@@ -52,6 +68,9 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
if ctx.Err() != nil {
guard.fenceLocked("shutdown requested (context cancelled)")
}
if unanswered != "" {
guard.fenceLocked(unanswered)
}
guard.stopPending = h.workspaceStopPending
h.view.workspaceGuard.Store(guard)
h.workspaceLeaseMu.Unlock()
@@ -65,6 +84,32 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
}
}
// firstHeartbeatWait bounds the wait for the first answered heartbeat: the
// longest lease validity a renewal reply may carry (Refresh refuses more).
// Tests shorten it.
var firstHeartbeatWait = 30 * time.Second
// firstHeartbeatWaitStarted, when set (tests only), is told when the lease
// runtime starts waiting for the first answered heartbeat.
var firstHeartbeatWaitStarted func(time.Time)
// firstHeartbeatAnswered reports whether the lease runtime may renew: the
// master has answered this process's first heartbeat (with its incarnation),
// so a renewal is judged on this process's own report, never on a
// predecessor's. A host whose heartbeat loop never started (Start not called)
// has nothing to wait for.
func (h *Host) firstHeartbeatAnswered() bool {
if !h.started.Load() {
return true
}
select {
case <-h.heartbeatAnswered:
return true
default:
return false
}
}
// WorkspaceStopPending is called when a graceful stop of volumeID has begun
// (its chunk layer is being detached): the lease guard renews at once and
// then sleeps at most stopPendingPoll between renewals, instead of its normal
+27 -46
View File
@@ -9,7 +9,7 @@ The design is described in three documents, and this one collects their machines
**Conventions.** These are the same as in the design documents.
- Code references name a file and a function, not a line number. Test references name the test function and its file.
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it; an entry naming a model checked outside the repository says so. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
- Status:
- `ACTIVE`: a Go test in this repository asserts the statement.
- `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row.
@@ -60,7 +60,7 @@ stateDiagram-v2
Ready --> Ready: changed files synced, renamed, directory synced
Ready --> Faulted: record put/import persistence failure
Recovering --> Faulted: recovery directory sync failure
Faulted --> Exited: one ERROR attempt, exit 74 within 1 s
Faulted --> Exited: one ERROR attempt, exit 1 within 1 s
Exited --> Recovering: supervisor restarts
```
@@ -71,7 +71,7 @@ stateDiagram-v2
| Ready | Ready | a changed put or import: changed files are durable before rename (per-file fsync, or one `syncfs` on a qualified filesystem) and one directory barrier precedes publication; an unchanged record does no I/O and keeps its SeenAt | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `core/lifecycle/node_inventory.go` `ImportNodes`, `registrationLocked`; `core/lifecycle/placement_intent.go` `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-NODE-REGISTRATION-FRESHNESS-001` |
| Ready | Faulted | a put or import returns a `RecordPersistenceError`; the store latches it, so later mutations return `ErrLifecycleRecoveryRequired`, before calling the process policy; a marshal error before any I/O does not latch | `core/lifecycle/record_file.go` `latchPersistenceFailure`; each store's `putLocked`, `ImportNodes`, `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Recovering | Faulted | a store open's records-directory sync fails; `New` hands the `RecordPersistenceError` to the process policy | `core/lifecycle/record_file.go` `syncRecordDirectory`; `core/host/master/host.go` `New` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 74 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 1 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
| Exited | Recovering | the supervisor restarts blockmaster (`Restart=on-failure`) | `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
A store latches the error before calling the process policy. A failed step may
@@ -88,10 +88,7 @@ before rename; startup reports the chosen path for the node and placement
stores, each probed at its own directory. The filesystem-wide sync can
also wait for unrelated writeback on that filesystem.
The executable arms a one-second process-exit timer before logging
and exits with status 74 (durability unknown) immediately after the log
returns. The best-effort log reason is `lifecycle_persist_failed`; status 74
alone does not identify a lifecycle fault, since authority-store faults use
the same status. The process does not wait for graceful
and exits immediately after the log returns, rather than waiting for graceful
shutdown behind a writer. Embedders without this process policy must reopen a
failed store before any further mutation. Removal errors do not invoke this
policy: the in-memory record and its published snapshot stay present until
@@ -192,7 +189,7 @@ flowchart LR
|---|---|---|---|---|
| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; new addresses, or the same addresses for another primary process (the line's incarnation differs); a no-op when both are unchanged; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against and the volume's line is no longer that one (replica, epoch, addresses) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/directive.go` `expectedLineMoved` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`, `INV-AUTH-RESTART-REISSUE-001` |
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against (the controller's rebalance and failover, an operator's failback) and the volume's line is no longer that one, compared by replica and epoch, and by addresses only when the ask names them (the controller's moves do; an operator's failback names replica and epoch only, so an endpoint move to other addresses does not refuse it): a queued controller move never overwrites a reassign or an endpoint move to other addresses that landed after its decision; a same-address endpoint reissue (new endpoint version or incarnation, same addresses) still matches, and the move's epoch bump fences it | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume`; `core/authority/directive.go` `expectedLineMoved`; `core/authority/controller.go` `decideVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing; a write whose outcome is unknown (the directory fsync after the rename failed) fail-stops blockmaster, so no caller is told it failed | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
@@ -201,34 +198,6 @@ flowchart LR
| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` |
| DeleteReserved, removed from the desired spec | Retired metadata (reservation permanent) | no live lease, then a fresh bounded HEAD read proves deleted or absent; unread/live/deleting keeps the records. Remove authority durably, then placement and bindings, then the volume record; a crash retries the remaining removals. A startup lease skip schedules one more pass after the latest observed barrier, also without the product loop; full passes log skips. The store and its resweep inputs are untouched | `core/host/master/spec_retirement.go` `ReconcileDeletedSpecVolumes`, `startPostFloorRetirement`; `core/authority/workspace_retirement.go` `RetireDeletedWorkspace` | `INV-SPEC-DELETE-RETIRE-001`, `INV-SPEC-DELETE-RETRY-001` |
**Controller ask, per volume (between the promotion gate and the publisher).**
The topology controller turns a supported snapshot into at most one ask per volume. The publisher drains the controller's queue one ask at a time (its `Run` loop, between two calls of `next`). A fenced replace decided by the supported gate is submitted with the replaced primary's slot unacceptable, whatever the gate's reason, so the controller's own acceptability predicate never keeps that primary. An ask is pending while it is queued or held by the publisher; an identical ask is deduplicated only while it is pending.
```mermaid
stateDiagram-v2
[*] --> Queued: intake decides an ask (desired, DesiredAt set)
Queued --> Held: publisher takes it (next)
Held --> Published: apply publishes (line moves)
Held --> Lost: apply ends without a publication (publisher calls next again)
Lost --> Queued: next intake decides the identical ask (DesiredAt kept)
Queued --> Queued: identical ask decided (already desired)
Held --> Held: identical ask decided (already desired)
Published --> [*]: snapshot observes the new line (desired confirmed)
```
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| no desired ask | Queued | an intake of a supported snapshot decides an ask; the desired entry records DesiredAt. A fenced replace (with or without a recorded loss) reaches the controller with the replaced primary's slot unreachable and not ready, so its intake decides the failover to the fenced target | `core/authority/controller.go` `processSupportedVolumeLocked`, `decideVolume`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-PROMOTE-REPLACE-HANDOFF-001`, `INV-PROMOTE-REPLACE-HANDOFF-002` |
| Queued | Held | the publisher takes the ask; the queue records the volume it holds | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
| Queued or Held | (no change) | an intake decides the identical ask while it is pending: deduplicated (`already desired since T`), nothing queued twice | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending` | `INV-AUTH-DESIRED-RETRY-001` |
| Held | Published | the apply publishes the line (epoch minted by the publisher) | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-EPOCH-MINT-001` |
| Held | Lost | the apply ends without a publication (refused, or dropped); the publisher asks for its next ask, which clears the held volume | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
| Lost | Queued (DesiredAt kept) | an intake decides the identical ask while the line, re-read after the pending check, is still the one it decided against (an ask published during the intake is not lost): enqueued again (`enqueued again ...`), the desired entry and its DesiredAt unchanged | `core/authority/controller.go` `processSupportedVolumeLocked` | `INV-AUTH-DESIRED-RETRY-001`, `INV-AUTH-DESIRED-RETRY-002` |
| any desired (unconfirmed) | Stuck evidence | DesiredAt + retry window passed without the line observed; a repeatedly lost ask reaches it from its first desire | `core/authority/convergence.go` `evaluateStuckLocked` | `INV-AUTH-DESIRED-RETRY-002` |
Model: PromoLive r6, checked outside the repository (it is not in `docs/spec/`), models this handoff with the intake split as the code does it (read the line and decide; after the publisher may have run, enqueue only if the ask is not pending and the line is still the one read). `RoundProgress` and `QueuedMatchesLine` hold; the mutants `dedupe_keeps_lost`, `predicate_split` and `nonatomic_submit` are each caught. The retry window and the Stuck evidence are not modelled; their test is the evidence.
**Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established.
```mermaid
@@ -804,6 +773,25 @@ Name-only snapshot deletion is a legacy-format transition only: it refuses a v1.
| Terminal retained | Retired | at least this handle's Wc since its end; next admission or poll scans bounded table | retireManualCutsLocked | INV-CUT-HANDLE-LIFETIME-001 |
### M-format. Cluster format finalize
```mermaid
stateDiagram-v2
Level0 --> Finalizing: check possible live leases and set intent under grant locks
Finalizing --> Level1: durable envelope succeeds, then publish level 1
Finalizing --> Level0: proven pre-rename failure, then clear intent
Finalizing --> Exited74: uncertain post-rename failure, keep intent and fail-stop
```
| From | To | Guard / action | Enforced in | Invariant |
|---|---|---|---|---|
| Level 0 | Finalizing | Preserve the existing known-old work check. Under Publisher mu then leaseMu, exclude unserved lines, clean ACKed releases and proven-ended leases; require the latest level-1 report received for each remaining volume (a delayed report can stand in for a newer process; the operations manual's finalize rule covers that) and set the admission intent. Report changes invalidate captured proofs. | `core/authority/format_finalize.go` `BeginFormatFinalize`; `core/host/master/format_gate.go` `FinalizeFormat` | `INV-FMT-FINALIZE-001` |
| Finalizing | Finalizing | Move and publication are placement: refuse only known-old targets. First serving deadlines, live renewals and regrants require the latest level-1 report received for the volume during intent and at level 1 (a delayed report is covered by the operations manual's finalize rule). A stored move lease alone permits no serving. Capable renewals stay memory-only; no grant lock spans the durable write. | `core/host/master/workspace_binding.go` `admitWorkspacePublication`; `core/authority/workspace_lease_view.go` `firstWorkspaceGrant`, `regrantWorkspaceLease` | `INV-FMT-FINALIZE-001`, `INV-WS-RENEW-NONBLOCKING-001` |
| Finalizing | Level 1 / Level 0 | On durable success publish level 1 under the grant locks; on a proven pre-rename failure clear the intent; an uncertain post-rename persistence failure retains the intent and fail-stops for recovery. The in-memory intent is not a persisted format or a new authority fact. | `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `CancelFormatFinalize` | `INV-FMT-LEVEL-001`, `INV-FMT-FINALIZE-001` |
FormatGate r12 models this interval as Begin, durable raise and Abort, refining r11's atomic `Finalize`.
The intent closes level-0 serving admission while the store write runs outside the grant locks. It neither grants authority nor raises a holder's effective level.
## Part B. Invariant ledger
@@ -1038,8 +1026,6 @@ Notes:
| `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE |
| `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE |
| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-DESIRED-RETRY-001` | The controller deduplicates a desired ask only while it is pending: queued, or taken by the publisher and still being applied. An identical ask that ended without a publication, the line still the one it was decided against, is enqueued again on the next intake. | M2 controller ask: Queued or Held (deduplicated); Held → Lost; Lost → Queued | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending`, `next` | `TestALostReassignIsEnqueuedAgainOnTheNextIntake`, `TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `QueuedMatchesLine`, `RoundProgress` (mutants `dedupe_keeps_lost`, `nonatomic_submit`) | ACTIVE |
| `INV-AUTH-DESIRED-RETRY-002` | An ask enqueued again keeps its first DesiredAt, so an ask lost on every apply still becomes Stuck once the retry window passes from that first desire. | M2 controller ask: Lost → Queued (DesiredAt kept); Stuck evidence | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/convergence.go` `evaluateStuckLocked` | `TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (the retry; the retry window and Stuck are not modelled: the test is the evidence) | ACTIVE |
| `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`, `refreshAsk` (conditional on the line it read); `core/host/master/product_loop.go` `RunLifecycleProductTick`, `restartedHolderRefresh` (the product loop's direct path for a workspace-bound RF1 volume, conditional on the line it read); `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestRF1RuntimeVolumeIsReissuedToARestartedHolder`, `TestRF1RuntimeLineNamingNoProcessIsReissued`, `TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied` (`core/host/master/rf1_restart_reissue_test.go`); `TestRefreshIsConditionalOnTheLineItWasDecidedAgainst`, `TestControllerRefreshNamesTheLineItWasDecidedAgainst` (`core/authority/refresh_expected_line_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE |
| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
@@ -1052,14 +1038,14 @@ Notes:
| `INV-WS-RESTART-GRACE-001` | At format level 1, a renewal writes nothing durable. A forced move, an expired re-grant and a no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
| `INV-WS-AUTH-RECORD-V2-001` | The format finalize writes the store's attestation file as format 2 (`INV-FMT-LEVEL-001`), on which a v1.0.x master refuses its whole start; from then on its authority records are envelope version 2 (a v1.0.x master would skip them); before it, both are v1.0's. It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
| `INV-FMT-LEVEL-001` | The cluster's format level is the attestation file's form: v1.0.x's bare map is level 0, the envelope (format 2, format_level 1) level 1. It only rises: the finalize is its only writer, and an envelope below level 1 is refused at start. | FormatGate Finalize (level 0 → 1) | `core/host/master/store_attestation.go` `decodeStoreAttestations`, `finalize`, `persist`, `level`; `core/host/master/host.go` `New` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestAnAttestationEnvelopeBelowLevel1IsRefused` (`core/host/master/format_gate_test.go`); `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAV100MasterRefusesTheAttestationEnvelope` (`core/host/master/golden_v100_test.go`) | `FormatGate` `OneWay` (mutation `level_lowered`) | ACTIVE |
| `INV-FMT-FINALIZE-001` | The finalize is refused, naming them, only while a fresh report of a process holding a volume reads below 1; hosts with no or a stale report are listed, not blocking. Else it writes the envelope durably, then switches the publisher under both its locks, then answers; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeCheck`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestFinalizeFormatListsTheHostsItCannotConfirm`, `TestAFailedFinalizeWriteLeavesLevel0`, `TestAHolderRestartedOnAnOldBinaryIsNotReissuedItsLine` (`core/host/master/format_gate_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted` (`core/host/volume/line_incarnation_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`); `TestClusterFinalizeFormatTypedAnswer` (`cmd/sw-block/cluster_format_json_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE |
| `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported server is placeable; no line is granted to a holder process before its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`, `grantTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE |
| `INV-FMT-FINALIZE-001` | Finalize checks possibly-live leases and sets a memory intent under grant locks. First grants, renewals and regrants require the latest level-1 report during intent and at level 1. Move/publication is Place. I/O holds no grant lock; pre-rename failure clears intent; uncertain persistence fail-stops. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeCheck`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `BeginFormatFinalize`, `CancelFormatFinalize` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestFinalizeFormatListsTheHostsItCannotConfirm`, `TestAFailedFinalizeWriteLeavesLevel0`, `TestAHolderRestartedOnAnOldBinaryIsNotReissuedItsLine` (`core/host/master/format_gate_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted` (`core/host/volume/line_incarnation_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`); `TestClusterFinalizeFormatTypedAnswer` (`cmd/sw-block/cluster_format_json_test.go`); `TestFinalizeRequiresTheGrantedHoldersReadReport`, `TestFinalizeSerializesTheLevelZeroPublicationBoundary`, `TestFormatFinalizeIntentRequiresRegrantReport`, `TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases`, `TestFormatFinalizeIntentDoesNotSurviveProcessExit`, `TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen`, `TestFormatFinalizeLiveRenewalChecksCurrentProcess`, `TestFormatFinalizeDeadlineProofSurvivesIntentCompletion`, `TestFormatMoveRecordCannotServeBeforeReportedRenewal`, `TestFormatFinalizeUncertainWriteFailStops` | FormatGate r12 FinalizeBegin, FinalizeCommit, FinalizeAbort, Grant, Renew / ServersReported, GrantReport, NoStrand; serve_across_restart and grant_unchecked_in_intent are refused; move/publication is Place, and only a checked renewal reply grants serving | ACTIVE |
| `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported target may be placed or moved; its serving deadline requires its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE |
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-NODE-REGISTRATION-FRESHNESS-001` | Replaying a node registration without an observation time preserves its stored SeenAt; unchanged non-time fields do not rewrite its record. A restart is not a fresh observation, also when the declaration changed; a live heartbeat supplies freshness independently. | M2 lifecycle registration replay (no authority transition) | `core/lifecycle/node_inventory.go` `ImportNodes`, `RegisterNode`, `registrationLocked`; `core/host/master/observation_snapshot.go` `nodeHeartbeat`; `core/lifecycle/verified_placement.go` `VerifyPlacementIntent` | `TestUnchangedNodeRestartDoesNotRefreshAStaleObservation`, `TestChangedNodeImportDoesNotRefreshAStaleObservation` (`core/lifecycle/node_import_freshness_test.go`); `TestObservationNodesReportTheNewestHeartbeat` (`core/host/master/observation_heartbeat_test.go`); live-holder process restart qualification pending | Observation time is evidence, not authority; a declaration is not an observation | STUB |
| `INV-LIFECYCLE-STORE-DURABLE-001` | A successful record put/import publishes only after complete replacement records and their directory are durable. Open syncs the records directory before publication. A possibly-applied failure blocks mutations until reopen; recovery reconciles complete old/new records. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `node_inventory.go` `ImportNodes`; `placement_intent.go` `ImportPlans`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`); `TestImportStepSyncsChangedFilesThenOneDirectory` (`core/lifecycle/import_step_sync_test.go`); `TestImportSyncfsFailureAndOrdering`, `TestImportSyncfsReturnedFailurePolicyAndReplay`, `TestImportSyncfsCrashBoundaries`, `TestSyncfsKernelGate`, `TestSyncfsFilesystemGate`, `TestImportBatchSelectsSyncfsByFilesystem`, `TestImportDurabilityModeProbesEachStoreDirectory` (`core/lifecycle/import_syncfs_test.go`); `TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk` (`core/lifecycle/import_recovery_test.go`); `TestVolumeEqualityRequiresRecovery` (`core/lifecycle/volume_recovery_test.go`); `TestNodeMarshalErrorDoesNotRequireRecovery` (`core/lifecycle/remove_retry_test.go`) | Lifecycle record publication, including startup-step durability barrier | ACTIVE |
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits 74 (durability unknown) within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits nonzero within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE |
@@ -1410,10 +1396,6 @@ Notes:
| `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` | The automatic path never replaces a lost primary of a `best_effort` volume (a write may be on the primary alone, as for the operator's move): both gates hold it before any fencing round and show `best_effort_no_automatic_failover`. | M3 Supporting → promotion candidate (both gates) | `core/host/master/product_loop.go` `automaticFailoverHold` (supported gate before `fencedDecision`; unsupported gate before its candidates); `promotionAllowedReplicas` | `TestTheAutomaticPathHoldsABestEffortVolume` (`core/host/master/best_effort_hold_test.go`); `TestMountedFailover_ProductLoopRF3BestEffortIsHeldDespiteAHighestDurableSurvivor`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-ACK-PROFILE-MATCH-001` | The automatic path holds a lost primary's volume, before any fencing round and showing `ack_profile_mismatch`, when a probe answer names no ack profile or another than blockmaster's `--launcher-replication-ack`; blockmaster refuses to start with an unknown one. | M3 Supporting → promotion candidate (both gates) | `core/host/master/probe_round.go` `profileMismatch`; `core/host/master/product_loop.go` `automaticFailoverHold` (plain round), `fencedDecision` (fencing round); `core/host/volume/probe_round.go` `probeAnswer`; `cmd/blockvolume/main.go` `hostConfig`; `cmd/blockmaster/main.go` `parseFlags` | `TestTheAutomaticPathHoldsOnAnAckProfileMismatch`, `TestProbeRound_ReportsAnAckProfileMismatch`, `TestTheFencingRoundsAckProfileIsCheckedToo` (`core/host/master/ack_profile_mismatch_test.go`); `TestProbeAnswerNamesTheVolumesAckProfile` (`core/host/volume/probe_ack_profile_test.go`); `TestHostConfigAnswersTheVolumesOwnAckProfile` (`cmd/blockvolume/probe_ack_profile_test.go`); `TestBlockmasterRefusesAnUnknownLauncherReplicationAck` (`cmd/blockmaster/launcher_replication_ack_flag_test.go`) | — | ACTIVE |
| `INV-PROMOTE-DECISION-REPORTED-001` | Every replace decision of the supported promotion gate is logged once after its tick: with the controller's outcome from the same submission (read under its lock, so a later intake cannot change it), as not submitted and why, or as a failed submit. Diagnostics only: no decision changes. | M3 Supporting → promotion candidate (supported gate → controller → publisher) | `core/host/master/product_loop.go` `submitPlacementSnapshots`, `noteGateReplace`, `reportReplaces`; `core/authority/controller.go` `SubmitObservedStateOutcomes`, `LastOutcome` | `TestAReplaceDecisionLogsWhatTheControllerDidWithIt` (cases: enqueued, already desired, no ask with why, not submitted, an intake after the submission does not change its report, a submission that did not carry the volume, one report per decision), `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication`, `TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted` (`core/host/master/gate_controller_outcome_test.go`, `core/host/master/gate_binding_read_failure_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-AUTHORITY-PUBLICATION-LOGGED-001` | Every authority publication is logged on the master's log with its volume, replica, epoch, endpoint version and intent, also when no event sink is set. Diagnostics only: no decision changes. | M3 controller → publisher (publication observer) | `core/host/master/product_loop.go` `recordAuthorityPublishedEvent` | `TestAPublicationIsLogged`, `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication` (`core/host/master/gate_controller_outcome_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-PROMOTE-REPLACE-HANDOFF-001` | A fenced replace decided by the supported promotion gate, whatever its reason (a recorded loss, or a primary only the gate reads as unacceptable, such as one on a node below the cluster's format level), submits the replaced primary's slot as unreachable and not ready. | M2 controller ask: no desired ask → Queued (failover) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
| `INV-PROMOTE-REPLACE-HANDOFF-002` | The controller never keeps a primary the gate replaced by its own acceptability predicate: it publishes the fenced target with its fenced evidence, the line minted only at the fenced epoch. | M2 controller ask: no desired ask → Queued (failover); M3 Primary → another replica Primary at e+1 | `core/authority/controller.go` `decideVolume` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`); `TestALostPrimarysFencedReplacementIsPublished` (`core/host/master/primary_loss_publish_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
| `INV-PRIMARY-ACK-PROFILE-001` | A primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (blockmaster's); otherwise its frontend is not Healthy and status names both profiles. So a lost primary, which does not answer, acknowledged under the master's profile. | M1 Primary → Serving (replicated line) | `core/host/master/services.go` `assignmentFact` (`ack_profile`); `core/host/volume/workspace_startup.go` `noteAckProfile`; `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/host/volume/status_server.go` | `TestPrimaryOfAReplicatedLineServesOnlyUnderTheMastersAckProfile` (`core/host/volume/ack_profile_refusal_test.go`); `TestAssignmentNamesTheMastersAckProfile` (`core/host/master/ack_profile_mismatch_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 |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
@@ -1435,7 +1417,6 @@ Notes:
- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only.
- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`.
- `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001`, `INV-PROMOTE-FRONTIER-BEST-EFFORT-001`: new rows split from `INV-PROMOTE-FRONTIER-001`, kept beside it. N_peers is the number of replicas other than the current primary; for RF=3 (two peers) both must be seen under `sync_quorum`, one under `sync_all`. An unknown frontier is never read as zero. Heartbeat freshness is the observation store's rule (`FreshSlotCandidate`). The gate runs for every volume with two or more slots (RF=2 included); a primary change is published only with its evidence.
- `INV-PROMOTE-DECISION-REPORTED-001`: a decision is not submitted when the placements changed during the probe, a volume got a workspace binding, a replica's endpoints are bound elsewhere, or the workspace bindings could not be read after the probe; the line names which. `INV-AUTHORITY-PUBLICATION-LOGGED-001` was split from it.
- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values.
- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only.
- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence.
+69 -7
View File
@@ -262,9 +262,7 @@ follow the state-storage and low-write-load guidance in section 1 before restart
blockmaster must run under systemd or an equivalent restart supervisor. A node, placement
or volume lifecycle record write or recovery-directory sync failure attempts one `ERROR` naming the store,
record and error, ending with `exiting so the supervisor restarts from durable state`,
and exits with status 74 (durability unknown). The best-effort log reason
`lifecycle_persist_failed` identifies a lifecycle fault; status 74 alone does not,
because authority-store faults use the same status. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
and exits with status 1. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
`sw-blockmaster.service` has `Restart=on-failure` and `RestartSec=5s`; restart reloads
complete records through the recovery barriers before serving again.
@@ -615,7 +613,60 @@ writing the v1.0 format until you finalize. Until then you can go back.
**Going back** before the finalize: reinstall the v1.0.x binaries in reverse order (each holder, then
blockmaster), restarting each the same way. The v1.1 CLI can stay.
5. **Finalize** once every holder runs v1.1:
5. **Finalize** once every holder runs v1.1.
**Hard rule: from the end of the upgrade until `sw-block cluster finalize-format` completes, no v1.0.x volume process
may run on any host, and none may start.**
Check it on **every host itself**. blockmaster's view cannot show it, so do not rely on it.
`blockvolume --version` prints the build's revision, not a release number:
`blockvolume revision=<commit> modified=<true|false|unknown>`. Compare every line with the line the v1.1.x binary
you installed on that host prints.
```sh
# 0. The reference line: the v1.1.x blockvolume binary you installed on this host.
/usr/local/bin/blockvolume --version
# 1. Every RUNNING volume process: /proc/<pid>/exe runs the image that process is running,
# even if an upgrade has since replaced the file on disk.
for pid in $(pgrep -x blockvolume); do printf '%s ' "$pid"; sudo /proc/"$pid"/exe --version; done
# 2. The binary each unit would start on a restart: every blockvolume unit and instance, loaded or not (an
# enabled but stopped unit is not loaded, so a systemctl glob alone would skip it). Instances come from the
# loaded list, the enabled links, and instance drop-in directories (an instance-only override, such as
# sw-blockvolume@v1.service.d/override.conf, can set its own ExecStart); systemctl cat <instance> shows the
# template with that instance's drop-ins.
units=$( { systemctl list-unit-files 'sw-blockvolume*' --no-legend | cut -d' ' -f1
systemctl list-units --all 'sw-blockvolume@*' --no-legend --plain | cut -d' ' -f1
ls /etc/systemd/system/*.wants/ /run/systemd/system/*.wants/ 2>/dev/null | grep '^sw-blockvolume'
for d in /etc/systemd/system/sw-blockvolume*.service.d /run/systemd/system/sw-blockvolume*.service.d; do
[ -d "$d" ] && basename "$d" .d
done; } | sort -u)
for b in $(for u in $units; do systemctl cat "$u"; done | sed -n 's/^ExecStart=\([^ ]*\).*/\1/p' | sort -u); do
printf '%s ' "$b"; "$b" --version
done
```
Every line of steps 1 and 2 must print exactly the reference line, with `modified=false`. A line with another
revision, `modified=true` or `modified=unknown`, an error, or no output means that the process or unit cannot be
shown to run v1.1.x: stop that volume (or fix that unit) and upgrade it before the finalize. Do not roll any host
back while the finalize runs.
**Also:** wait at least 30 seconds after the last start or restart of any volume process before running the
finalize. In that time a running process normally reports its read level, and the finalize refuses while the latest
report for a volume shows an older level, so the wait usually catches a process that was missed. A report can be
delayed without bound (see "What remains"), so the wait does not replace the hard rule.
**What remains (stated, not closed in v1.1.2):**
- The finalize judges each serving volume by the last heartbeat report blockmaster received for that volume.
- A report delayed in the network or inside blockmaster can arrive after a newer process's report and stand in for
it. No wait bounds that delay. The delayed report can come from a process that has since stopped, including an
old one.
- What keeps the finalize safe in that case is which process can still serve: with no v1.0.x process running or
able to start, every process that can serve a volume reads the v1.1 format, whatever report blockmaster received
last.
- v1.1.3 carries the process identity on every lease renewal and at the finalize, which removes this rule.
Then:
```sh
sw-block cluster finalize-format --master 127.0.0.1:9180 --json
@@ -624,10 +675,21 @@ writing the v1.0 format until you finalize. Until then you can go back.
- **Refused** (exit 2, `FORMAT_HOSTS_TOO_OLD`) while a holder still runs v1.0.x. That holder reports format
level 0 and is named in `hosts` (for example `"reported":"volume v1 reads level 0"`). Upgrade it, or move its
volume, and run the finalize again.
- **`listed`** names the hosts the master cannot confirm but that do not block the finalize: a held volume with no
report or a stale one, a host with no report, and an old process that holds no volume.
- A process with a possibly-live lease must have reported reading level 1. No report or an old report from a
serving process refuses the finalize and names its host and volume. A clean ACKed release and a lease proven
ended are excluded from this serving check; a placement alone is not proof of serving. During the durable
finalize and after level 1 commits, first serving deadlines and all renewal paths require the current process's
level-1 report. A replacement old process cannot extend a live lease; capable renewals remain nonblocking.
Moves and authority publication may place an unreported target; an issued move does not permit serving.
The target starts, reports, and obtains a checked renewal reply before it serves.
- **`listed`** names other hosts the master cannot confirm but that do not block the finalize: an unserved
placement with no report, a host with no work or report, or a stale capable report.
- **Persistence fault.** If the attestation replacement may have landed, blockmaster retains the admission
intent and exits 74 so its supervisor restarts from disk. Run it under a restarting supervisor.
ERROR delivery is best effort if logging is blocked; termination remains bounded. Inspect `format-level`
after recovery before retrying. A failure before replacement leaves level 0 and can be retried.
- **Exit codes:** **0** finalized or already finalized; **2** refused; **75** blockmaster unreachable, retry; **1**
any other failure (the level is unchanged).
any other failure. After a persistence fault the recovered level may be 0 or 1.
- **JSON only.** The typed codes (`FORMAT_HOSTS_TOO_OLD`, and `HOST_HOLDS_WORK` below) appear only with `--json`.
Plain output says `refused`.
@@ -33,8 +33,7 @@ writing guest:
`sw-block ops volumes --master-api <addr> -o json`, and if the primary moved, repeat the failover against it. A
read shows the line at that moment only: blockmaster applies the queued rebalance when its assignment queue reaches
it, not at a fixed time, so the primary can still move after any read, and the guest is then started again on the
new primary (item 4). Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line
moved after it was decided.
new primary (item 4).
**Planned for a later release.** Supported replicated volumes are planned for a later release; v1.1.x keeps every replicated
configuration a preview. Replicated volumes are a preview: a primary cut off from the block master is not stopped
+1 -1
View File
@@ -57,7 +57,7 @@ v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored fo
- Affects replicated volumes (preview) whose acknowledgement profile allows a planned move: `sync-all`, or `sync-quorum` with two replicas.
- blockmaster may decide an automatic rebalance, which moves the primary to a less loaded server, just before an operator's `sw-block ops failover`. If that rebalance is applied after the failover, it moves the primary again, away from the replica the operator chose.
- No acknowledged write is lost: under these profiles every replica holds every acknowledged write.
- What to do: after `sw-block ops failover`, read the volume's line with `sw-block ops volumes --master-api <addr> -o json`; if `primary_replica` moved again, repeat the failover with `--expect-current <primary_replica>@<epoch>`. No read confirms that the primary stays: blockmaster applies the queued rebalance when its assignment queue reaches it, not at a fixed time, so it can still move the primary after any read, and the guest is then started again on the new primary. Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line moved after it was decided, so one decided before an operator's failover is no longer applied after it. A rebalance decided after the failover can still move the primary, as any rebalance can.
- What to do: after `sw-block ops failover`, read the volume's line with `sw-block ops volumes --master-api <addr> -o json`; if `primary_replica` moved again, repeat the failover with `--expect-current <primary_replica>@<epoch>`. No read confirms that the primary stays: blockmaster applies the queued rebalance when its assignment queue reaches it, not at a fixed time, so it can still move the primary after any read, and the guest is then started again on the new primary. A fix is planned for a later v1.1.x release.
## Known issue: resuming an interrupted snapshot delete can stop the volume's snapshot deletes and cleaning
+29 -9
View File
@@ -2,19 +2,39 @@
v1.1.2 is not yet released.
## Fixed
- **Replicated volumes (preview): a queued rebalance no longer undoes an operator failover.** blockmaster's automatic
rebalance and failover name the volume's line they were decided against, and blockmaster refuses one when that line
moved since (another replica or epoch, or other addresses). A rebalance decided just before `sw-block ops failover`
is no longer applied after it. This was a v1.1.1 known issue.
## Known issue: blockmaster restart can stall on a busy filesystem
- **Trigger:** blockmaster's state directory or its ancestors share a filesystem with heavy writes, such as the holders' local data.
- **Effect:** blockmaster's start syncs its state directories, which can wait for the filesystem journal. When the import has changed records, it also runs a `syncfs` for each store with changed records on ext4, XFS, btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders' data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes); this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then granted again on the same holder, with its data. A forced move during that time can lose writes after the last published HEAD (see [forced move](../volume-lifecycle.md#after-a-crash)).
- **What to do:** keep the holders' data off both the state directory's filesystem and the filesystem holding its ancestor directories. In practice, put the holders' data on its own filesystem, not the root filesystem. A different directory on the same filesystem is not enough. A dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestors up to `/`, including `/var/lib` and `/var` with the shipped layout. Restart blockmaster at low write load on all those filesystems. This limitation also applies when the cluster spec has not changed.
## Lifecycle persistence failures
## Format finalize
A blockmaster lifecycle put, import or open-barrier persistence failure exits with durability-unknown status 74 instead of generic status 1. Both immediate termination and the one-second fallback use that status. The best-effort ERROR diagnostic names `lifecycle_persist_failed`. Run blockmaster under supervision so a failed process restarts from durable state; record ordering, recovery barriers and import syncfs selection are unchanged.
`sw-block cluster finalize-format` now refuses with `FORMAT_HOSTS_TOO_OLD` (exit 2), naming the host and volume,
if a possibly-serving process has not reported reading level 1. Silence and a stale level-0 report do not prove
that the holder stopped. Upgrade and report from that holder before retrying. A clean release excludes its lease
from the serving check, but a retained placement with a fresh level-0 report still blocks the host-side check;
move that placement away or upgrade the placed process and report level 1 before retrying.
The serving check excludes clean ACKed releases and leases proven ended; an unserved placement needs no report.
First serving deadlines, re-grants and live renewals require the latest level-1 report blockmaster received for
the volume during finalize and after level 1 commits. A v1.1.2 volume process renews only after blockmaster has
answered its own first heartbeat, and an old process's own report refuses its renewals once it lands. A delayed
report can still stand in for a newer process, so the host-verified operator rule below is what keeps the finalize
safe in that case (stated, not closed in v1.1.2). Capable processes renew without waiting for the store write. This changes no persisted format or rollback-before-finalize rule.
Moves and authority publication remain placement: an unknown target may be placed; only a known-old report refuses it.
An issued move record alone permits no serving. The target must report and get an accepted renewal reply first.
If finalize fails after replacing its attestation file, blockmaster exits 74 so its supervisor restarts
from disk. ERROR delivery is best effort if logging is blocked; termination remains bounded. Run blockmaster
under a restarting supervisor and inspect `format-level` after recovery. Failures before replacement leave
level 0 and may be retried.
- **Format finalize: operator rule.** From the end of the upgrade until `sw-block cluster finalize-format` completes:
- no v1.0.x volume process may run or start on any host. Check it on each host from the running processes
(`/proc/<pid>/exe --version`) and the units' binaries, each printing exactly the revision of the v1.1.x binary
you installed with `modified=false`, not from blockmaster;
- wait 30 seconds after the last volume process start before finalizing.
The finalize now refuses while a serving volume process reports an older read level. A delayed heartbeat report
can still stand in for a newer process, and the rule covers that case. v1.1.3 removes the rule. See the
operations manual.
+1
View File
@@ -198,6 +198,7 @@ core/frontend/nvmerdma/target.go providerBackend.Sync context.WithTimeout 1 per-
core/frontend/ublk/device_linux.go openWhenPresent time.Now().Add 1 per-call NONE: no model row maps this file yet one ublk device open wait
core/frontend/ublk/lifecycle.go settleQueues time.NewTimer 1 per-call NONE: no model row maps this file yet one bounded wait
core/frontend/write_budget.go WithWriteBudget context.WithDeadline 1 per-call NONE: no model row maps this file yet one guest write command's budget
core/host/master/format_gate.go Host.failUncertainFormatFinalize time.AfterFunc 1 availability-contract FormatGate.Finalize one-second fail-stop fallback independent of a blocked diagnostic sink
core/host/master/host.go New http.Server.ReadHeaderTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/host/master/host.go New http.Server.ReadTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/host/master/host.go New http.Server.WriteTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
Can't render this file because it contains an unexpected character in line 50 and column 123.