Merge remote-tracking branch 'origin/main' into ci/g4-planned-handoff

# Conflicts:
#	.github/workflows/test.yml
This commit is contained in:
pingqiu committed 2026-11-22 06:29:53 -08:00
commit 8bf4428682
86 files changed
+3593 -901

No files matched your search

+7 -5
View File
@@ -82,16 +82,18 @@ jobs:
fi
done
fi
go test -p=1 -short -count=1 -timeout 10m $pkgs
# 20m per package: core/storage alone took 602 s on tp04 on main
# (2026-11-22), past the old 10m, so any PR touching it failed.
go test -p=1 -short -count=1 -timeout 20m $pkgs
- name: Test planned hand-over (real binaries)
# The documented standalone planned hand-over and its refused clean
# move without the ACK (cmd/blockvolume TestStandalone*, build tags
# subprocess and chunkstore_integration, so the default pass above is
# unchanged) run real blockmaster, blockvolume and sw-block against a
# pinned SeaweedFS release. The release archive is checked against its sha256 before
# every use, also when taken from the runner's cache; a mismatch fails
# the step. Nothing else is fetched.
# pinned SeaweedFS release. The release archive is checked against its
# sha256 before every use, also when taken from the runner's cache; a
# mismatch fails the step. Nothing else is fetched.
env:
WEED_VERSION: "4.53"
WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d
@@ -109,4 +111,4 @@ jobs:
bin="$RUNNER_TEMP/weed-$WEED_VERSION"
mkdir -p "$bin"
tar -xzf "$tgz" -C "$bin" weed
CHUNKSTORE_WEED="$bin/weed" go test -tags 'subprocess chunkstore_integration' -count=1 -timeout 10m -run '^TestStandalone(PlannedHandoffToTheSameHost|CleanMoveWithoutTheACKIsRefused)$' ./cmd/blockvolume/
CHUNKSTORE_WEED="$bin/weed" go test -tags 'subprocess chunkstore_integration' -count=1 -timeout 10m -run '^TestStandalone(PlannedHandoffToTheSameHost|CleanMoveWithoutTheACKIsRefused)$' ./cmd/blockvolume/
+3
View File
@@ -30,3 +30,6 @@ coverage.out
# MkDocs engineering wiki build output
/site/
# Windows builds of the binaries (never committed)
/*.exe
+5 -1
View File
@@ -678,7 +678,11 @@ func run(f flags) int {
cfg.ChunkHolder = chunkHolder(f)
cfg.ChunkStagger = true
if f.chunk.hostLimit.Directory != "" {
limiter, limitErr := hostlimit.New(f.chunk.hostLimit)
limitErr := hostlimit.CheckLaunch(f.chunk.hostLimit)
var limiter *hostlimit.Limiter
if limitErr == nil {
limiter, limitErr = hostlimit.New(f.chunk.hostLimit)
}
if limitErr != nil {
chunkErr = errors.Join(chunkErr, limitErr)
} else {
@@ -166,7 +166,7 @@ func TestBinaryReplicationIngressFollowsAssignedSlots(t *testing.T) {
ingressRefused(t, data)
ingressRefused(t, dual)
fact := func(e uint64, peers []*control.ReplicaDescriptor) *control.AssignmentFact {
return &control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers}
return &control.AssignmentFact{ServerId: "s1", VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers}
}
m.facts <- fact(1, nil)
ingressWait(t, "RF1 assignment not applied", func() bool { return epoch(1) })
@@ -64,7 +64,7 @@ func seedForcedVolume(t *testing.T, h *master.Host) {
t.Fatal("no authority line for vol-f")
}
}
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
t.Fatal(err)
}
}
@@ -45,7 +45,7 @@ func TestWorkspacePlannedHandoffAgainstRealMaster(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// This is the separate host event, never synthesized by the CLI.
_, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9})
_, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9})
if err != nil {
t.Fatal(err)
}
+4
View File
@@ -23,6 +23,10 @@ import (
// AssignmentInfo is a raw assignment from the master heartbeat.
type AssignmentInfo struct {
// ServerID is immutable for a moved authority line; an unknown moved
// owner remains empty instead of falling back to placement.
ServerID string
OwnerFromMove bool
VolumeID string
ReplicaID string
Epoch uint64
@@ -0,0 +1,26 @@
package authority
import "github.com/seaweedfs/seaweed-block/core/adapter"
// captureAssignmentOwner binds owner and line in one publication under p.mu
// (INV-AUTH-HOLDER-IDENTITY-001). Reload derives it from that same durable
// record's journal. A reserved/unissued move never permits placement fallback.
func (p *Publisher) captureAssignmentOwner(info *adapter.AssignmentInfo, issuing *WorkspaceState) {
state := issuing
if state == nil {
state = p.workspace[info.VolumeID]
}
if state == nil {
return
}
for _, move := range state.Moves {
if move.NewReplicaID == info.ReplicaID && move.NewEpoch == info.Epoch {
info.OwnerFromMove = true
info.ServerID = ""
if move.Issued {
info.ServerID = move.NewHost
}
return
}
}
}
@@ -0,0 +1,25 @@
package authority
import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"testing"
)
// INV-AUTH-HOLDER-IDENTITY-001: an unissued move cannot authorize a
// placement fallback, while a published move captures its own target.
func TestAssignmentOwnerReservedAndIssuedCapture(t *testing.T) {
p := NewPublisher(nil)
state := &WorkspaceState{Moves: []WorkspaceMoveRecord{{NewReplicaID: "r1", NewEpoch: 2, NewHost: "s2"}}}
for _, issued := range []bool{false, true} {
state.Moves[0].Issued = issued
info := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}
p.captureAssignmentOwner(&info, state)
want := ""
if issued {
want = "s2"
}
if !info.OwnerFromMove || info.ServerID != want {
t.Fatalf("issued=%t: captured %+v", issued, info)
}
}
}
+5 -1
View File
@@ -275,7 +275,7 @@ func (p *Publisher) reloadFromStore() {
p.workspace[rec.VolumeID] = cloneWorkspace(rec.Workspace)
}
key := subKey{volumeID: rec.VolumeID, replicaID: rec.ReplicaID}
p.state[key] = assignmentState{
loaded := assignmentState{
info: adapter.AssignmentInfo{
VolumeID: rec.VolumeID,
ReplicaID: rec.ReplicaID,
@@ -286,6 +286,8 @@ func (p *Publisher) reloadFromStore() {
},
present: true,
}
p.captureAssignmentOwner(&loaded.info, rec.Workspace)
p.state[key] = loaded
if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] {
p.writeSeqByVolume[rec.VolumeID] = rec.WriteSeq
}
@@ -586,6 +588,8 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
// sequenced after Put: on Put failure we simply return without
// touching p.state / p.writeSeqByVolume, so no rollback is
// needed. Subscribers never see a fact that isn't durable yet.
p.captureAssignmentOwner(&next, issuedWorkspace)
if p.store != nil {
// Compute the per-volume WriteSeq for this mint. Starts
// at the highest previously-persisted value for the
@@ -12,18 +12,19 @@ import (
// p.mu -> leaseMu at every point where an input changes, so that whenever
// p.mu is released the view equals derive(published) (INV-LEASE-VIEW-001).
type leaseDerived struct {
bound bool // an authority line exists for the volume
replica string
epoch uint64
issuedHost string // NewHost of the issued move that minted the line; "" if none
leasePresent bool
revoking bool
movePending bool // the last workspace move is reserved, not issued
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
storeless bool
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
maxSkewNS int64
lease WorkspaceLease // the published (durable) lease
bound bool // an authority line exists for the volume
replica string
epoch uint64
ownerFromMove bool
issuedHost string // NewHost of the issued move that minted the line; "" if none
leasePresent bool
revoking bool
movePending bool // the last workspace move is reserved, not issued
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
storeless bool
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
maxSkewNS int64
lease WorkspaceLease // the published (durable) lease
}
// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu.
@@ -43,14 +44,10 @@ 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.issuedHost, d.ownerFromMove = line.info.ServerID, line.info.OwnerFromMove
}
if s := p.workspace[volume]; s != nil {
d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued
for _, r := range s.Moves {
if d.bound && r.Issued && r.NewReplicaID == d.replica && r.NewEpoch == d.epoch {
d.issuedHost = r.NewHost
}
}
if s.Lease != nil {
d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease
d.maxSkewNS = int64(p.workspaceSkew(s.Lease))
@@ -154,7 +151,21 @@ type PublishedLine struct {
Epoch uint64
// IssuedHost is the target host of the issued move that minted this line;
// "" when no issued move did (a placement or static topology line).
IssuedHost string
IssuedHost string
OwnerFromMove bool
}
// PublishedAuthorityLine reads one committed line under leaf leaseMu. Identity
// checks on renewal must not wait for p.mu, which spans authority store I/O
// (INV-LEASE-VIEW-001, INV-WS-RENEW-NONBLOCKING-001).
func (p *Publisher) PublishedAuthorityLine(volume string) (PublishedLine, bool) {
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
lv := p.leaseViews[volume]
if lv == nil || !lv.d.bound {
return PublishedLine{}, false
}
return PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost, OwnerFromMove: lv.d.ownerFromMove}, true
}
// PublishedAuthorityLines returns the committed authority line of every
@@ -168,7 +179,7 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
out := make(map[string]PublishedLine, len(p.leaseViews))
for volume, lv := range p.leaseViews {
if lv.d.bound {
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost}
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost, OwnerFromMove: lv.d.ownerFromMove}
}
}
return out
+12 -1
View File
@@ -86,7 +86,18 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) {
if err != nil || again != r {
t.Fatal("grant replay changed", again, err)
}
final := NewPublisher(nil, WithStore(disk)).WorkspaceState("v")
finalPublisher := NewPublisher(nil, WithStore(disk))
for name, publisher := range map[string]*Publisher{"issued": loaded, "reloaded": finalPublisher} {
line, ok := publisher.LastPublished("v", "old")
if !ok || line.ServerID != "new-node" || !line.OwnerFromMove {
t.Fatalf("%s lost captured moved owner: %+v", name, line)
}
published, _ := publisher.PublishedAuthorityLine("v")
if published.IssuedHost != line.ServerID || !published.OwnerFromMove {
t.Fatalf("%s lease and stream owners differ: %+v / %+v", name, published, line)
}
}
final := finalPublisher.WorkspaceState("v")
if final == nil || len(final.Moves) != 1 || !final.Moves[0].Issued {
t.Fatal("issued epoch lost journal", final)
}
+62 -6
View File
@@ -145,6 +145,13 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
if resp == nil {
return PublishTarget{}, false
}
if fronts, tagged := primaryOwnedFrontends(resp, rejectLoopback); tagged {
if len(fronts) == 0 {
return PublishTarget{}, false
}
resp = &control.StatusResponse{VolumeId: resp.GetVolumeId(), ReplicaId: resp.GetReplicaId(), Epoch: resp.GetEpoch(),
EndpointVersion: resp.GetEndpointVersion(), Assigned: resp.GetAssigned(), Frontends: fronts}
}
base := PublishTarget{
VolumeID: resp.GetVolumeId(),
ReplicaID: resp.GetReplicaId(),
@@ -161,20 +168,23 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
if ft.GetProtocol() != string(ProtocolISCSI) || ft.GetAddr() == "" || ft.GetIqn() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback) {
continue
}
if _, ok := iscsiByIQN[ft.GetIqn()]; !ok {
iscsiOrder = append(iscsiOrder, ft.GetIqn())
// one multipath target is one IQN AND LUN: paths to another LUN of the same IQN are another unit
// (INV-AUTH-HOLDER-IDENTITY-001)
key := ft.GetIqn() + "\x00" + strconv.FormatUint(uint64(ft.GetLun()), 10)
if _, ok := iscsiByIQN[key]; !ok {
iscsiOrder = append(iscsiOrder, key)
}
iscsiByIQN[ft.GetIqn()] = append(iscsiByIQN[ft.GetIqn()], ft)
iscsiByIQN[key] = append(iscsiByIQN[key], ft)
}
for _, iqn := range iscsiOrder {
frontends := iscsiByIQN[iqn]
for _, key := range iscsiOrder {
frontends := iscsiByIQN[key]
if len(frontends) == 0 {
continue
}
out := base
out.Protocol = ProtocolISCSI
out.ISCSIAddr = frontends[0].GetAddr()
out.IQN = iqn
out.IQN = frontends[0].GetIqn()
out.LUN = frontends[0].GetLun()
if len(frontends) > 1 {
out.Multipath = true
@@ -247,6 +257,52 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
return PublishTarget{}, false
}
// primaryOwnedFrontends applies INV-AUTH-HOLDER-IDENTITY-001 when the master tags each frontend with its replica: the
// usable frontends of the primary replica come first, and another replica's frontend is kept only as an extra path to a
// target the primary itself serves (same IQN and LUN, or same NQN/NSID/transport). No usable primary frontend: none at all, so
// a supporting replica is never published under the primary identity. An untagged (older) response is returned as is.
func primaryOwnedFrontends(resp *control.StatusResponse, rejectLoopback bool) ([]*control.FrontendTarget, bool) {
tagged := false
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() != "" {
tagged = true
}
}
if !tagged {
return nil, false
}
key := func(ft *control.FrontendTarget) (string, bool) {
switch {
case ft.GetAddr() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback):
return "", false
case ft.GetProtocol() == string(ProtocolISCSI) && ft.GetIqn() != "":
return "iscsi\x00" + ft.GetIqn() + "\x00" + strconv.FormatUint(uint64(ft.GetLun()), 10), true // IQN AND LUN
case ft.GetProtocol() == string(ProtocolNVMe) && ft.GetNqn() != "":
return "nvme\x00" + ft.GetNqn() + "\x00" + strconv.FormatUint(uint64(ft.GetNsid()), 10) + "\x00" +
string(normalizeFrontendTransport(ProtocolNVMe, FrontendTransport(ft.GetTransport()))), true
}
return "", false
}
var out []*control.FrontendTarget
served := map[string]bool{}
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() == resp.GetReplicaId() {
if k, ok := key(ft); ok {
served[k] = true
out = append(out, ft)
}
}
}
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() != resp.GetReplicaId() {
if k, ok := key(ft); ok && served[k] {
out = append(out, ft)
}
}
}
return out, true
}
func rejectFrontendAddr(addr string, rejectLoopback bool) bool {
if !rejectLoopback {
return false
@@ -0,0 +1,67 @@
package csi
import (
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// INV-AUTH-HOLDER-IDENTITY-001: with replica-tagged frontends, a target is published only when the primary replica has a
// usable frontend; another replica's frontend is at most an extra path to the primary's own target. Untagged responses
// (an older master) keep the previous first-usable behaviour.
func TestPublishTargetIsPrimaryOwned(t *testing.T) {
ft := func(replica, addr, iqn string) *control.FrontendTarget {
return &control.FrontendTarget{Protocol: string(ProtocolISCSI), Addr: addr, Iqn: iqn, ReplicaId: replica}
}
status := func(fronts ...*control.FrontendTarget) *control.StatusResponse {
return &control.StatusResponse{VolumeId: "v1", Assigned: true, ReplicaId: "r1", Epoch: 3, Frontends: fronts}
}
// the primary's only frontend is one CSI rejects (loopback): the supporting replica's must not stand in
if got, ok := publishTargetFromStatus(status(ft("r1", "127.0.0.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.v1")), false, true); ok {
t.Fatalf("rejected primary frontend: published %+v, want no target", got)
}
if got, ok := publishTargetFromStatus(status(ft("r1", "127.0.0.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.v1")), true, true); ok {
t.Fatalf("rejected primary frontend (multipath): published %+v, want no target", got)
}
// primary first; a supporting path to the SAME target joins only as a multipath path
got, ok := publishTargetFromStatus(status(ft("r2", "192.0.2.2:3260", "iqn.v1"), ft("r1", "192.0.2.1:3260", "iqn.v1")), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || !got.Multipath || len(got.ISCSIAddrs) != 2 || got.ISCSIAddrs[0] != "192.0.2.1:3260" {
t.Fatalf("multipath: %+v ok=%v, want the primary first with the supporting path", got, ok)
}
// a supporting frontend of ANOTHER target never joins
got, ok = publishTargetFromStatus(status(ft("r1", "192.0.2.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.other")), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.Multipath || got.IQN != "iqn.v1" {
t.Fatalf("foreign target: %+v ok=%v, want only the primary's", got, ok)
}
// iSCSI paths match on IQN AND LUN (codex01): a supporting q/LUN2 is another target, never a path to the primary's q/LUN1
lun := func(replica, addr string, n uint32) *control.FrontendTarget {
return &control.FrontendTarget{Protocol: string(ProtocolISCSI), Addr: addr, Iqn: "iqn.q", Lun: n, ReplicaId: replica}
}
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r2", "192.0.2.2:3260", 2)), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.LUN != 1 || got.Multipath || len(got.ISCSIAddrs) != 0 {
t.Fatalf("LUN mismatch: %+v ok=%v, want only the primary's q/LUN1 (no multipath)", got, ok)
}
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r2", "192.0.2.2:3260", 1)), true, false)
if !ok || got.LUN != 1 || !got.Multipath || len(got.ISCSIAddrs) != 2 || got.ISCSIAddrs[0] != "192.0.2.1:3260" {
t.Fatalf("nonzero LUN match: %+v ok=%v, want multipath primary-first at LUN 1", got, ok)
}
// two PRIMARY-owned units of one IQN (q/LUN1 at A, q/LUN2 at B) are two targets, never one multipath target with
// LUN1 for both (codex01: the final grouping binds IQN and LUN too)
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r1", "192.0.2.2:3260", 2)), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.LUN != 1 || got.Multipath || len(got.ISCSIAddrs) != 0 {
t.Fatalf("two primary units: %+v ok=%v, want q/LUN1 at 192.0.2.1 alone (no multipath with LUN2's path)", got, ok)
}
got, ok = publishTargetFromStatus(status(lun("", "192.0.2.1:3260", 1), lun("", "192.0.2.2:3260", 2)), true, false)
if !ok || got.LUN != 1 || got.Multipath {
t.Fatalf("untagged two units: %+v ok=%v, want q/LUN1 alone", got, ok)
}
// no primary frontend at all, supporting present: no target
if got, ok := publishTargetFromStatus(status(ft("r2", "192.0.2.2:3260", "iqn.v1")), false, false); ok {
t.Fatalf("no primary frontend: published %+v, want no target", got)
}
// untagged (older master): unchanged first-usable selection
got, ok = publishTargetFromStatus(status(ft("", "192.0.2.2:3260", "iqn.v1")), false, false)
if !ok || got.ISCSIAddr != "192.0.2.2:3260" {
t.Fatalf("untagged: %+v ok=%v, want the first usable frontend", got, ok)
}
}
@@ -0,0 +1,28 @@
package master
import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
"testing"
)
// INV-AUTH-HOLDER-IDENTITY-001 / TERM-HOLDER-001: fault injection at the
// stream encoder, not a claim that publisher ordering can emit an unissued
// line. The captured E2 publication is available while its journal is not.
func TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal(t *testing.T) {
h := &Host{boot: &bootstrap.DurableAuthorityBootstrap{Publisher: authority.NewPublisher(authority.NewStaticDirective(nil))}, topo: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{VolumeID: "v", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}}}}
for _, owner := range []string{"s2", ""} {
t.Run("owner="+owner, func(t *testing.T) {
info := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, ServerID: owner, OwnerFromMove: true}
fact := (&services{host: h}).assignmentFact(info)
if fact.ServerId != owner {
t.Fatalf("captured owner %q relabelled %q from placement while journal unavailable", owner, fact.ServerId)
}
})
}
initial := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
if got := (&services{host: h}).assignmentFact(initial).ServerId; got != "s1" {
t.Fatalf("move-less initial placement owner: %q", got)
}
}
@@ -42,7 +42,7 @@ func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.
if line.Epoch != 1 || line.ReplicaID != "r1" {
t.Fatalf("fixture authority line: %+v", line)
}
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: vol, ReplicaId: "r1", Epoch: 1}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatal(err)
}
@@ -311,8 +311,8 @@ func TestStatusReportsExtensionWriteLatency(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err) // first grant: not an extension
}
get := func() map[string]any {
@@ -329,7 +329,7 @@ func TestStatusReportsExtensionWriteLatency(t *testing.T) {
t.Fatalf("before any extension: %v", b)
}
time.Sleep(8 * time.Second)
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err)
}
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
@@ -122,7 +122,8 @@ func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, pl
volume.Replicas = replicas
volume.ObservedReplicas = countObservedReplicas(replicas)
if volume.PrimaryReplica != "" {
volume.PrimaryNode = serverForReplica(placement, volume.PrimaryReplica)
// the server on the authority line (issued holder), not placement (INV-AUTH-HOLDER-IDENTITY-001)
volume.PrimaryNode = h.workspaceSourceHost(volumeID, line.ReplicaID, line.Epoch)
volume.PublishTarget = publishTargetForReplica(replicas, volume.PrimaryReplica)
}
@@ -230,7 +231,15 @@ func (h *Host) observationReplicas(volumeID string, placement lifecycle.Placemen
replica.Role = "primary"
replica.ReplicationRole = "primary"
}
if fact, ok := h.ObservationHost().Store().SlotFact(volumeID, replicaID); ok {
fact, ok := h.ObservationHost().Store().SlotFact(volumeID, replicaID)
if hasLine && line.Assigned && replicaID == line.ReplicaID {
// the whole primary row is the line's server: its identity, evidence and frontend
// (INV-AUTH-HOLDER-IDENTITY-001); never placement's server carrying the holder's frontend
var holder string
holder, fact, ok = h.holderSlotFact(volumeID, replicaID, line.Epoch)
replica.ServerID, replica.KubernetesNode = holder, holder
}
if ok {
replica.Observed = true
replica.CandidateReady = fact.ReadyForPrimary
replica.CandidateReadyReason = candidateReason(fact.ReadyForPrimary)
@@ -0,0 +1,106 @@
package master
import (
"context"
"fmt"
"net"
"strings"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/peer"
)
// addrHost is the host part of a host:port (or bare host) address.
func addrHost(addr string) string {
if h, _, err := net.SplitHostPort(addr); err == nil {
return h
}
return strings.TrimSpace(addr)
}
// registryHosts is the host set the node registry records for serverID (data, ctrl and plain addresses) and the host
// named in refusals; ok is false when serverID has no registry record.
func (h *Host) registryHosts(serverID string) (hosts map[string]bool, named string, ok bool) {
if h.lifecycle == nil || h.lifecycle.Nodes == nil || serverID == "" {
return nil, "", false
}
reg, ok := h.lifecycle.Nodes.GetNodeSnapshot(serverID) // committed snapshot: never the store mutex (INV-WS-RENEW-NONBLOCKING-001)
if !ok {
return nil, "", false
}
hosts = map[string]bool{}
for _, a := range []string{reg.DataAddr, reg.CtrlAddr, reg.Addr} {
if a != "" {
hosts[addrHost(a)] = true
}
}
named = addrHost(reg.DataAddr)
if named == "" {
named = addrHost(reg.Addr)
}
return hosts, named, true
}
// refuseServerIDFromOtherHost is the observation half of INV-AUTH-HOLDER-IDENTITY-001: a heartbeat whose slot addresses
// are on a host other than the one registered for its server id is refused before its slots reach the observations.
// Only the host part is compared (each volume process listens on its own ports); several server ids on one host stay
// allowed; an id with no registry record is not checked here (no first-seen binding in v1.0: host addresses change).
func (h *Host) refuseServerIDFromOtherHost(r *control.HeartbeatReport) error {
hosts, named, ok := h.registryHosts(r.ServerId)
if !ok || len(hosts) == 0 {
return nil
}
for _, s := range r.Slots {
for _, a := range []string{s.DataAddr, s.CtrlAddr} {
if a != "" && !hosts[addrHost(a)] {
return fmt.Errorf("heartbeat: server id %s is registered on host %s; refused from %s (volume %s replica %s): one server id names one host",
r.ServerId, named, addrHost(a), s.VolumeId, s.ReplicaId)
}
}
}
return nil
}
// peerHost is the host part of a gRPC call's network peer; "" when the call carries none.
func peerHost(ctx context.Context) string {
p, ok := peer.FromContext(ctx)
if !ok || p.Addr == nil {
return ""
}
return addrHost(p.Addr.String())
}
// refuseWorkspaceHolderHost is the holder half of INV-AUTH-HOLDER-IDENTITY-001 for workspace volumes (lease renew, ACK,
// assignment stream): the server id must be registered (no first-seen binding), and the call's network peer must be on
// the host the registry records for it. Limits: it trusts the network peer address (no NAT or proxy between volume and
// master in OSS), and it is not authentication. Every refusal is logged.
func (h *Host) refuseWorkspaceHolderHost(ctx context.Context, rpc, server string) error {
hosts, named, ok := h.registryHosts(server)
var err error
switch ph := peerHost(ctx); {
case !ok:
err = fmt.Errorf("%s: server id %q is not registered; a workspace holder's server id must be", rpc, server)
case ph == "" || !hosts[ph]:
if ph == "" {
ph = "an unknown peer"
}
err = fmt.Errorf("%s: server id %s is registered on host %s; refused from %s: one server id names one host", rpc, server, named, ph)
}
if err != nil {
h.log.Print(err)
}
return err
}
// holderSlotFact is the slot fact of replica on the server the authority line names (workspaceSourceHost); a
// same-replica claim from any other server, however fresh, is never used (INV-AUTH-HOLDER-IDENTITY-001).
// No resolvable holder: no fact (fail closed).
func (h *Host) holderSlotFact(volumeID, replicaID string, epoch uint64) (string, authority.SlotFact, bool) {
holder := h.workspaceSourceHost(volumeID, replicaID, epoch)
if holder == "" || h.obs == nil {
return holder, authority.SlotFact{}, false
}
fact, ok := h.obs.Store().SlotFactOnServer(holder, volumeID, replicaID)
return holder, fact, ok
}
@@ -0,0 +1,453 @@
package master
import (
"context"
"errors"
"fmt"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/csi"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// INV-AUTH-HOLDER-IDENTITY-001: after an issued workspace move the authority line is on the new host while the placement
// slot may still name the old one. The displayed primary node, its publish target and the CSI portal follow the ISSUED
// holder; the old host, still reporting the replica id with a newer observation, wins none of them.
func TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot(t *testing.T) {
heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}}
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }})
if err != nil {
t.Fatal(err)
}
m.Start()
defer closeTestMaster(t, m)
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
ws, lc, obs := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn), control.NewObservationServiceClient(conn)
for _, n := range []struct{ id, d, c string }{{"node-a", "127.0.0.1:19101", "127.0.0.1:19102"}, {"node-b", "127.0.0.1:19301", "127.0.0.1:19302"}} {
if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: n.d, CtrlAddr: n.c}); err != nil {
t.Fatal(err)
}
}
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "a2", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "a2", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "a2", ServerID: "node-b", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := obs.ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "a2", ReplicaId: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}}}); err != nil {
t.Fatal(err)
}
if _, err := m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
a2 := waitAuthorityLine(t, m.Publisher(), "a2")
id := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
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" {
t.Fatalf("move to node-a: %+v %v", g, err)
}
line, _ := m.Publisher().VolumeAuthorityLine("a2")
if p, ok := m.Lifecycle().Placements.GetPlacementSnapshot("a2"); ok {
t.Logf("placement after the move: %+v (the displayed primary must not depend on it)", p.Slots)
}
fact := func(server, host string, at time.Time) authority.Observation {
return authority.Observation{ServerID: server, ObservedAt: at, Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "a2", ReplicaID: "r1", DataAddr: host + ":19111", CtrlAddr: host + ":19112",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 10,
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: host + ":3260", IQN: "iqn.2026-05.io.seaweedfs:a2", LUN: 1}}}}}
}
now := time.Now().UTC()
if holder := m.workspaceSourceHost("a2", line.ReplicaID, line.Epoch); holder != "node-a" {
t.Fatalf("issued holder %q, want node-a (line %+v)", holder, line)
}
lookup := csi.NewControlStatusLookup(control.NewEvidenceServiceClient(conn))
// only the old host reports the replica: no primary evidence from the issued holder, so no portal at all
if err := m.ObservationHost().Ingest(fact("node-b", "192.0.2.9", now.Add(time.Second))); err != nil {
t.Fatal(err)
}
if target, err := lookup.LookupPublishTarget(ctx, "a2", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("CSI lookup with only the old host's claim: target %+v err %v, want ErrPublishTargetNotFound", target, err)
}
if err := m.ObservationHost().Ingest(fact("node-a", "127.0.0.1", now)); err != nil {
t.Fatal(err)
}
if target, err := lookup.LookupPublishTarget(ctx, "a2", ""); err != nil || !strings.Contains(fmt.Sprintf("%+v", target), "127.0.0.1:3260") || strings.Contains(fmt.Sprintf("%+v", target), "192.0.2.9") {
t.Fatalf("CSI lookup: target %+v err %v, want the issued holder's 127.0.0.1:3260", target, err)
}
var vol *struct{ node, target, rowServer, rowNode, rowFrontend string }
for _, v := range m.ObservationSnapshot(time.Now().UTC()).Volumes {
if v.VolumeID == "a2" {
vol = &struct{ node, target, rowServer, rowNode, rowFrontend string }{node: v.PrimaryNode, target: v.PublishTarget}
for _, r := range v.Replicas {
if r.ReplicaID == line.ReplicaID {
vol.rowServer, vol.rowNode, vol.rowFrontend = r.ServerID, r.KubernetesNode, r.FrontendAddr
}
}
}
}
// the whole primary row is the issued holder (codex01 P2): never placement's node-b carrying node-a's frontend
if vol == nil || vol.node != "node-a" || vol.target != "127.0.0.1:3260" || vol.rowServer != "node-a" || vol.rowNode != "node-a" || vol.rowFrontend != "127.0.0.1:3260" {
t.Fatalf("displayed primary %+v, want node-a at 127.0.0.1:3260 in the volume and its primary row (the issued holder, not the placement slot or the old host)", vol)
}
resp, err := newServices(m).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "a2"})
if err != nil || len(resp.Frontends) == 0 || resp.Frontends[0].Addr != "127.0.0.1:3260" {
t.Fatalf("CSI portal %v %v, want the issued holder's 127.0.0.1:3260", resp.GetFrontends(), err)
}
}
// heartbeatFrom sends a heartbeat for server whose slot addresses are on host.
func (r *isolationRig) heartbeatFrom(server, host string) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: host + ":19611", CtrlAddr: host + ":19612"}}})
return err
}
// INV-AUTH-HOLDER-IDENTITY-001: OSS has no host authentication, so a server id names a host only if the master
// refuses that id from any host other than the one registered for it. Two processes started with the same --server-id
// on different hosts: the one on the registered host is accepted, the other is refused, and it never enters the
// observations (a copied config cannot borrow the registered host's holder identity).
func TestServerIDRefusedFromAHostOtherThanItsRegisteredOne(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a is registered on 127.0.0.1
if err := r.heartbeatFrom("node-a", "127.0.0.1"); err != nil {
t.Fatalf("heartbeat from node-a's registered host refused: %v", err)
}
err := r.heartbeatFrom("node-a", "127.0.0.2")
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1") {
t.Fatalf("same --server-id from a second host: %v, want FailedPrecondition naming the registered host", err)
}
if slot, ok := r.m.ObservationHost().Store().SlotFactOnServer("node-a", "hb-node-a", "r-node-a"); !ok || !strings.HasPrefix(slot.DataAddr, "127.0.0.1:") {
t.Fatalf("refused heartbeat reached the observations: %+v ok=%v", slot, ok)
}
}
// INV-AUTH-HOLDER-IDENTITY-001: the CSI portal (QueryVolumeStatus frontends) and the displayed primary
// (ClusterStatus primary node and publish target) come from the server on the volume's authority line, never from
// whichever host sent the freshest heartbeat for the same replica id. A stale old host that still reports the
// primary's replica, even more recently, changes neither.
func TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
seedObservationSnapshotVolume(t, h)
seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01")
ingestObservationSnapshotRF3(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
line := waitAuthorityLine(t, h.Publisher(), "pvc-a")
holder := h.workspaceSourceHost("pvc-a", line.ReplicaID, line.Epoch)
own, ok := h.ObservationHost().Store().SlotFactOnServer(holder, "pvc-a", line.ReplicaID)
if holder == "" || !ok || len(own.Frontends) == 0 {
t.Fatalf("line %+v names holder %q with no observed frontend", line, holder)
}
holderAddr := own.Frontends[0].Addr
stale := ""
for _, server := range []string{"m01", "m02", "tp01"} { // the fixture's placement servers
if server != holder {
stale = server
break
}
}
// the stale host reports the primary's replica id with a newer observation than the holder's
if err := h.ObservationHost().Ingest(authority.Observation{ServerID: stale, ObservedAt: time.Now().UTC().Add(time.Second),
Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "pvc-a", ReplicaID: line.ReplicaID, DataAddr: "192.0.2.9:19101", CtrlAddr: "192.0.2.9:19102",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 99,
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: "192.0.2.9:3260", IQN: "iqn.2026-05.io.seaweedfs:pvc-a", LUN: 1}}}}}); err != nil {
t.Fatalf("ingest stale host: %v", err)
}
resp, err := newServices(h).QueryVolumeStatus(context.Background(), &control.StatusRequest{VolumeId: "pvc-a"})
if err != nil {
t.Fatalf("status: %v", err)
}
if len(resp.Frontends) == 0 || resp.Frontends[0].Addr != holderAddr {
t.Fatalf("CSI portal: frontends=%v, want the line server %s's %s first (stale host %s must not win)", resp.Frontends, holder, holderAddr, stale)
}
for _, ft := range resp.Frontends {
if ft.Addr == "192.0.2.9:3260" {
t.Fatalf("CSI portal lists the stale host's frontend: %v", resp.Frontends)
}
}
vol := h.ObservationSnapshot(time.Now().UTC()).Volumes[0]
if vol.PrimaryNode != holder || vol.PublishTarget != holderAddr {
t.Fatalf("displayed primary node=%q target=%q, want %q %q (line server, not the stale host %s)", vol.PrimaryNode, vol.PublishTarget, holder, holderAddr, stale)
}
}
// dialFrom opens a client connection to the rig's master whose source address is host (a real loopback address).
func (r *isolationRig) dialFrom(t *testing.T, host string) *grpc.ClientConn {
t.Helper()
d := net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP(host)}}
conn, err := grpc.NewClient(r.m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { return d.DialContext(ctx, "tcp", addr) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return conn
}
// INV-AUTH-HOLDER-IDENTITY-001, workspace path: two processes with the same --server-id on two real loopback hosts. The
// one not on the registered host (127.0.0.2) is refused at lease renew, at the revocation ACK and at the assignment
// stream (so it never receives the line to adopt), and each refusal is logged; an unregistered server id is refused at
// its first renew; the registered host is unaffected. The check trusts the network peer address (no NAT or proxy
// between volume and master in OSS); it is not authentication.
func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a registered on 127.0.0.1
r.createVolume(t, "w1")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w1", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "w1", ReplicaId: "r1", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}}}); err != nil {
t.Fatal(err)
}
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, r.m.Publisher(), "w1")
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "w1", ReplicaId: "r1", Epoch: line.Epoch}
other := r.dialFrom(t, "127.0.0.2")
wsOther, asnOther := control.NewWorkspaceServiceClient(other), control.NewAssignmentServiceClient(other)
refusedFrom2 := func(what string, err error) {
t.Helper()
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1; refused from 127.0.0.2") {
t.Fatalf("%s from 127.0.0.2 as node-a: %v, want the host refusal", what, err)
}
}
_, err := wsOther.RenewWorkspaceLease(r.ctx, id)
refusedFrom2("renew", err)
_, err = wsOther.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9})
refusedFrom2("ACK", err)
stream, err := asnOther.SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1", ServerId: "node-a"})
if err == nil {
_, err = stream.Recv()
}
refusedFrom2("assignment stream", err)
if n := strings.Count(r.logs.String(), "refused from 127.0.0.2"); n < 3 {
t.Fatalf("refusals logged %d times, want 3:\n%s", n, r.logs.String())
}
// the registered host is unaffected: it renews and receives the line
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("renew from the registered host: %v", err)
}
own, err := control.NewAssignmentServiceClient(r.dialFrom(t, "127.0.0.1")).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1", ServerId: "node-a"})
if err != nil {
t.Fatal(err)
}
if fact, err := own.Recv(); err != nil || fact.GetEpoch() != line.Epoch {
t.Fatalf("assignment stream from the registered host: %+v %v", fact, err)
}
// an unregistered server id is refused at its first renew; a stream naming no server id is refused too
_, err = r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{ServerId: "node-z", VolumeId: "w1", ReplicaId: "r1", Epoch: line.Epoch})
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), `server id "node-z" is not registered`) {
t.Fatalf("renew by an unregistered server id: %v, want the not-registered refusal", err)
}
anon := r.dialFrom(t, "127.0.0.1")
s2, err := control.NewAssignmentServiceClient(anon).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1"})
if err == nil {
_, err = s2.Recv()
}
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), `server id "" is not registered`) {
t.Fatalf("assignment stream with no server id: %v, want the not-registered refusal", err)
}
}
// loopbackPeer is ctx as an RPC from 127.0.0.1 arrives at the master (in-process service calls carry no peer).
func loopbackPeer(ctx context.Context) context.Context {
return peer.NewContext(ctx, &peer.Peer{Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000}})
}
// registerWorkspaceHolder registers server on 127.0.0.1 (a workspace holder must be registered).
func registerWorkspaceHolder(t *testing.T, h *Host, server string) {
t.Helper()
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:19901", CtrlAddr: "127.0.0.1:19902"}); err != nil {
t.Fatal(err)
}
}
// codex01 P1: a CSI client takes the first frontend as the primary. When the primary's evidence (from the line's server)
// is missing, the status lists NO frontend, even though supporting replicas report theirs; without the rule a
// supporting replica's frontend would be published under the primary identity.
func TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing(t *testing.T) {
obs := authority.NewObservationHost(authority.ObservationHostConfig{})
for _, r := range []struct{ server, replica, host string }{{"node-b", "r2", "127.0.0.2"}, {"node-c", "r3", "127.0.0.3"}} {
if err := obs.IngestHeartbeat(authority.HeartbeatMessage{ServerID: r.server, SentAt: time.Now().UTC(), Reachable: true, Eligible: true,
Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: r.replica, DataAddr: r.host + ":9201", CtrlAddr: r.host + ":9101",
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: r.host + ":3260", IQN: "iqn.2026-05.example:v1"}}}}}); err != nil {
t.Fatal(err)
}
}
noPrimary := func(replicaID string) (authority.SlotFact, bool) {
if replicaID == "r1" {
return authority.SlotFact{}, false // the line's server has no evidence for the primary
}
return obs.Store().SlotFact("v1", replicaID)
}
if got := statusFrontendsFor(obs, "v1", []string{"r1", "r2", "r3"}, true, "r1", noPrimary); len(got) != 0 {
t.Fatalf("primary evidence missing: frontends %v, want none (a supporting replica must not stand in for the primary)", got)
}
if got := statusFrontendsFor(obs, "v1", []string{"r1", "r2", "r3"}, true, "", noPrimary); len(got) != 2 {
t.Fatalf("control: without the primary rule the supporting frontends are listed (%v): the hazard this test pins", got)
}
}
// inProcEvidence is the CSI lookup's EvidenceService client wired straight to the master's QueryVolumeStatus.
type inProcEvidence struct{ s *services }
func (e inProcEvidence) QueryVolumeStatus(ctx context.Context, in *control.StatusRequest, _ ...grpc.CallOption) (*control.StatusResponse, error) {
return e.s.QueryVolumeStatus(ctx, in)
}
// codex01 #416 P1-2: through the real CSI ControlStatusLookup, with supporting replicas reporting usable frontends, no
// target is published when the primary's slot (on the line's server) exists but carries no frontend, or when its only
// frontend is one CSI rejects (loopback, with loopback targets rejected). Control: the same lookup without the loopback
// rejection publishes the primary's own frontend.
func TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
seedObservationSnapshotVolume(t, h)
seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01")
ingestObservationSnapshotRF3(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
line := waitAuthorityLine(t, h.Publisher(), "pvc-a")
holder := h.workspaceSourceHost("pvc-a", line.ReplicaID, line.Epoch)
reprimary := func(fronts []authority.FrontendTargetFact, at time.Time) {
t.Helper()
if err := h.ObservationHost().Ingest(authority.Observation{ServerID: holder, ObservedAt: at, Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "pvc-a", ReplicaID: line.ReplicaID, DataAddr: "192.0.2.1:19101", CtrlAddr: "192.0.2.1:19102",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 30, Frontends: fronts}}}); err != nil {
t.Fatal(err)
}
}
svc := newServices(h)
plain := csi.NewControlStatusLookup(inProcEvidence{svc})
noLoopback := csi.NewControlStatusLookupWithOptions(inProcEvidence{svc}, csi.WithLoopbackPublishTargetsRejected())
ctx := context.Background()
// (a) the primary slot exists on the holder but carries no frontend
reprimary(nil, time.Now().UTC().Add(time.Second))
if resp, err := svc.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "pvc-a"}); err != nil || len(resp.Frontends) != 0 {
t.Fatalf("primary slot without a frontend: status frontends %v err %v, want none", resp.GetFrontends(), err)
}
if target, err := plain.LookupPublishTarget(ctx, "pvc-a", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("primary slot without a frontend: CSI target %+v err %v, want ErrPublishTargetNotFound", target, err)
}
// (b) the primary's only frontend is loopback, which this CSI lookup rejects; supporting replicas are usable
reprimary([]authority.FrontendTargetFact{{Protocol: "iscsi", Addr: "127.0.0.1:3260", IQN: "iqn.2026-05.io.seaweedfs:pvc-a", LUN: 1}}, time.Now().UTC().Add(2*time.Second))
if target, err := noLoopback.LookupPublishTarget(ctx, "pvc-a", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("rejected primary frontend: CSI target %+v err %v, want ErrPublishTargetNotFound (no supporting stand-in)", target, err)
}
if target, err := plain.LookupPublishTarget(ctx, "pvc-a", ""); err != nil || target.ISCSIAddr != "127.0.0.1:3260" || target.ReplicaID != line.ReplicaID {
t.Fatalf("control: CSI target %+v err %v, want the primary's own 127.0.0.1:3260", target, err)
}
}
// codex01 #416 P2: a workspace volume being deleted is still a workspace volume: its assignment stream keeps the holder
// host check (a deletion reservation must not open a bypass).
func TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "w2")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w2", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w2", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if len(r.m.replicaSlotsFor("w2")) == 0 {
t.Fatal("fixture: w2 has no replica slot, the stream would fail before the host check")
}
if _, err := r.m.Lifecycle().Deletions.Admit("w2", "del-1"); err != nil {
t.Fatal(err)
}
stream, err := control.NewAssignmentServiceClient(r.dialFrom(t, "127.0.0.2")).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w2", ReplicaId: "r1", ServerId: "node-a"})
if err == nil {
_, err = stream.Recv()
}
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "refused from 127.0.0.2") {
t.Fatalf("deletion-reserved workspace volume, stream from another host: %v, want the host refusal", err)
}
}
// codex01 #416 P2 (INV-WS-RENEW-NONBLOCKING-001): a LIVE lease renewal through holderMatches, whose host check reads the
// node registry, completes while a registration write is held (the store mutex RegisterNode keeps across file I/O). The
// hold is proven real: a concurrent RegisterNode does not finish until it is released.
func TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a registered on 127.0.0.1
r.createVolume(t, "w3")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w3", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w3", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "w3", 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)
}
line := waitAuthorityLine(t, r.m.Publisher(), "w3")
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "w3", ReplicaId: "r1", Epoch: line.Epoch}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("first grant: %v", err)
}
release := r.m.Lifecycle().Nodes.HoldWritesForTest()
writer := make(chan struct{})
t.Cleanup(func() {
release()
select {
case <-writer:
case <-time.After(5 * time.Second):
t.Error("held registration writer did not join")
}
})
go func() {
defer close(writer)
_, _ = r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502"})
}()
ctx, cancel := context.WithTimeout(r.ctx, time.Second)
defer cancel()
if _, err := r.ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatalf("live renewal during a held registration write: %v (it must not wait on the registry store)", err)
}
select {
case <-writer:
t.Fatal("control: the registration write was not actually held")
default:
}
release()
select {
case <-writer:
case <-time.After(5 * time.Second):
t.Fatal("registration write did not finish after the release")
}
}
+63 -20
View File
@@ -292,6 +292,10 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.refuseColocatedHeartbeat(r.ServerId, storeident.Identity{MachineID: r.GetMachineId(), Dev: r.GetDurableRootDev(), FSID: r.GetDurableRootFsid()}); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
// INV-AUTH-HOLDER-IDENTITY-001: one server id names one host.
if err := s.host.refuseServerIDFromOtherHost(r); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
msg := heartbeatFromWire(r)
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
@@ -387,6 +391,13 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
if len(slots) == 0 {
return fmt.Errorf("subscribe: volume %q not in accepted topology", req.VolumeId)
}
// INV-AUTH-HOLDER-IDENTITY-001: a workspace volume's line is delivered only to a registered server id streaming
// from its registered host, so a second host with a copied --server-id never receives (never adopts) it.
if s.isWorkspaceVolume(req.VolumeId) {
if err := s.host.refuseWorkspaceHolderHost(ctx, "assignment stream", req.GetServerId()); err != nil {
return status.Error(codes.FailedPrecondition, err.Error())
}
}
type recv struct {
ch <-chan adapter.AssignmentInfo
@@ -461,24 +472,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
lastEpoch = info.Epoch
lastEV = info.EndpointVersion
sentAny = true
fact := &control.AssignmentFact{
VolumeId: info.VolumeID,
ReplicaId: info.ReplicaID,
Epoch: info.Epoch,
EndpointVersion: info.EndpointVersion,
DataAddr: info.DataAddr,
CtrlAddr: info.CtrlAddr,
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
// topology. peer_set_generation is derived
// from the authoritative line's (Epoch, EndpointVersion)
// packed into one uint64 as (epoch<<32 | ev). Assertion
// above guarantees each fits in uint32 so no aliasing.
// Monotonic across process lifetimes because Epoch/EV are
// durable authority facts preserved across master restart.
fact.Peers = s.collectPeers(req.VolumeId, info)
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
fact := s.assignmentFact(info)
if err := stream.Send(fact); err != nil {
return err
}
@@ -508,7 +502,15 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq
replicaIDs = []string{line.ReplicaID}
}
replicaIDs = primaryFirstReplicaIDs(replicaIDs, line.ReplicaID)
resp.Frontends = statusFrontendsForAssignedVolume(s.host.obs, req.VolumeId, replicaIDs, line.Assigned)
// the primary's portal comes from the server on the line, never a fresher same-replica claim elsewhere
// (INV-AUTH-HOLDER-IDENTITY-001)
resp.Frontends = statusFrontendsFor(s.host.obs, req.VolumeId, replicaIDs, line.Assigned, line.ReplicaID, func(replicaID string) (authority.SlotFact, bool) {
if replicaID == line.ReplicaID {
_, fact, ok := s.host.holderSlotFact(req.VolumeId, replicaID, line.Epoch)
return fact, ok
}
return s.host.obs.Store().SlotFact(req.VolumeId, replicaID)
})
resp.UnhealthyReplicas = statusUnhealthyReplicas(s.host.obs, req.VolumeId, replicaIDs)
}
if ev, ok := ctrl.LastUnsupported(req.VolumeId); ok {
@@ -552,20 +554,37 @@ func primaryFirstReplicaIDs(replicaIDs []string, primaryReplicaID string) []stri
}
func statusFrontendsForAssignedVolume(obs *authority.ObservationHost, volumeID string, replicaIDs []string, assigned bool) []*control.FrontendTarget {
return statusFrontendsFor(obs, volumeID, replicaIDs, assigned, "", nil)
}
// statusFrontendsFor lists the frontends of replicaIDs in order; slotOf selects each replica's slot fact (nil: the
// freshest claim for that replica). When primary is set and its slot fact is missing, nothing is listed: a CSI client
// takes the first frontend as the primary, so a supporting replica's frontend must never stand in for it
// (INV-AUTH-HOLDER-IDENTITY-001, fail closed).
func statusFrontendsFor(obs *authority.ObservationHost, volumeID string, replicaIDs []string, assigned bool, primary string, slotOf func(replicaID string) (authority.SlotFact, bool)) []*control.FrontendTarget {
if !assigned || obs == nil {
return nil
}
if slotOf == nil {
slotOf = func(replicaID string) (authority.SlotFact, bool) { return obs.Store().SlotFact(volumeID, replicaID) }
}
if primary != "" {
if f, ok := slotOf(primary); !ok || len(f.Frontends) == 0 {
return nil // no primary evidence, or a primary slot with no frontend: nothing to publish
}
}
out := make([]*control.FrontendTarget, 0, len(replicaIDs))
seen := map[string]struct{}{}
for _, replicaID := range replicaIDs {
if replicaID == "" {
continue
}
slot, ok := obs.Store().SlotFact(volumeID, replicaID)
slot, ok := slotOf(replicaID)
if !ok {
continue
}
for _, ft := range frontendTargetsToWire(slot.Frontends) {
ft.ReplicaId = replicaID // CSI selects only a primary-owned target (INV-AUTH-HOLDER-IDENTITY-001)
key := frontendTargetKey(ft)
if _, ok := seen[key]; ok {
continue
@@ -931,3 +950,27 @@ func (h *Host) ingestHeartbeatRecordingHealth(msg authority.HeartbeatMessage) er
}
return nil
}
// assignmentFact encodes one captured publication at the stream boundary.
func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.AssignmentFact {
fact := &control.AssignmentFact{
VolumeId: info.VolumeID,
ReplicaId: info.ReplicaID,
ServerId: s.host.workspaceLineOwner(authority.PublishedLine{ReplicaID: info.ReplicaID, Epoch: info.Epoch, IssuedHost: info.ServerID, OwnerFromMove: info.OwnerFromMove}, info.VolumeID, info.ReplicaID, info.Epoch),
Epoch: info.Epoch,
EndpointVersion: info.EndpointVersion,
DataAddr: info.DataAddr,
CtrlAddr: info.CtrlAddr,
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
// topology. peer_set_generation is derived
// from the authoritative line's (Epoch, EndpointVersion)
// packed into one uint64 as (epoch<<32 | ev). Assertion
// above guarantees each fits in uint32 so no aliasing.
// Monotonic across process lifetimes because Epoch/EV are
// durable authority facts preserved across master restart.
fact.Peers = s.collectPeers(info.VolumeID, info)
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
return fact
}
@@ -65,18 +65,55 @@ func (h *Host) workspaceEndpointsAvailable(b lifecycle.WorkspaceBinding) error {
return nil
}
// workspaceSourceHost resolves explicit holder membership for
// INV-AUTH-HOLDER-IDENTITY-001; endpoints never select a server.
func (h *Host) workspaceSourceHost(volume, replica string, epoch uint64) string {
current, _ := h.Publisher().PublishedAuthorityLine(volume)
return h.workspaceLineOwner(current, volume, replica, epoch)
}
// workspaceLineOwner is TERM-HOLDER-001's single owner decision function
// (INV-AUTH-HOLDER-IDENTITY-001). A captured current line never takes the
// publisher's store-write lock (INV-WS-RENEW-NONBLOCKING-001); only historical
// lines need the move journal. Endpoints never identify a server.
func (h *Host) workspaceLineOwner(current authority.PublishedLine, volume, replica string, epoch uint64) string {
if current.ReplicaID == replica && current.Epoch == epoch {
if current.OwnerFromMove || current.IssuedHost != "" {
return current.IssuedHost
}
return h.placementSourceHost(volume, replica)
}
if state := h.Publisher().WorkspaceState(volume); state != nil {
for _, r := range state.Moves {
if r.Issued && r.NewReplicaID == replica && r.NewEpoch == epoch {
return r.NewHost
}
if r.Issued && r.OldReplicaID == replica && r.OldEpoch == epoch {
return r.OldHost
}
}
}
if p, ok := h.lifecycle.Placements.GetPlacement(volume); ok {
for _, slot := range p.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
return h.placementSourceHost(volume, replica)
}
// placementSourceHost uses committed membership, never endpoint inference
// (INV-AUTH-HOLDER-IDENTITY-001, INV-WS-RENEW-NONBLOCKING-001).
func (h *Host) placementSourceHost(volume, replica string) string {
if h.lifecycle != nil {
if p, ok := h.lifecycle.Placements.GetPlacementSnapshot(volume); ok {
for _, slot := range p.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
}
}
}
}
for _, v := range h.topo.Volumes {
if v.VolumeID == volume {
for _, slot := range v.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
}
}
}
}
@@ -88,7 +88,7 @@ func TestWorkspaceBindingLegacyMoveCannotTakePreparedReservation(t *testing.T) {
if _, e := client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "prepared", ServerId: "node-b", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); e != nil {
t.Fatal(e)
}
id := &control.WorkspaceIdentity{VolumeId: "legacy", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "legacy", ReplicaId: "r1", Epoch: 1}
if _, e := client.RenewWorkspaceLease(ctx, id); e != nil {
t.Fatal(e)
}
@@ -114,7 +114,7 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) {
if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil {
t.Fatal(e)
}
if _, e := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1}); e != nil {
if _, e := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "live", ReplicaId: "r1", Epoch: 1}); e != nil {
t.Fatal(e)
}
if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "live"}); e == nil {
@@ -126,7 +126,7 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) {
if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("live"); e != nil || !bound {
t.Fatal("refused deletion removed binding", bound, e)
}
id := &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "live", ReplicaId: "r1", Epoch: 1}
if _, e := client.RevokeWorkspace(ctx, id); e != nil {
t.Fatal(e)
}
@@ -255,7 +255,7 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) {
})
reviewLegacyBind(t, h, c, ctx, "ack")
client := control.NewWorkspaceServiceClient(c)
id := &control.WorkspaceIdentity{VolumeId: "ack", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "ack", ReplicaId: "r1", Epoch: 1}
if _, e := client.RenewWorkspaceLease(ctx, id); e != nil {
t.Fatal(e)
}
@@ -120,7 +120,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), vol)
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: line.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: vol, ReplicaId: "r1", Epoch: line.Epoch}
lease, e := client.RenewWorkspaceLease(ctx, id)
if e != nil {
t.Fatal(e)
@@ -78,7 +78,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
t.Fatal(err)
}
oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a")
oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
oldID := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil {
t.Fatal(err)
}
@@ -188,7 +188,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
}
// The new holder detaches cleanly and ACKs; the delete is then admitted.
newID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch}
newID := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, newID); err != nil {
t.Fatal(err)
}
@@ -0,0 +1,145 @@
package master
import (
"context"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"reflect"
"sync/atomic"
"testing"
"time"
)
func leaseHolderIdentity(t *testing.T, epoch uint64, server string) *control.WorkspaceIdentity {
t.Helper()
q := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: epoch}
b, err := proto.Marshal(q)
if err != nil {
t.Fatal(err)
}
if server != "" {
b = protowire.AppendTag(b, 4, protowire.BytesType)
b = protowire.AppendString(b, server)
}
if err = proto.Unmarshal(b, q); err != nil {
t.Fatal(err)
}
return q
}
func TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant(t *testing.T) {
var nowNS atomic.Int64
nowNS.Store(time.Now().UnixNano())
h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
}, func(h *Host) {
authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher())
})
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
t.Cleanup(cancel)
reviewCreate(t, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "v")
refuse := func(stage string, epoch uint64) {
t.Helper()
for _, server := range []string{"", "node-b"} {
before := h.Publisher().WorkspaceState("v")
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, epoch, server)); err == nil {
t.Errorf("%s accepted lease for server %q", stage, server)
}
after := h.Publisher().WorkspaceState("v")
if !reflect.DeepEqual(before, after) {
t.Errorf("%s refused identity changed lease", stage)
}
}
}
refuse("first grant", line.Epoch)
id := leaseHolderIdentity(t, line.Epoch, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal("matching server grant", err)
}
refuse("renew", line.Epoch)
nowNS.Add(int64(2 * time.Minute)) // beyond both the old horizon and clock-skew barrier
refuse("expired re-grant", line.Epoch)
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal("matching server expired re-grant", err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "same-host", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"})
if err != nil {
t.Fatal(err)
}
refuse("re-grant", g.NewEpoch)
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, g.NewEpoch, "node-a")); err != nil {
t.Fatal("matching server re-grant", err)
}
}
// INV-AUTH-HOLDER-IDENTITY-001: an ACK licenses a clean move, so only the
// primary server/replica pair may record it, not another host of the same r1.
func TestWorkspaceRevocationACKRequiresHolderServer(t *testing.T) {
for _, server := range []string{"", "node-b"} {
t.Run("server="+server, func(t *testing.T) {
h, conn, ctx := reviewBindingHost(t)
reviewCreate(t, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "v")
own := leaseHolderIdentity(t, line.Epoch, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, own); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, own); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: leaseHolderIdentity(t, line.Epoch, server), HeadGen: 9}); err == nil {
t.Errorf("ACK accepted server %q with the right replica/epoch", server)
}
recorded, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "v"})
if err != nil {
t.Fatal(err)
}
if recorded.GetRevocationAck() != nil {
t.Errorf("foreign ACK recorded: %v", recorded.GetRevocationAck())
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: own, HeadGen: 9}); err != nil {
t.Fatal("own ACK refused", err)
}
recorded, err = ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "v"})
if err != nil || recorded.GetRevocationAck().GetHeadGen() != 9 {
t.Fatal("own ACK not recorded", recorded, err)
}
})
}
}
@@ -55,7 +55,7 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) {
t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender
var stops atomic.Int32
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1},
func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -112,8 +112,8 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
first, err := svc.RenewWorkspaceLease(ctx, id)
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
first, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id)
if err != nil {
t.Fatal(err)
}
@@ -129,7 +129,7 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
if err != nil || !rv.Revoking || rv.ExpiresAtNs != first.ExpiresAtNs {
t.Fatalf("RevokeWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, rv, err)
}
if _, err := svc.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
if _, err := svc.AckWorkspaceRevoked(loopbackPeer(ctx), &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
deletions := h.Lifecycle().Deletions
@@ -148,6 +148,9 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
}()
renewed := make(chan *control.WorkspaceLeaseFact, 1)
renewErr := make(chan error, 1)
ownerResult := make(chan string, 1)
ownerJoined := make(chan struct{})
ownerStarted := false
renewStarted := false
t.Cleanup(func() { // bounded: release, settle both workers, then clear the hook
releaseHook()
@@ -158,6 +161,14 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
settled = false
t.Error("held reservation write did not settle")
}
if ownerStarted {
select {
case <-ownerJoined:
case <-time.After(5 * time.Second):
settled = false
t.Error("owner lookup did not settle")
}
}
if renewStarted {
select {
case <-renewErr:
@@ -175,9 +186,25 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("reservation write of vol-b never reached the store")
}
// TERM-HOLDER-001: current-line facts and lease admission resolve the
// same committed owner without entering the publisher's store-write lock.
ownerStarted = true
go func() {
defer close(ownerJoined)
ownerResult <- h.workspaceSourceHost("vol-b", line.ReplicaID, line.Epoch)
}()
select {
case owner := <-ownerResult:
matches, matchErr := svc.holderMatches(loopbackPeer(ctx), "vol-b", line.ReplicaID, owner, line.Epoch)
if owner != "node-a" || !matches || matchErr != nil {
t.Fatalf("fact and lease owner differ under held writer: %q", owner)
}
case <-time.After(time.Second):
t.Fatal("current owner lookup waited for publisher store write")
}
renewStarted = true
go func() {
f, err := svc.RenewWorkspaceLease(ctx, id)
f, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id)
renewed <- f
renewErr <- err
}()
@@ -201,7 +228,7 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("mark deleting did not finish")
}
if _, err := svc.RenewWorkspaceLease(ctx, id); err == nil || !strings.Contains(err.Error(), "being deleted") {
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err == nil || !strings.Contains(err.Error(), "being deleted") {
t.Fatalf("renewal after the reservation was published: %v; want refused as being deleted", err)
}
}
@@ -0,0 +1,74 @@
package master
import (
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"testing"
)
// TERM-HOLDER-001 / INV-AUTH-HOLDER-IDENTITY-001: current facts, leases and
// move-source history share the owner rule; placement does not override a move.
func TestWorkspaceLineOwnerIssuedAndHistorical(t *testing.T) {
h, conn, ctx := reviewBindingHost(t)
reviewLegacyBind(t, h, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
id := leaseHolderIdentity(t, 1, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
target := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-b", DataAddr: "127.0.0.1:20000", CtrlAddr: "127.0.0.1:20001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, target); err != nil {
t.Fatal(err)
}
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)
}
if !grant.Issued || grant.NewEpoch != 2 {
t.Fatal("move did not issue", grant)
}
svc := &services{host: h}
matches := func(server string) bool {
t.Helper()
ok, err := svc.holderMatches(loopbackPeer(ctx), "v", "r1", server, 2)
if err != nil {
t.Fatal(err)
}
return ok
}
if got := h.placementSourceHost("v", "r1"); got != "node-a" {
t.Fatal("fixture placement no longer differs from issued owner", got)
}
// Both consumers must prefer the issued owner to the old placement.
if got := h.workspaceSourceHost("v", "r1", 2); got != "node-b" || !matches(got) || matches("node-a") {
t.Fatal("fact/lease issued owner mismatch", got)
}
stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(ctx, &control.SubscribeRequest{VolumeId: "v", ReplicaId: "r1", ServerId: "node-b"})
if err != nil {
t.Fatal(err)
}
fact, err := stream.Recv()
if err != nil || fact.GetServerId() != "node-b" || fact.GetEpoch() != 2 {
t.Fatal("wrong produced fact", fact, err)
}
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, 2, "node-b")); err != nil {
t.Fatal("issued owner lease refused", err)
}
// Change only desired-placement metadata. It must not rewrite the owner of
// the historical e1 line retained in the actual issued move journal.
if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v", ServerID: "node-c", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if got := h.workspaceSourceHost("v", "r1", 1); got != "node-a" {
t.Fatal("historical line guessed from current placement", got)
}
if got := h.workspaceSourceHost("v", "r1", 2); got != "node-b" || !matches(got) {
t.Fatal("issued owner changed with placement", got)
}
}
@@ -97,7 +97,7 @@ func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceS
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-f")
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
t.Fatal(err)
}
return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1",
@@ -80,7 +80,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
}
defer conn.Close()
client := control.NewWorkspaceServiceClient(conn)
id := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
lease, err := client.RenewWorkspaceLease(ctx, id)
if err != nil {
t.Fatal(err)
@@ -75,7 +75,7 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) {
t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2)
}
// a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD.
id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
@@ -159,7 +159,7 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) {
// The grantee renews (its guard is valid), then pauses before its claim.
guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}, skewLeaseClient{p},
&control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow })
&control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow })
if err != nil {
t.Fatal(err)
}
@@ -65,7 +65,7 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, masterNS.Load()) }), authority.WithWorkspaceMaxClockSkew(4*time.Second))
seedSkewPublisher(t, p, dir)
client := &heldSkewLeaseClient{skewLeaseClient: skewLeaseClient{p}, entered: make(chan *control.WorkspaceLeaseFact, 1), release: make(chan struct{})}
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) })
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) })
if err != nil {
t.Fatal(err)
}
@@ -150,11 +150,11 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil))
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
seedSkewPublisher(t, p, dir)
var stops atomic.Int32
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1},
func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -166,7 +166,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
cancel()
<-runDone // Run returns on cancel; the go test timeout bounds a hang
})
t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins
t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins
for !g.Projection().Healthy { // progress: the first grant
time.Sleep(20 * time.Millisecond)
}
@@ -215,8 +215,8 @@ func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err) // first grant
}
deletions := h.Lifecycle().Deletions
@@ -266,7 +266,7 @@ func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) {
}
start := time.Now()
renewStarted = true
go func() { _, err := svc.RenewWorkspaceLease(ctx, id); renewed <- err }()
go func() { _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); renewed <- err }()
select {
case err := <-renewed:
renewed <- err // keep it for the cleanup join
@@ -27,7 +27,7 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) {
if line := waitAuthorityLine(t, h.Publisher(), "v"); line.Epoch != 1 {
t.Fatal(line)
}
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r1", Epoch: 1}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
@@ -54,6 +54,17 @@ func (s *services) workspaceVolumeForRenewal(volume string) error {
return nil
}
// isWorkspaceVolume reports whether volume is a workspace volume (workspace RPC on, an existing RF1 volume), from the
// lock-free lifecycle snapshot. Unlike workspaceVolumeForRenewal it ignores a deletion reservation: a volume being
// deleted is still a workspace volume, and its assignment stream keeps the holder host check (codex01 #416 P2).
func (s *services) isWorkspaceVolume(volume string) bool {
if !s.host.cfg.WorkspaceRPC || s.host.lifecycle == nil {
return false
}
r, ok := s.host.lifecycle.Volumes.GetVolumeSnapshot(volume)
return ok && r.Spec.ReplicationFactor == 1
}
func workspaceError(err error) error {
if err == nil {
return nil
@@ -86,10 +97,30 @@ func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeas
return &control.WorkspaceLeaseFact{VolumeId: volume, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ExpiresAtNs: l.ExpiresAtNS, ValidForNs: int64(remaining), Revoking: l.Revoking}
}
// holderMatches implements INV-AUTH-HOLDER-IDENTITY-001 for both holder RPCs.
// The committed line and placement snapshot avoid store I/O on renewal.
// A non-nil error is the host refusal: the server id is unregistered, or the
// call's network peer is not on its registered host (refuseWorkspaceHolderHost).
func (s *services) holderMatches(ctx context.Context, volume, replica, server string, epoch uint64) (bool, error) {
if err := s.host.refuseWorkspaceHolderHost(ctx, "workspace lease", server); err != nil {
return false, err
}
line, ok := s.host.Publisher().PublishedAuthorityLine(volume)
if !ok || server == "" || line.ReplicaID != replica || line.Epoch != epoch {
return false, nil
}
return server == s.host.workspaceLineOwner(line, volume, replica, epoch), nil
}
func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
if err := s.workspaceVolumeForRenewal(q.GetVolumeId()); err != nil {
return nil, err
}
if ok, err := s.holderMatches(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetServerId(), q.GetEpoch()); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
} else if !ok {
return nil, status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder")
}
l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch())
if err != nil {
return nil, workspaceError(err)
@@ -119,6 +150,11 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace
if err := s.workspaceVolume(id.GetVolumeId()); err != nil {
return nil, err
}
if ok, err := s.holderMatches(ctx, id.GetVolumeId(), id.GetReplicaId(), id.GetServerId(), id.GetEpoch()); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
} else if !ok {
return nil, status.Error(codes.FailedPrecondition, "workspace ACK: server identity does not match the current holder")
}
if err := s.host.Publisher().AckWorkspaceRevocation(ctx, id.GetVolumeId(), authority.WorkspaceRevokeAck{ReplicaID: id.GetReplicaId(), Epoch: id.GetEpoch(), HeadGen: q.GetHeadGen()}); err != nil {
return nil, workspaceError(err)
}
@@ -15,13 +15,27 @@ import (
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
type workspaceRPCView struct{ p frontend.Projection }
func (v workspaceRPCView) Projection() frontend.Projection { return v.p }
// lostAckReply returns an unknown outcome only after the real master has
// committed the ACK. The caller must resolve it from a recorded witness.
type lostAckReply struct{ control.WorkspaceServiceClient }
func (c lostAckReply) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck, opts ...grpc.CallOption) (*control.WorkspaceEmpty, error) {
reply, err := c.WorkspaceServiceClient.AckWorkspaceRevoked(ctx, q, opts...)
if err != nil {
return reply, err
}
return nil, status.Error(codes.DeadlineExceeded, "injected ACK reply loss after commit")
}
func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
var detached atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -56,6 +70,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101"}); err != nil {
t.Fatal(err)
}
registerWorkspaceHolder(t, h, "node-a") // a workspace holder's server id must be registered (INV-AUTH-HOLDER-IDENTITY-001)
seedVerifiedExistingReplicaPlacement(t, h)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
@@ -70,11 +85,11 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
}
defer conn.Close()
client := control.NewWorkspaceServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
id := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r2", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: "r2", Epoch: 1}
stops := 0
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "vol-a", ReplicaID: "r2", Epoch: 1, Healthy: true}}, client, id,
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "vol-a", ReplicaID: "r2", Epoch: 1, Healthy: true}}, lostAckReply{client}, id,
func(context.Context) (uint64, error) { stops++; return 9, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -90,8 +105,18 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
if _, err := client.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if err := g.Refresh(ctx); err != nil {
t.Fatal(err)
// The stop/ACK path keeps its production timeout. Resolve a lost reply
// from the master's exact ACK, never from elapsed time or the stop alone.
if err := g.Refresh(ctx); status.Code(err) != codes.DeadlineExceeded {
t.Fatalf("expected unknown ACK reply, got %v", err)
}
recorded, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"})
if err != nil {
t.Fatal("ACK witness unreadable", err)
}
ack := recorded.GetRevocationAck()
if ack.GetIdentity().GetVolumeId() != "vol-a" || ack.GetIdentity().GetReplicaId() != "r2" || ack.GetIdentity().GetEpoch() != 1 || ack.GetHeadGen() != 9 {
t.Fatalf("unknown ACK has no exact recorded witness: %+v", ack)
}
if g.Projection().Healthy || stops != 1 {
t.Fatal("revoked frontend remained admitted")
@@ -102,12 +127,12 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
detached.Store(true)
streamCtx, cancelStream := context.WithCancel(ctx)
defer cancelStream()
stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(streamCtx, &control.SubscribeRequest{VolumeId: "vol-a", ReplicaId: "r2"})
stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(streamCtx, &control.SubscribeRequest{VolumeId: "vol-a", ReplicaId: "r2", ServerId: "node-a"})
if err != nil {
t.Fatal(err)
}
initial, err := stream.Recv()
if err != nil || initial.ReplicaId != "r2" || initial.Epoch != 1 {
if err != nil || initial.ServerId != "node-a" || initial.ReplicaId != "r2" || initial.Epoch != 1 {
t.Fatal("initial assignment", initial, err)
}
beforeLine, _ := h.Publisher().VolumeAuthorityLine("vol-a")
@@ -133,7 +158,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
t.Fatal(grant)
}
delivered, err := stream.Recv()
if err != nil || delivered.ReplicaId != "r2" || delivered.Epoch != 2 || delivered.DataAddr != q.TargetDataAddr || delivered.CtrlAddr != q.TargetCtrlAddr || len(delivered.Peers) != 0 {
if err != nil || delivered.ServerId != "node-b" || delivered.ReplicaId != "r2" || delivered.Epoch != 2 || delivered.DataAddr != q.TargetDataAddr || delivered.CtrlAddr != q.TargetCtrlAddr || len(delivered.Peers) != 0 {
t.Fatal("same-ID move was not delivered on the existing stream with no retired peer", delivered, err)
}
cancelStream()
@@ -144,7 +169,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
if _, err := client.RenewWorkspaceLease(ctx, id); err == nil {
t.Fatal("old authority renewed")
}
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r2", Epoch: 2}); err != nil {
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "vol-a", ReplicaId: "r2", Epoch: 2}); err != nil {
t.Fatal(err)
}
if err := h.Close(ctx); err != nil {
@@ -43,7 +43,7 @@ func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) {
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(3*time.Second, func() time.Time { return masterNow }))
seedSkewPublisher(t, p, dir)
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, skewLeaseClient{p}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return hostNow })
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, skewLeaseClient{p}, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return hostNow })
if err != nil {
t.Fatal(err)
}
@@ -130,12 +130,13 @@ func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) {
if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
registerWorkspaceHolder(t, h, "node-a") // a workspace holder's server id must be registered (INV-AUTH-HOLDER-IDENTITY-001)
seedVerifiedExistingReplicaPlacement(t, h)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-a")
reply, err := (&services{host: h}).RenewWorkspaceLease(context.Background(), &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch})
reply, err := (&services{host: h}).RenewWorkspaceLease(loopbackPeer(context.Background()), &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch})
if err != nil {
t.Fatal(err)
}
@@ -92,7 +92,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
t.Fatal(err)
}
oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a")
oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
oldID := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil {
t.Fatal(err)
}
@@ -148,7 +148,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
if !grant.Issued || grant.NewEpoch != grantee+1 || line.Epoch != grant.NewEpoch || grant.HeadGen != seed.Gen || grant.RemoteLsn != seed.RemoteLSN {
t.Fatalf("forced grant %+v line %+v; want epoch %d on HEAD gen %d lsn %d", grant, line, grantee+1, seed.Gen, seed.RemoteLSN)
}
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil {
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil {
t.Fatal("the dead grantee's epoch renewed after the forced move")
}
@@ -132,7 +132,7 @@ func TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment(t *testing.T) {
PeerSetGeneration: 42,
}
h.applyFact(fact)
h.applyFixtureFact(fact)
// Both collaborators called exactly once.
if got := r.callCount.Load(); got != 1 {
@@ -188,7 +188,7 @@ func TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment(t *testin
PeerSetGeneration: 7,
}
h.applyFact(fact)
h.applyFixtureFact(fact)
// UpdateReplicaSet was called (once).
if got := r.callCount.Load(); got != 1 {
@@ -223,7 +223,7 @@ func TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter(t
},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if got := r.callCount.Load(); got != 0 {
t.Fatalf("local readiness block must skip UpdateReplicaSet: got %d calls", got)
@@ -258,7 +258,7 @@ func TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter(t *
},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if got := a.callCount.Load(); got != 0 {
t.Fatalf("local readiness block must skip supporting OnAssignment: got %d calls", got)
@@ -294,7 +294,7 @@ func TestHost_ApplyFact_SupportingReplica_ReplaysAfterLocalReadinessClears(t *te
}},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
@@ -337,7 +337,7 @@ func TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirs
}},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
@@ -372,7 +372,7 @@ func TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication(t *testing.T) {
PeerSetGeneration: 100,
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if a.callCount.Load() != 0 {
t.Fatalf("supersede must not call adapter: got %d calls", a.callCount.Load())
@@ -411,7 +411,7 @@ func TestHost_ApplyFact_SupportingReplica_UsesSelfPeerDescriptorWithoutReplicati
PeerSetGeneration: 100,
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if got := a.callCount.Load(); got != 1 {
t.Fatalf("supporting replica should apply self peer lineage once: got %d calls", got)
@@ -454,7 +454,7 @@ func TestHost_ApplyFact_SupportingReplica_UsesSelfPeerDescriptorWithoutReplicati
PeerSetGeneration: 101,
}
h.applyFact(primaryFact)
h.applyFixtureFact(primaryFact)
if got := a.callCount.Load(); got != 2 {
t.Fatalf("promotion after supporting assignment should apply adapter again: got %d calls", got)
@@ -490,7 +490,7 @@ func TestHost_ApplyFact_SupportingReplica_InvalidSelfPeerDescriptorStaysSupersed
}},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if got := a.callCount.Load(); got != 0 {
t.Fatalf("invalid supporting peer descriptor must not call adapter: got %d calls", got)
@@ -521,7 +521,7 @@ func TestHost_ApplyFact_SupportingReplica_MismatchedSelfPeerLineageStaysSupersed
}},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if got := a.callCount.Load(); got != 0 {
t.Fatalf("mismatched supporting peer lineage must not call adapter: got %d calls", got)
@@ -548,7 +548,7 @@ func TestHost_ApplyFact_SupportingReplica_ReportsReplicaReadyButNotFrontendPrima
h.view = NewAdapterProjectionView(a, "vol1", "r2", h)
s := NewStatusServer(h.view)
h.applyFact(&control.AssignmentFact{
h.applyFixtureFact(&control.AssignmentFact{
VolumeId: "vol1",
ReplicaId: "r1",
Epoch: 7,
@@ -619,7 +619,7 @@ func TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment(t *testing.T
}},
}
h.applyFact(fact)
h.applyFixtureFact(fact)
if a.callCount.Load() != 1 {
t.Fatalf("observer-only must call adapter: got %d", a.callCount.Load())
@@ -0,0 +1,80 @@
package volume
import (
"fmt"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// assignmentNamesSelf implements INV-AUTH-HOLDER-IDENTITY-001. Missing server identity is
// refused. Endpoints are routing data and never qualify holder identity.
func (h *Host) assignmentNamesSelf(f *control.AssignmentFact) bool {
return f.GetServerId() != "" && f.GetServerId() == h.cfg.ServerID &&
f.GetVolumeId() == h.cfg.VolumeID && f.GetReplicaId() == h.cfg.ReplicaID
}
// observeForeignHolder implements M3 / INV-AUTH-HOLDER-IDENTITY-001.
// Delivery before a move is not supersession: record every refused fact,
// and use the one supersession decision against the adopted engine lineage.
func (h *Host) observeForeignHolder(f *control.AssignmentFact) {
h.log.Printf("blockvolume: assignment identity refusal volume=%q replica=%q server=%q epoch=%d ev=%d data=%q ctrl=%q "+
"expected_volume=%q expected_replica=%q expected_server=%q expected_data=%q expected_ctrl=%q",
f.VolumeId, f.ReplicaId, f.ServerId, f.Epoch, f.EndpointVersion, f.DataAddr, f.CtrlAddr,
h.cfg.VolumeID, h.cfg.ReplicaID, h.cfg.ServerID, h.cfg.DataAddr, h.cfg.CtrlAddr)
h.recordOtherLine(f)
if h.view == nil {
return
}
own := h.view.EngineProjection()
if !h.IsSuperseded(h.cfg.ReplicaID, own.Epoch, own.EndpointVersion) {
h.log.Printf("blockvolume: volume %s foreign assignment server=%q replica=%q recorded, not adopted; waiting for own current line", h.cfg.VolumeID, f.ServerId, f.ReplicaId)
return
}
h.wd.notPrimary()
if err := h.fenceSelfWithPeers(selfRolePrimary, f.Epoch, false); err != nil {
h.log.Printf("blockvolume: foreign holder ingress fence: %v", err)
}
h.log.Printf("blockvolume: volume %s superseded by assignment server=%q replica=%q; fenced, not serving", h.cfg.VolumeID, f.ServerId, f.ReplicaId)
}
// reportAssignmentEndpoints is diagnostic only under INV-AUTH-HOLDER-IDENTITY-001:
// the master's published routing values need not spell this process's listeners.
func (h *Host) reportAssignmentEndpoints(f *control.AssignmentFact) {
warning := ""
if (f.DataAddr != "" && f.DataAddr != h.cfg.DataAddr) || (f.CtrlAddr != "" && f.CtrlAddr != h.cfg.CtrlAddr) {
warning = fmt.Sprintf("master advertises data=%s ctrl=%s for this holder; this process listens on %s, %s", f.DataAddr, f.CtrlAddr, h.cfg.DataAddr, h.cfg.CtrlAddr)
}
previous := h.assignmentEndpointWarning.Swap(warning)
if warning != "" && previous != warning {
h.log.Printf("blockvolume: %s", warning)
}
}
// AssignmentEndpointWarning is visible on status without changing readiness.
func (h *Host) AssignmentEndpointWarning() string {
warning, _ := h.assignmentEndpointWarning.Load().(string)
return warning
}
// refusePrimaryAssignment implements M3 / INV-AUTH-HOLDER-IDENTITY-001:
// a candidate cannot enter the adapter behind an already observed foreign line.
// Identity and ordering each use their existing single deciding function.
func (h *Host) refusePrimaryAssignment(f *control.AssignmentFact) bool {
if f.ReplicaId != h.cfg.ReplicaID {
return false
}
if !h.assignmentNamesSelf(f) {
h.observeForeignHolder(f)
return true
}
other := h.LastOtherLine()
// A candidate's owner cannot change within one epoch, even when its EV
// advances. This is an admission refusal, not a supersession fence on
// an already-adopted lineage (whose strict-newer rule is unchanged).
sameEpochForeign := other != nil && other.Epoch == f.Epoch && other.ReplicaId == f.ReplicaId && other.ServerId != "" && other.ServerId != f.ServerId
if sameEpochForeign || h.IsSuperseded(h.cfg.ReplicaID, f.Epoch, f.EndpointVersion) {
h.log.Printf("blockvolume: volume %s refuses stale self-labelled assignment server=%q epoch=%d ev=%d behind recorded foreign line",
h.cfg.VolumeID, f.ServerId, f.Epoch, f.EndpointVersion)
return true
}
return false
}
@@ -0,0 +1,304 @@
package volume
import (
"fmt"
"log"
"strings"
"sync/atomic"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
)
// r2.34 AUTHORITY: replica r1 and loopback addresses are reused after a move.
// Field 9 is encoded on the wire so this regression also runs on the old schema.
func holderAssignment(t *testing.T, server string) *control.AssignmentFact {
t.Helper()
f := &control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 2, EndpointVersion: 1, DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304"}
b, err := proto.Marshal(f)
if err != nil {
t.Fatal(err)
}
if server != "" {
b = protowire.AppendTag(b, 9, protowire.BytesType)
b = protowire.AppendString(b, server)
}
if err = proto.Unmarshal(b, f); err != nil {
t.Fatal(err)
}
return f
}
func TestAssignmentHolderIdentityRestartedOldProcess(t *testing.T) {
for _, server := range []string{"new-host", ""} {
t.Run("server="+server, func(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "old-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
// Forced move has kept r1; the restarted old process receives r1@2.
// Endpoint-only matching is deliberately indistinguishable here.
h.applyFact(holderAssignment(t, server))
if p := h.realAdpt.Projection(); p.Epoch != 0 {
t.Errorf("old process adopted foreign/missing server: %+v", p)
}
if h.LastOtherLine() == nil {
t.Error("foreign primary line was not recorded")
}
for _, cmd := range h.t1exec.Commands() {
if strings.HasPrefix(cmd, "PublishHealthy:") {
t.Errorf("foreign line published healthy: %s", cmd)
}
}
if h.view.Projection().Healthy {
t.Error("foreign assignment made the frontend healthy")
}
})
}
}
func TestAssignmentHolderIdentityMatchingServerStillAdopts(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "new-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
h.applyFact(holderAssignment(t, "new-host"))
deadline := time.Now().Add(time.Second)
for !h.view.Projection().Healthy && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if p := h.view.Projection(); !p.Healthy || p.Epoch != 2 {
t.Fatalf("matching holder did not become healthy: %+v", p)
}
}
// The old process may already have been healthy before the forced move. The
// foreign line must withdraw that projection even though r1 is unchanged.
func TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "old-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
own := holderAssignment(t, "old-host")
own.Epoch = 1
h.applyFact(own)
deadline := time.Now().Add(time.Second)
for !h.view.Projection().Healthy && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if !h.view.Projection().Healthy {
t.Fatal("old owner baseline not healthy")
}
h.applyFact(holderAssignment(t, "new-host"))
if h.realAdpt.Projection().Epoch != 1 {
t.Fatal("foreign epoch adopted")
}
if h.view.Projection().Healthy {
t.Fatal("same-r1 foreign holder left the old frontend healthy")
}
stale := holderAssignment(t, "new-host")
stale.Epoch = 0
h.applyFact(stale)
if h.view.Projection().Healthy {
t.Fatal("stale foreign replay erased the newer fencing line")
}
}
// Endpoints are routing data, not the holder identity (claude06 ruling).
func TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch(t *testing.T) {
for _, endpoint := range []string{"data", "control"} {
t.Run(endpoint, func(t *testing.T) {
logs := &lockedBuffer{}
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "new-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true, Logger: log.New(logs, "", 0)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
f := holderAssignment(t, "new-host")
if endpoint == "data" {
f.DataAddr = "0.0.0.0:19303"
} else {
f.CtrlAddr = "localhost:19304"
}
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(f)
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
deadline := time.Now().Add(time.Second)
for !h.view.Projection().Healthy && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if p := h.view.Projection(); !p.Healthy || p.Epoch != 2 || h.LastOtherLine() != nil {
t.Fatalf("own endpoint spelling fenced holder: %+v", p)
}
st := NewStatusServer(h.ProjectionView()).statusProjection()
if len(st.Warnings) != 1 || !strings.Contains(st.Warnings[0], "master advertises data=") || !strings.Contains(st.Warnings[0], "this process listens on") {
t.Fatalf("status warning missing: %+v", st.Warnings)
}
h.applyFact(f)
if n := strings.Count(logs.String(), "master advertises data="); n != 1 {
t.Fatalf("warning logged %d times, want once", n)
}
corrected := holderAssignment(t, "new-host")
corrected.EndpointVersion = 2
h.applyFact(corrected)
if got := NewStatusServer(h.ProjectionView()).statusProjection().Warnings; len(got) != 0 {
t.Fatalf("corrected endpoints retained warning: %v", got)
}
})
}
}
type holderFenceCounter struct{ calls atomic.Uint32 }
func (f *holderFenceCounter) FenceAsPrimary(uint64) error { f.calls.Add(1); return nil }
func (f *holderFenceCounter) AdmitAsReplica(uint64) error { f.calls.Add(1); return nil }
// INV-AUTH-HOLDER-IDENTITY-001 / M3: a recorded foreign fact supersedes
// only an adopted own lineage and only when it is strictly newer.
func TestAssignmentHolderIdentityForeignStreamOrdering(t *testing.T) {
for _, mode := range []string{"target-old-first", "target-own-endpoint-first", "served-newer-foreign", "served-newer-endpoint-version", "served-old-replay", "served-equal-replay", "never-assigned"} {
t.Run(mode, func(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "new-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
fencer := &holderFenceCounter{}
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
own := holderAssignment(t, "new-host")
foreign := holderAssignment(t, "old-host")
foreign.Epoch = 1
waitHealthy := func() {
t.Helper()
deadline := time.Now().Add(time.Second)
for !h.view.Projection().Healthy && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if p := h.view.Projection(); !p.Healthy || p.Epoch != 2 {
t.Fatalf("rightful target did not serve: %+v", p)
}
}
switch mode {
case "target-old-first":
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(foreign)
if fencer.calls.Load() != 0 || h.IsSuperseded("r1", 0, 0) {
t.Fatal("unassigned target was fenced by the current old line")
}
h.applyFact(own)
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
waitHealthy()
case "target-own-endpoint-first":
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(own)
mismatch := holderAssignment(t, "new-host")
mismatch.DataAddr = "127.0.0.1:9991"
h.applyFact(mismatch)
if fencer.calls.Load() != 0 {
t.Fatal("early endpoint refusal fenced unassigned target")
}
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
waitHealthy()
case "never-assigned":
h.applyFact(foreign)
foreign.Epoch = 2
h.applyFact(foreign)
if fencer.calls.Load() != 0 || h.realAdpt.Projection().Epoch != 0 || h.view.Projection().Healthy || h.IsSuperseded("r1", 0, 0) || h.LastOtherLine() == nil {
t.Fatal("never-assigned process must record, wait, neither adopt nor fence")
}
default:
h.applyFact(own)
waitHealthy()
before := fencer.calls.Load()
if mode == "served-newer-foreign" {
foreign.Epoch = 3
}
if mode == "served-equal-replay" {
foreign.Epoch = 2
}
if mode == "served-newer-endpoint-version" {
foreign.Epoch = 2
foreign.EndpointVersion = 2
}
h.applyFact(foreign)
if mode == "served-newer-foreign" || mode == "served-newer-endpoint-version" {
if fencer.calls.Load() <= before || h.view.Projection().Healthy {
t.Fatal("served holder was not fenced by newer foreign line")
}
} else if fencer.calls.Load() != before || !h.view.Projection().Healthy {
t.Fatal("old foreign replay fenced a serving holder")
}
}
})
}
}
// INV-AUTH-HOLDER-IDENTITY-001: an old process cannot adopt a stale
// self-labelled EV1 after it has observed the forced move's foreign EV2.
func TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "old-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
h.BlockLocalReadiness("awaiting durable recovery")
staleSelf := holderAssignment(t, "old-host")
h.applyFact(staleSelf) // retained before the newer foreign delivery
for _, ev := range []uint64{1, 2, 1, 3} {
foreign := holderAssignment(t, "new-host")
foreign.EndpointVersion = ev
h.applyFact(foreign)
if h.realAdpt.Projection().Epoch != 0 {
t.Fatalf("old server adopted foreign EV%d", ev)
}
}
// Covers the safety boundary even if an older delivery incorrectly
// names the source: a known newer foreign line still takes precedence.
h.ClearLocalReadinessBlock()
h.replayLocalReadinessFactIfReady()
if p := h.realAdpt.Projection(); p.Epoch != 0 {
t.Fatalf("old server adopted stale EV1 after foreign newer line: %+v", p)
}
for _, cmd := range h.t1exec.Commands() {
if strings.HasPrefix(cmd, "PublishHealthy:") {
t.Fatalf("old server published healthy: %s", cmd)
}
}
if h.view.Projection().Healthy {
t.Fatal("old server served after forced move")
}
}
// INV-AUTH-HOLDER-IDENTITY-001: a recorded foreign owner at this epoch
// cannot be overwritten by a self-labelled delivery, even at a higher EV.
func TestAssignmentHolderIdentitySameEpochCannotChangeServer(t *testing.T) {
for _, ev := range []uint64{1, 2, 3} {
t.Run(fmt.Sprint(ev), func(t *testing.T) {
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "old-host", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
foreign := holderAssignment(t, "new-host")
foreign.EndpointVersion = 2
h.applyFact(foreign)
self := holderAssignment(t, "old-host")
self.EndpointVersion = ev
h.applyFact(self)
if p := h.realAdpt.Projection(); p.Epoch != 0 {
t.Fatalf("same epoch changed from recorded new-host to old-host at EV%d: %+v", ev, p)
}
})
}
}
@@ -0,0 +1,28 @@
package volume
import (
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/proto"
)
// applyFixtureFact supplies the explicit holder identity for pre-r2.34 tests
// whose subject is peer ordering, readiness or recovery. Identity-refusal
// regressions call applyFact directly and never use this fixture constructor.
func (h *Host) applyFixtureFact(f *control.AssignmentFact) {
f = proto.Clone(f).(*control.AssignmentFact)
if h.cfg.ServerID == "" {
h.cfg.ServerID = "fixture-server"
}
if f.ServerId == "" {
f.ServerId = h.cfg.ServerID
}
if f.ReplicaId == h.cfg.ReplicaID {
if h.cfg.DataAddr == "" {
h.cfg.DataAddr = f.DataAddr
}
if h.cfg.CtrlAddr == "" {
h.cfg.CtrlAddr = f.CtrlAddr
}
}
h.applyFact(f)
}
@@ -34,7 +34,7 @@ func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T
// main.go: block readiness before Start; the assignment arrives and
// is retained, not applied.
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1})
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1})
if p := h.ProjectionView().Projection(); p.Healthy || p.Epoch != 0 {
t.Fatalf("assignment applied while readiness was blocked: %+v", p)
}
@@ -247,6 +247,10 @@ func (s *StatusServer) chunkMux() http.Handler {
return mux
}
// codeHostSlotBusy refuses a cut, snapshot or detach because every host
// cut slot is held (retryable).
const codeHostSlotBusy = "host_slot_busy"
func writeChunkJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
@@ -338,6 +342,11 @@ func chunkErrorCode(err error) (int, string, bool) {
return http.StatusConflict, chunkstore.CodeNotChunkVolume, false
case errors.Is(err, context.DeadlineExceeded):
return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true
// Every host cut slot held (host admission, --host-limit-dir): a wait
// that ends when another cut releases its slot. Its own code, so a
// caller can resend on exactly this refusal without reading messages.
case errors.Is(err, hostlimit.ErrSlotsHeld):
return http.StatusServiceUnavailable, codeHostSlotBusy, true
case errors.Is(err, storage.ErrChunkCaptureRefused):
return http.StatusServiceUnavailable, "capture_refused", true
default:
@@ -0,0 +1,30 @@
package volume
import (
"fmt"
"net/http"
"testing"
"github.com/seaweedfs/seaweed-block/core/hostlimit"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// A refusal because every host cut slot is held has its own retryable
// code; other capture refusals, a plain host busy included, keep
// capture_refused.
func TestHostSlotHeldHasItsOwnCode(t *testing.T) {
for _, tc := range []struct {
err error
code string
}{
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld), codeHostSlotBusy},
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrUrgentPending), codeHostSlotBusy},
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrBusy), "capture_refused"},
{fmt.Errorf("%w: not a healthy primary", storage.ErrChunkCaptureRefused), "capture_refused"},
} {
status, code, retryable := chunkErrorCode(tc.err)
if status != http.StatusServiceUnavailable || code != tc.code || !retryable {
t.Fatalf("%v: %d %s %v; want 503 %s retryable", tc.err, status, code, retryable, tc.code)
}
}
}
@@ -62,7 +62,7 @@ func restoredHostWrites(t *testing.T, inheritedLSN uint64, observerAfterSeed boo
// main.go order: readiness blocked, the assignment (epoch 5) retained.
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1})
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1})
dp, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk,
@@ -59,7 +59,7 @@ func TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend(t *testing.T) {
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
h.applyFact(selfFact(2))
h.applyFixtureFact(selfFact(2))
if a.callCount.Load() != 1 {
t.Fatal("fixture: primary at epoch 2 not adopted")
}
@@ -74,7 +74,7 @@ func TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend(t *testing.T) {
}
fencer.fail.Store(true)
h.applyFact(selfFact(3)) // the epoch advance whose floor persist fails
h.applyFixtureFact(selfFact(3)) // the epoch advance whose floor persist fails
if a.callCount.Load() != 1 {
t.Fatal("the epoch-3 role was adopted though its floor persist failed")
}
@@ -92,7 +92,7 @@ func TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend(t *testing.T) {
}
fencer.fail.Store(false)
h.applyFact(selfFact(3)) // master's stream replay redelivers
h.applyFixtureFact(selfFact(3)) // master's stream replay redelivers
if failed, _ := h.RoleAdmissionFailure(); failed {
t.Fatal("latch not cleared by a successful redelivery")
}
@@ -115,7 +115,7 @@ func TestG1_SupportingAdmissionFailsClosed(t *testing.T) {
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
h.applyFact(&control.AssignmentFact{
h.applyFixtureFact(&control.AssignmentFact{
VolumeId: "vol1", ReplicaId: "rA", Epoch: 2, EndpointVersion: 1,
DataAddr: "127.0.0.1:3", CtrlAddr: "127.0.0.1:4", PeerSetGeneration: 2,
Peers: []*control.ReplicaDescriptor{{ReplicaId: "rB", Epoch: 2, EndpointVersion: 1, DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6"}},
@@ -132,7 +132,7 @@ func TestG1_SupportingAdmissionFailsClosed(t *testing.T) {
// failure is returned (the binary then does not serve) and latched.
func TestG1_SetSelfFenceReturnsTheReplayError(t *testing.T) {
h, _, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{})
h.applyFact(selfFact(2)) // no listener yet: the role is recorded
h.applyFixtureFact(selfFact(2)) // no listener yet: the role is recorded
fencer := &switchFencer{}
fencer.fail.Store(true)
if err := h.SetSelfFence(fencer); err == nil {
@@ -175,7 +175,7 @@ func TestG1_StaleReplayDoesNotClearANewerAdmissionFailure(t *testing.T) {
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
h.applyFact(selfFact(2))
h.applyFixtureFact(selfFact(2))
store := memorywal.NewStore(8, 4096)
t.Cleanup(func() { _ = store.Close() })
backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "rB", Epoch: 2, EndpointVersion: 1})
@@ -184,8 +184,8 @@ func TestG1_StaleReplayDoesNotClearANewerAdmissionFailure(t *testing.T) {
if _, err := backend.Write(ctx, 0, []byte("baseline")); err != nil {
t.Fatal(err)
}
h.applyFact(selfFact(3)) // fails: latched
h.applyFact(selfFact(2)) // stale replay; its role call would succeed
h.applyFixtureFact(selfFact(3)) // fails: latched
h.applyFixtureFact(selfFact(2)) // stale replay; its role call would succeed
if failed, _ := h.RoleAdmissionFailure(); !failed {
t.Fatal("a stale epoch-2 replay cleared the unresolved epoch-3 admission failure")
}
@@ -193,7 +193,7 @@ func TestG1_StaleReplayDoesNotClearANewerAdmissionFailure(t *testing.T) {
t.Fatalf("stale replay reopened writes: %v", err)
}
fencer.failAt.Store(0)
h.applyFact(selfFact(3)) // the current epoch, now durable
h.applyFixtureFact(selfFact(3)) // the current epoch, now durable
if failed, _ := h.RoleAdmissionFailure(); failed {
t.Fatal("the current epoch's success did not clear the latch")
}
@@ -207,10 +207,10 @@ func TestG1_StaleSupportingReplayDoesNotClearTheLatch(t *testing.T) {
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
h.applyFact(supportingFact(2))
h.applyFact(supportingFact(3)) // fails
h.applyFixtureFact(supportingFact(2))
h.applyFixtureFact(supportingFact(3)) // fails
calls := a.callCount.Load()
h.applyFact(supportingFact(2)) // stale
h.applyFixtureFact(supportingFact(2)) // stale
if failed, _ := h.RoleAdmissionFailure(); !failed {
t.Fatal("a stale supporting replay cleared the latch")
}
@@ -218,7 +218,7 @@ func TestG1_StaleSupportingReplayDoesNotClearTheLatch(t *testing.T) {
t.Fatal("a stale supporting replay was admitted")
}
fencer.failAt.Store(0)
h.applyFact(supportingFact(3))
h.applyFixtureFact(supportingFact(3))
if failed, _ := h.RoleAdmissionFailure(); failed {
t.Fatal("the current supporting admission did not clear the latch")
}
@@ -234,8 +234,8 @@ func TestG1_InstallReplayTargetsTheCurrentRole(t *testing.T) {
if err := h.SetSelfFence(failing); err != nil {
t.Fatal(err)
}
h.applyFact(selfFact(3)) // fails
h.applyFact(selfFact(2)) // stale
h.applyFixtureFact(selfFact(3)) // fails
h.applyFixtureFact(selfFact(2)) // stale
recorder := &recordingFencer{}
if err := h.SetSelfFence(recorder); err != nil {
t.Fatalf("install replay: %v", err)
@@ -82,7 +82,7 @@ func TestG2_PromotedHostRefusesShipFromDeposedPrimary(t *testing.T) {
}
// Master promotes B to primary at epoch 2: the production role path.
h.applyFact(&control.AssignmentFact{
h.applyFixtureFact(&control.AssignmentFact{
VolumeId: "vol1",
ReplicaId: "rB", // self
Epoch: 2,
@@ -119,7 +119,7 @@ func (s stubFencer) AdmitAsReplica(uint64) error { return nil }
func TestG2_HostDoesNotAdoptPrimaryWhenItsListenerCannotBeFenced(t *testing.T) {
h, a, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{})
h.SetSelfFence(stubFencer{err: errors.New("2 replication mutation(s) still in flight")})
h.applyFact(&control.AssignmentFact{
h.applyFixtureFact(&control.AssignmentFact{
VolumeId: "vol1",
ReplicaId: "rB",
Epoch: 2,
+29 -13
View File
@@ -187,8 +187,9 @@ type Host struct {
readyMarkerMu sync.Mutex
supportingReadyMarks map[string]struct{}
localReadinessBlocked atomic.Bool
localReadinessReason atomic.Value // string
assignmentEndpointWarning atomic.Value // diagnostic string; never an admission guard
localReadinessBlocked atomic.Bool
localReadinessReason atomic.Value // string
// localRecoveryReason is the typed reason local durable recovery
// failed (#133); empty when none or unclassified.
localRecoveryReason atomic.Value // string
@@ -235,6 +236,11 @@ func (h *Host) recordOtherLine(f *control.AssignmentFact) {
// is the canonical safe deep-copy for proto messages.
cp := proto.Clone(f).(*control.AssignmentFact)
h.otherMu.Lock()
// A stale replay must not erase the newer foreign-holder fence (INV-AUTH-HOLDER-IDENTITY-001).
if old := h.lastOther; old != nil && (cp.Epoch < old.Epoch || cp.Epoch == old.Epoch && cp.EndpointVersion < old.EndpointVersion) {
h.otherMu.Unlock()
return
}
h.lastOther = cp
h.otherMu.Unlock()
}
@@ -390,7 +396,8 @@ func (h *Host) replayLocalReadinessFactIfReady() {
if fact == nil {
return
}
h.log.Printf("blockvolume: volume %s replaying assignment after local readiness cleared", h.cfg.VolumeID)
h.log.Printf("blockvolume: volume %s replaying assignment after local readiness cleared server=%q epoch=%d ev=%d data=%q ctrl=%q",
h.cfg.VolumeID, fact.ServerId, fact.Epoch, fact.EndpointVersion, fact.DataAddr, fact.CtrlAddr)
h.applyFact(fact)
}
@@ -514,21 +521,21 @@ func (h *Host) getReplication() replicaSetUpdater {
return h.replication
}
// IsSuperseded satisfies SupersedeProbe: returns true when this
// host's lastOther record names a DIFFERENT replica at a strictly
// newer (Epoch, EndpointVersion) than the caller's self-lineage.
// Same-replica updates (our own Epoch advance) are NOT supersede
// events; the bridge handles those naturally through adapter
// projection.
// IsSuperseded gates a newer foreign replica line, or a same-replica foreign
// server identity strictly newer than an adopted local lineage. An explicitly
// matching self identity remains an ordinary adapter update.
func (h *Host) IsSuperseded(selfReplicaID string, selfEpoch, selfEV uint64) bool {
h.otherMu.Lock()
defer h.otherMu.Unlock()
if h.lastOther == nil {
if h.lastOther == nil || selfEpoch == 0 {
return false
}
other := h.lastOther
if other.ReplicaId == selfReplicaID {
return false
if h.assignmentNamesSelf(other) {
return false
}
return other.Epoch > selfEpoch || other.Epoch == selfEpoch && other.EndpointVersion > selfEV
}
if other.Epoch > selfEpoch {
return true
@@ -761,6 +768,7 @@ func (h *Host) streamOnce(ctx context.Context) error {
stream, err := h.asnCli.SubscribeAssignments(ctx, &control.SubscribeRequest{
VolumeId: h.cfg.VolumeID,
ReplicaId: h.cfg.ReplicaID,
ServerId: h.cfg.ServerID, // INV-AUTH-HOLDER-IDENTITY-001: the master checks it against the stream's host
})
if err != nil {
return err
@@ -773,6 +781,8 @@ func (h *Host) streamOnce(ctx context.Context) error {
if err != nil {
return err
}
h.log.Printf("blockvolume: assignment stream delivery process=%q server=%q volume=%q replica=%q epoch=%d ev=%d data=%q ctrl=%q",
h.cfg.ServerID, fact.ServerId, fact.VolumeId, fact.ReplicaId, fact.Epoch, fact.EndpointVersion, fact.DataAddr, fact.CtrlAddr)
h.applyFact(fact)
}
}
@@ -803,6 +813,10 @@ func (h *Host) streamOnce(ctx context.Context) error {
// OnAssignment could flip the projection Healthy before peers were
// installed, admitting local-only writes with zero fan-out.
func (h *Host) applyFact(fact *control.AssignmentFact) {
// INV-AUTH-HOLDER-IDENTITY-001: matching r1 and loopback endpoints do not identify a host.
if h.refusePrimaryAssignment(fact) {
return
}
if fact.ReplicaId != h.cfg.ReplicaID {
h.wd.notPrimary()
// Another replica is authoritative for this volume line. Record that
@@ -847,6 +861,8 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
return
}
h.reportAssignmentEndpoints(fact)
// The recovery watchdog runs from the primary assignment, before any
// admission step can fail (#128 rule 6).
h.wd.primaryAssigned(fact.Epoch)
@@ -918,8 +934,8 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
return
}
h.adpt.OnAssignment(info)
h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)",
h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion)
h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d) process=%q server=%q data=%q ctrl=%q",
h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, h.cfg.ServerID, fact.ServerId, fact.DataAddr, fact.CtrlAddr)
if h.cfg.ReadyMarker != nil && info.Epoch > 0 && h.readyOnce.CompareAndSwap(false, true) {
select {
case h.cfg.ReadyMarker <- info:
@@ -227,3 +227,11 @@ func (v *AdapterProjectionView) PromotionReadyFact() engine.PromotionReadyFact {
func (v *AdapterProjectionView) EngineProjection() engine.ReplicaProjection {
return v.projector.Projection()
}
// assignmentEndpointWarning exposes routing disagreement without gating I/O.
func (v *AdapterProjectionView) assignmentEndpointWarning() string {
if p, ok := v.probe.(interface{ AssignmentEndpointWarning() string }); ok {
return p.AssignmentEndpointWarning()
}
return ""
}
@@ -98,7 +98,7 @@ func TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce(t *testing.T) {
if got := h.ReportLocalRecoveryFailure(report.Err); got != UnhealthyWALCorrupt {
t.Fatalf("ReportLocalRecoveryFailure(%v)=%q; want %s", report.Err, got, UnhealthyWALCorrupt)
}
h.applyFact(selfPrimaryFact(1)) // refused by the readiness block, but primary-assigned
h.applyFixtureFact(selfPrimaryFact(1)) // refused by the readiness block, but primary-assigned
if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyWALCorrupt {
t.Fatalf("primary-assigned after corrupt recovery: eligible=%t reason=%q; want ineligible, %s at once", s.Eligible, s.UnhealthyReason, UnhealthyWALCorrupt)
}
@@ -119,14 +119,14 @@ func TestLocalRecoveryFailure_ScopeAndUnclassifiedFallback(t *testing.T) {
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" {
t.Fatalf("not primary-assigned: %+v; want not flagged", s)
}
h.applyFact(selfPrimaryFact(1))
h.applyFixtureFact(selfPrimaryFact(1))
if s := reportSlot(t, h); s.UnhealthyReason != UnhealthyIOError {
t.Fatalf("primary-assigned with an I/O recovery failure: reason=%q; want %s", s.UnhealthyReason, UnhealthyIOError)
}
h2, clk2 := watchdogHost(t, 10*time.Second)
h2.ReportLocalRecoveryFailure(errors.New("unclassified"))
h2.applyFact(selfPrimaryFact(1))
h2.applyFixtureFact(selfPrimaryFact(1))
if s := reportSlot(t, h2); s.UnhealthyReason != "" {
t.Fatalf("unclassified failure inside the timeout: reason=%q; want none yet", s.UnhealthyReason)
}
@@ -46,7 +46,7 @@ func reportSlot(t *testing.T, h *Host) *control.HeartbeatSlot {
// unhealthy (Eligible=false, recovery_timeout) once the timeout elapses.
func TestRecoveryWatchdog_PrimaryNotReadyPastTimeoutReportsUnhealthy(t *testing.T) {
h, clk := watchdogHost(t, 30*time.Second)
h.applyFact(selfPrimaryFact(1))
h.applyFixtureFact(selfPrimaryFact(1))
clk.advance(29 * time.Second)
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" || s.ReadyForPrimary {
@@ -64,8 +64,8 @@ func TestRecoveryWatchdog_PrimaryNotReadyPastTimeoutReportsUnhealthy(t *testing.
// A supporting replica in a long catch-up is never flagged.
func TestRecoveryWatchdog_SupportingReplicaNotFlagged(t *testing.T) {
h, clk := watchdogHost(t, 30*time.Second)
h.applyFact(selfPrimaryFact(1))
h.applyFact(&control.AssignmentFact{ // another replica is now primary
h.applyFixtureFact(selfPrimaryFact(1))
h.applyFixtureFact(&control.AssignmentFact{ // another replica is now primary
VolumeId: "v1", ReplicaId: "r2", Epoch: 2, EndpointVersion: 1,
DataAddr: "127.0.0.1:9301", CtrlAddr: "127.0.0.1:9302",
})
@@ -127,7 +127,7 @@ func TestRecoveryWatchdog_RoleAdmissionFailure(t *testing.T) {
// catch-up state.
func TestRecoveryWatchdog_StatusShowsReasonAndCatchUp(t *testing.T) {
h, clk := watchdogHost(t, time.Second)
h.applyFact(selfPrimaryFact(1))
h.applyFixtureFact(selfPrimaryFact(1))
clk.advance(2 * time.Second)
s := NewStatusServer(h.view)
if got := s.statusProjection().UnhealthyReason; got != UnhealthyRecoveryTimeout {
@@ -148,7 +148,7 @@ func TestRecoveryWatchdog_StatusShowsReasonAndCatchUp(t *testing.T) {
// no recovery_timeout, however long it lasts.
func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) {
h, clk := watchdogHost(t, 10*time.Second)
h.applyFact(selfPrimaryFact(1))
h.applyFixtureFact(selfPrimaryFact(1))
clk.advance(time.Second)
if r := h.unhealthyReason(readyAt(1), true); r != "" {
t.Fatalf("ready: %q", r)
@@ -157,7 +157,7 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) {
if r := h.unhealthyReason(readyAt(1), false); r != "" {
t.Fatalf("not ready an hour after being ready, same incarnation: %q; want no recovery_timeout", r)
}
h.applyFact(selfPrimaryFact(1)) // the same assignment replayed: still disarmed
h.applyFixtureFact(selfPrimaryFact(1)) // the same assignment replayed: still disarmed
clk.advance(time.Hour)
if r := h.unhealthyReason(readyAt(1), false); r != "" {
t.Fatalf("same assignment replayed: %q; want still disarmed", r)
@@ -169,7 +169,7 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) {
// reports recovery_timeout even for the same primary epoch.
func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) {
old, clk := watchdogHost(t, 10*time.Second)
old.applyFact(selfPrimaryFact(1))
old.applyFixtureFact(selfPrimaryFact(1))
if r := old.unhealthyReason(readyAt(1), true); r != "" {
t.Fatalf("old process ready: %q", r)
}
@@ -178,7 +178,7 @@ func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) {
if restarted.incarnation == old.incarnation {
t.Fatalf("restarted process kept incarnation %q", old.incarnation)
}
restarted.applyFact(selfPrimaryFact(1)) // same primary epoch
restarted.applyFixtureFact(selfPrimaryFact(1)) // same primary epoch
clk2.advance(11 * time.Second)
if s := reportSlot(t, restarted); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryTimeout {
t.Fatalf("restarted process past timeout: eligible=%t reason=%q; want ineligible, %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryTimeout)
@@ -213,13 +213,13 @@ func TestRecoveryWatchdog_OldEpochReadyDoesNotDisarmNewAssignment(t *testing.T)
ready := &engine.PromotionReadyFact{Ready: true, Epoch: 2, EndpointVersion: 1, ReplicaID: "rB"}
readyView(h, "vol1", "rB", ready)
h.applyFact(selfFact(2))
h.applyFixtureFact(selfFact(2))
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" {
t.Fatalf("ready primary at epoch 2: %+v", s)
}
repl.returnErr = errors.New("injected: peer set install failed")
h.applyFact(selfFact(3)) // refused: the adapter stays at epoch 2
h.applyFixtureFact(selfFact(3)) // refused: the adapter stays at epoch 2
if a.callCount.Load() != 1 {
t.Fatal("fixture: the epoch-3 assignment was adopted")
}
@@ -247,19 +247,19 @@ func TestRecoveryWatchdog_G1LatchWinsOverOldReady(t *testing.T) {
if err := h.SetSelfFence(fencer); err != nil {
t.Fatal(err)
}
h.applyFact(selfFact(2))
h.applyFixtureFact(selfFact(2))
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" {
t.Fatalf("ready primary at epoch 2: %+v", s)
}
fencer.fail.Store(true)
h.applyFact(selfFact(3)) // role call fails: G1 latch
h.applyFixtureFact(selfFact(3)) // role call fails: G1 latch
if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRoleAdmission {
t.Fatalf("G1 latch with an old ready fact: eligible=%t reason=%q; want %s", s.Eligible, s.UnhealthyReason, UnhealthyRoleAdmission)
}
fencer.fail.Store(false)
h.applyFact(selfFact(3)) // redelivery succeeds
h.applyFixtureFact(selfFact(3)) // redelivery succeeds
*ready = engine.PromotionReadyFact{Ready: true, Epoch: 3, EndpointVersion: 1, ReplicaID: "rB"}
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" {
t.Fatalf("after successful redelivery and an epoch-3 ready fact: eligible=%t reason=%q; want cleared", s.Eligible, s.UnhealthyReason)
+22 -22
View File
@@ -42,7 +42,7 @@ func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) {
h.replication = nil
h.BlockLocalReadiness("awaiting durable recovery")
h.applyFact(rf2PrimaryFact(3)) // stored for replay
h.applyFixtureFact(rf2PrimaryFact(3)) // stored for replay
h.ClearLocalReadinessBlock()
h.replicationMu.Lock()
h.setReplicationLocked(rv) // what SetReplicationVolume does, then it replays
@@ -63,7 +63,7 @@ func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) {
// A supporting-replica fact (another primary lists this replica) is refused too.
sup := rf2PrimaryFact(4)
sup.ReplicaId, sup.Peers[0].ReplicaId = "r2", "r1"
h.applyFact(sup)
h.applyFixtureFact(sup)
if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 {
t.Fatal("supporting replica admitted on an RF1-only volume")
}
@@ -74,7 +74,7 @@ func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) {
// The master moves the volume to RF1: adopted, latch cleared, ready emitted.
rf1 := rf2PrimaryFact(5)
rf1.Peers = nil
h.applyFact(rf1)
h.applyFixtureFact(rf1)
if a.callCount.Load() != 1 || len(ready) != 1 {
t.Fatalf("RF1 primary not adopted: adopt=%d ready=%d", a.callCount.Load(), len(ready))
}
@@ -87,7 +87,7 @@ func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) {
// and is adopted (today's behaviour for replicated volumes).
func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) {
h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{})
h.applyFact(rf2PrimaryFact(3))
h.applyFixtureFact(rf2PrimaryFact(3))
if r.callCount.Load() != 1 || a.callCount.Load() != 1 {
t.Fatalf("replicated fact not applied: peers=%d adopt=%d", r.callCount.Load(), a.callCount.Load())
}
@@ -102,25 +102,25 @@ func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) {
// epoch or newer, once its role is admitted, clears it.
func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) {
f := newRF1BackendHost(t)
f.h.applyFact(rf1Fact(2))
f.h.applyFixtureFact(rf1Fact(2))
if f.a.callCount.Load() != 1 {
t.Fatal("fixture: RF1@2 not adopted")
}
f.mustWrite(t, 2, 0xD2)
f.h.applyFact(rf2PrimaryFact(3))
f.h.applyFixtureFact(rf2PrimaryFact(3))
f.assertRefusedAt(t, 3)
f.h.applyFact(rf1Fact(2)) // stale replay below the refused epoch
f.h.applyFixtureFact(rf1Fact(2)) // stale replay below the refused epoch
f.assertRefusedAt(t, 3)
if f.a.callCount.Load() != 1 || f.r.callCount.Load() != 1 {
t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", f.a.callCount.Load(), f.r.callCount.Load())
}
f.fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal
f.h.applyFact(rf1Fact(3))
f.h.applyFixtureFact(rf1Fact(3))
if _, reason := f.h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || f.a.callCount.Load() != 1 {
t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, f.a.callCount.Load())
}
f.fencer.fail.Store(false)
f.h.applyFact(rf1Fact(3))
f.h.applyFixtureFact(rf1Fact(3))
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
}
@@ -199,22 +199,22 @@ func (f *rf1Fixture) assertRefusedAt(t *testing.T, epoch uint64) {
// clear that newer refusal nor adopt. RF1@3 then admits and serves at epoch 3.
func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) {
f := newRF1BackendHost(t)
f.h.applyFact(rf1Fact(2))
f.h.applyFixtureFact(rf1Fact(2))
f.mustWrite(t, 2, 0xA2)
fired := false
f.h.rf1BeforeAdmit = func() {
if !fired {
fired = true
f.h.applyFact(rf2PrimaryFact(3))
f.h.applyFixtureFact(rf2PrimaryFact(3))
}
}
f.h.applyFact(rf1Fact(2))
f.h.applyFixtureFact(rf1Fact(2))
f.h.rf1BeforeAdmit = nil
if !fired || f.a.callCount.Load() != 1 {
t.Fatalf("fixture fired=%v; held RF1@2 adopted=%d", fired, f.a.callCount.Load())
}
f.assertRefusedAt(t, 3)
f.h.applyFact(rf1Fact(3))
f.h.applyFixtureFact(rf1Fact(3))
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 || f.a.lastInfo.Epoch != 3 {
t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
}
@@ -241,7 +241,7 @@ func (u *holdingUpdater) UpdateReplicaSet(gen uint64, targets []replication.Repl
// replay then resumes. Bounded by timeouts.
func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) {
f := newRF1BackendHost(t)
f.h.applyFact(rf1Fact(2))
f.h.applyFixtureFact(rf1Fact(2))
f.mustWrite(t, 2, 0xB2)
u := &holdingUpdater{inner: f.r, entered: make(chan struct{}), release: make(chan struct{})}
u.armed.Store(true)
@@ -273,14 +273,14 @@ func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) {
}
})
replayStarted = true
go func() { defer close(replay); f.h.applyFact(rf1Fact(2)) }()
go func() { defer close(replay); f.h.applyFixtureFact(rf1Fact(2)) }()
select {
case <-u.entered:
case <-time.After(5 * time.Second):
t.Fatal("replay worker did not reach the peer-set update")
}
streamStarted = true
go func() { defer close(stream); f.h.applyFact(rf2PrimaryFact(3)) }()
go func() { defer close(stream); f.h.applyFixtureFact(rf2PrimaryFact(3)) }()
select {
case <-stream:
case <-time.After(5 * time.Second):
@@ -296,7 +296,7 @@ func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) {
t.Fatalf("parked RF1@2 adopted after the newer refusal: adopt=%d", f.a.callCount.Load())
}
f.assertRefusedAt(t, 3)
f.h.applyFact(rf1Fact(3))
f.h.applyFixtureFact(rf1Fact(3))
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
t.Fatalf("current RF1@3 not admitted: %v %q", failed, reason)
}
@@ -306,18 +306,18 @@ func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) {
// A stale RF2 below an admitted RF1 epoch does not re-latch the refusal.
func TestRF1Only_StaleRF2AfterNewerRF1DoesNotRelatch(t *testing.T) {
f := newRF1BackendHost(t)
f.h.applyFact(rf1Fact(2))
f.h.applyFact(rf2PrimaryFact(3))
f.h.applyFact(rf1Fact(4))
f.h.applyFixtureFact(rf1Fact(2))
f.h.applyFixtureFact(rf2PrimaryFact(3))
f.h.applyFixtureFact(rf1Fact(4))
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
}
f.h.applyFact(rf2PrimaryFact(3)) // stale replay
f.h.applyFixtureFact(rf2PrimaryFact(3)) // stale replay
if failed, reason := f.h.RoleAdmissionFailure(); failed {
t.Fatalf("stale RF2@3 re-latched after RF1@4: %q", reason)
}
f.mustWrite(t, 4, 0xC4)
f.h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused
f.h.applyFixtureFact(rf2PrimaryFact(4)) // same epoch, peers added: refused
if failed, _ := f.h.RoleAdmissionFailure(); !failed {
t.Fatal("RF2 at the admitted epoch not refused")
}
@@ -203,7 +203,7 @@ type StatusProjection struct {
// CatchUp shows a supporting replica's catch-up progress while it is
// not yet replica_ready; it is visible without being an alert.
CatchUp *CatchUpStatus `json:",omitempty"`
// Warnings are the durable store's typed recovery warnings (e.g.
// Warnings include routing disagreements and typed recovery warnings (e.g.
// wal_hole_suspected, issue #51). Visible, not an alert: they do not
// change Healthy or the frontend's readiness.
Warnings []string `json:",omitempty"`
@@ -531,6 +531,9 @@ func (s *StatusServer) authorityProjection() StatusProjection {
RoleAdmissionFailure: s.view.roleAdmissionReason(),
UnhealthyReason: s.view.unhealthyReason(),
}
if warning := s.view.assignmentEndpointWarning(); warning != "" {
out.Warnings = append(out.Warnings, warning)
}
if since := s.view.catchUpSince(); !since.IsZero() && replicationRole != ReplicationRoleReady {
cu := &CatchUpStatus{ElapsedMs: time.Since(since).Milliseconds()}
if ep.H > ep.R {
@@ -62,10 +62,10 @@ func TestHost_RecordOtherLine_SameReplica_NotSuperseded(t *testing.T) {
proj := &mutableProjector{p: engine.ReplicaProjection{
Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 2,
}}
h := &Host{cfg: Config{VolumeID: "v1", ReplicaID: "r1"}}
h := &Host{cfg: Config{ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1"}}
h.view = NewAdapterProjectionView(proj, "v1", "r1", h)
h.recordOtherLine(&control.AssignmentFact{
VolumeId: "v1", ReplicaId: "r1", Epoch: 2, EndpointVersion: 2,
ServerId: "node-a", VolumeId: "v1", ReplicaId: "r1", Epoch: 2, EndpointVersion: 2,
})
if !h.view.Projection().Healthy {
t.Fatal("same-replica lastOther must not trigger supersede")
@@ -0,0 +1,26 @@
package volume
import (
"context"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"testing"
)
func TestWorkspaceLeaseGuardCarriesHolderServerIdentity(t *testing.T) {
seen := ""
client := funcLeaseClient(func(_ context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) {
seen = id.ServerId
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: 1000000000}, nil
})
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1, ServerId: "node-a"}, func(context.Context) (uint64, error) { return 7, nil }, nil)
if err != nil {
t.Fatal(err)
}
if err = g.Refresh(context.Background()); err != nil {
t.Fatal(err)
}
if seen != "node-a" {
t.Fatalf("master saw holder server %q, want node-a", seen)
}
}
@@ -142,7 +142,7 @@ func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseC
if now == nil {
now = time.Now
}
return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch}, stop: stop, now: now, kick: make(chan struct{}, 1), after: time.After}, nil
return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, ServerId: id.ServerId, Epoch: id.Epoch}, stop: stop, now: now, kick: make(chan struct{}, 1), after: time.After}, nil
}
func (g *WorkspaceLeaseGuard) Projection() frontend.Projection {
@@ -32,7 +32,7 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
}
p := h.view.Projection()
if p.Epoch > 0 {
id := &control.WorkspaceIdentity{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, Epoch: p.Epoch}
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 {
return err
@@ -26,7 +26,7 @@ func workspaceRuntimeHost(t *testing.T, addr string, required bool) *Host {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
h.applyFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101"})
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101"})
end := time.Now().Add(time.Second)
for h.realAdpt.Projection().Mode != engine.ModeHealthy && time.Now().Before(end) {
time.Sleep(time.Millisecond)
+56
View File
@@ -0,0 +1,56 @@
package hostlimit
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
// CheckLaunch refuses a host-limit configuration whose premises do not
// hold, before the process uses it. The directory must exist as a real
// directory, outside temporary directories that cleaners empty, on a local
// file system (kernel file locks are not shared reliably over network
// file systems), and a configuration already published there by other
// processes must equal this one. The premise that every process on the
// host uses the same directory cannot be checked from one process.
func CheckLaunch(c Config) error {
return checkLaunch(c, []string{"/tmp", "/var/tmp", "/dev/shm", os.TempDir()}, remoteFS)
}
func checkLaunch(c Config, tempRoots []string, remote func(string) (string, bool)) error {
if err := c.Validate(); err != nil {
return err
}
dir := filepath.Clean(c.Directory)
info, err := os.Lstat(dir)
if err != nil {
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("hostlimit: --host-limit-dir %s must be a directory, not a symlink or a file", dir)
}
for _, root := range tempRoots {
root = filepath.Clean(root)
if root != "" && root != "." && (dir == root || strings.HasPrefix(dir, root+string(filepath.Separator))) {
return fmt.Errorf("hostlimit: --host-limit-dir %s is under %s, which temporary-file cleaners empty", dir, root)
}
}
if fs, isRemote := remote(dir); isRemote {
return fmt.Errorf("hostlimit: --host-limit-dir %s is on %s, a network file system; slot locks need a local one", dir, fs)
}
existing, err := os.ReadFile(filepath.Join(dir, "configuration.json"))
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
}
expected, _ := json.Marshal(c)
if string(existing) != string(expected) {
return fmt.Errorf("hostlimit: --host-limit-dir %s is in use with other host-limit flags (%s); every process on the host must use identical flags (this one: %s)", dir, existing, expected)
}
return nil
}
+32
View File
@@ -23,6 +23,16 @@ var ErrBusy = errors.New("hostlimit: no background slot")
// work: retrying once one is released can succeed. Other ErrBusy results
// (an oversized payload, an unusable pool) do not change by waiting.
var ErrSlotsHeld = fmt.Errorf("%w: every slot is held", ErrBusy)
// ErrUrgentPending refuses a Normal admission while an urgent cut runs or
// a caller holds HoldUrgentPending on the host: new background cuts wait
// for it. It is an ErrSlotsHeld, so waiting callers treat it alike.
var ErrUrgentPending = fmt.Errorf("%w: an urgent cut is pending", ErrSlotsHeld)
// urgentPendingFile is the pool file urgent work holds shared; Normal
// admission probes it exclusively, without waiting. It has no content.
const urgentPendingFile = "urgent-pending"
var ErrConfig = errors.New("hostlimit: incompatible host configuration")
var ErrRevoked = errors.New("hostlimit: cut budget revoked")
@@ -72,6 +82,7 @@ type Stats struct {
}
type lease struct {
file *os.File
pending *os.File // urgent only: the shared hold on urgentPendingFile
started time.Time
class Class
fallback bool
@@ -157,6 +168,20 @@ func (l *Limiter) pool(c Class) (*os.File, error) {
if string(existing) != string(expected) {
return nil, ErrConfig
}
if c == Normal {
probe, err := open(urgentPendingFile)
if err != nil {
return nil, err
}
err = tryLock(probe)
_ = probe.Close()
if errors.Is(err, ErrBusy) {
return nil, ErrUrgentPending
}
if err != nil {
return nil, err
}
}
names := []string{}
if c == BackgroundFill || c == Idle {
n, prefix := l.cfg.FillSlots, "fill"
@@ -299,6 +324,10 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (
l.next++
id := l.next
x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort}
if c == Urgent && !fallback {
// Best effort: an urgent cut that cannot signal still runs.
x.pending, _ = holdShared(filepath.Join(l.cfg.Directory, urgentPendingFile))
}
l.live[id] = x
l.stats.Admitted++
l.stats.PayloadReserved += payload
@@ -399,6 +428,9 @@ func (l *Limiter) releaseLoop() {
if x.file != nil {
_ = x.file.Close()
}
if x.pending != nil {
_ = x.pending.Close()
}
l.mu.Lock()
delete(l.live, id)
l.fallback = false
@@ -80,6 +80,12 @@ func TestSlotsUrgentAndJoinedRelease(t *testing.T) {
a.Release(x)
a.Release(x)
settled(t, a)
// A free normal slot is not taken while the urgent cut runs.
if _, e = d.Admit(context.Background(), 1, nil); !errors.Is(e, ErrUrgentPending) {
t.Fatalf("normal admission during an urgent cut: %v", e)
}
b.Release(y)
settled(t, b)
z, e := d.Admit(context.Background(), 1, nil)
if e != nil {
t.Fatal(e)
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
}
return err
}
// lockShared waits for a shared lock on f. An exclusive holder keeps it
// only for a non-blocking probe, so the wait is short.
func lockShared(f *os.File) error {
return syscall.Flock(int(f.Fd()), syscall.LOCK_SH)
}
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
}
return err
}
// lockShared waits for a shared lock on f. An exclusive holder keeps it
// only for a non-blocking probe, so the wait is short.
func lockShared(f *os.File) error {
return windows.LockFileEx(windows.Handle(f.Fd()), 0, 0, 1, 0, &windows.Overlapped{})
}
+33
View File
@@ -0,0 +1,33 @@
package hostlimit
import (
"os"
"path/filepath"
)
// HoldUrgentPending tells every limiter using dir that urgent work is
// pending on the host: until release is called, Normal admissions there
// are refused with ErrUrgentPending. Callers hold it across a stop or a
// drain, so background cuts do not take slots the stop is waiting for.
func HoldUrgentPending(dir string) (release func(), err error) {
f, err := holdShared(filepath.Join(dir, urgentPendingFile))
if err != nil {
return nil, err
}
return func() { _ = f.Close() }, nil
}
func holdShared(path string) (*os.File, error) {
if i, err := os.Lstat(path); err == nil && !i.Mode().IsRegular() {
return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrInvalid}
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err = lockShared(f); err != nil {
_ = f.Close()
return nil, err
}
return f, nil
}
@@ -0,0 +1,110 @@
package hostlimit
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// While a caller holds HoldUrgentPending, Normal admissions on the host
// wait (ErrUrgentPending, an ErrSlotsHeld); urgent ones still run.
func TestNormalWaitsWhileUrgentPendingIsHeld(t *testing.T) {
c := testConfig(t)
l := newTest(t, c)
release, err := HoldUrgentPending(c.Directory)
if err != nil {
t.Fatal(err)
}
if id, err := l.Acquire(context.Background(), Normal, nil); id != 0 || !errors.Is(err, ErrUrgentPending) || !errors.Is(err, ErrSlotsHeld) {
t.Fatalf("normal admission with an urgent pending: id=%d err=%v", id, err)
}
id, err := l.Acquire(context.Background(), Urgent, nil)
if err != nil {
t.Fatalf("urgent admission refused: %v", err)
}
l.Release(id)
release()
waitAdmitted(t, l, Normal)
}
// An urgent cut holds the pending signal for its lease: another process's
// Normal admission waits until the urgent cut is released.
func TestUrgentLeaseHoldsThePendingSignal(t *testing.T) {
c := testConfig(t)
a, b := newTest(t, c), newTest(t, c)
id, err := a.Acquire(context.Background(), Urgent, nil)
if err != nil {
t.Fatal(err)
}
if _, err := b.Acquire(context.Background(), Normal, nil); !errors.Is(err, ErrUrgentPending) {
t.Fatalf("normal admission during an urgent lease: %v", err)
}
a.Release(id)
waitAdmitted(t, b, Normal)
}
func waitAdmitted(t *testing.T, l *Limiter, c Class) {
t.Helper()
for deadline := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) {
id, err := l.Acquire(context.Background(), c, nil)
if err == nil {
l.Release(id)
return
}
if time.Now().After(deadline) {
t.Fatalf("still refused after the pending signal ended: %v", err)
}
}
}
func TestCheckLaunch(t *testing.T) {
local := func(string) (string, bool) { return "", false }
c := testConfig(t)
if err := checkLaunch(c, nil, local); err != nil {
t.Fatalf("a fresh local directory refused: %v", err)
}
refused := map[string]struct {
c Config
roots []string
remote func(string) (string, bool)
want string
}{
"missing": {DefaultConfig(filepath.Join(c.Directory, "missing")), nil, local, "missing"},
"temp root": {c, []string{filepath.Dir(c.Directory)}, local, "temporary-file cleaners"},
"remote": {c, nil, func(string) (string, bool) { return "NFS", true }, "network file system"},
}
file := filepath.Join(t.TempDir(), "f")
if err := os.WriteFile(file, nil, 0o600); err != nil {
t.Fatal(err)
}
refused["file"] = struct {
c Config
roots []string
remote func(string) (string, bool)
want string
}{DefaultConfig(file), nil, local, "must be a directory"}
for name, tc := range refused {
if err := checkLaunch(tc.c, tc.roots, tc.remote); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("%s: %v; want %q", name, err, tc.want)
}
}
// A configuration published by other processes must be identical.
l := newTest(t, c)
id, err := l.Acquire(context.Background(), Normal, nil)
if err != nil {
t.Fatal(err)
}
l.Release(id)
if err := checkLaunch(c, nil, local); err != nil {
t.Fatalf("the same flags refused: %v", err)
}
other := c
other.NormalSlots = 3
if err := checkLaunch(other, nil, local); err == nil || !strings.Contains(err.Error(), "identical flags") {
t.Fatalf("different flags accepted: %v", err)
}
}
@@ -0,0 +1,24 @@
//go:build linux
package hostlimit
import "syscall"
// remoteFS names the network file system dir is on, if it is on one.
func remoteFS(dir string) (string, bool) {
var st syscall.Statfs_t
if syscall.Statfs(dir, &st) != nil {
return "", false
}
switch uint32(st.Type) {
case 0x6969:
return "NFS", true
case 0xFF534D42:
return "CIFS", true
case 0xFE534D42:
return "SMB2", true
case 0x65735546:
return "FUSE", true
}
return "", false
}
@@ -0,0 +1,6 @@
//go:build !linux
package hostlimit
// remoteFS reports no network file system where it cannot tell.
func remoteFS(string) (string, bool) { return "", false }
+28 -3
View File
@@ -64,9 +64,10 @@ type NodeRegistration struct {
// NodeInventoryStore persists one JSON registration record per server.
type NodeInventoryStore struct {
mu sync.Mutex
dir string
records map[string]NodeRegistration
mu sync.Mutex
dir string
records map[string]NodeRegistration
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
}
// OpenNodeInventoryStore opens or creates a node inventory store.
@@ -84,9 +85,31 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) {
if err := s.load(); err != nil {
return nil, err
}
for id, rec := range s.records {
s.published.Store(id, copyNodeRegistration(rec))
}
return s, nil
}
// GetNodeSnapshot returns the last committed registration of serverID without taking the store mutex, which writers
// hold across file I/O: a lease renewal's holder host check never waits behind a registration write. The result is a
// copy (INV-WS-RENEW-NONBLOCKING-001, INV-AUTH-HOLDER-IDENTITY-001).
func (s *NodeInventoryStore) GetNodeSnapshot(serverID string) (NodeRegistration, bool) {
v, ok := s.published.Load(serverID)
if !ok {
return NodeRegistration{}, false
}
return copyNodeRegistration(v.(NodeRegistration)), true
}
// HoldWritesForTest takes the mutex a registration write holds across file I/O and returns its release (idempotent):
// a held registration write, for controls that a reader (the holder host check) never waits on it. Tests only.
func (s *NodeInventoryStore) HoldWritesForTest() (release func()) {
s.mu.Lock()
var once sync.Once
return func() { once.Do(s.mu.Unlock) }
}
// RegisterNode records the latest observed inventory for a server.
// Repeating registration replaces observation fields, but still does not
// publish authority or readiness.
@@ -104,6 +127,7 @@ func (s *NodeInventoryStore) RegisterNode(reg NodeRegistration) (NodeRegistratio
return NodeRegistration{}, err
}
s.records[reg.ServerID] = reg
s.published.Store(reg.ServerID, copyNodeRegistration(reg)) // committed: the file is in place
return reg, nil
}
@@ -119,6 +143,7 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error {
if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
}
s.published.Delete(serverID) // committed: the file is gone
return nil
}
@@ -0,0 +1,83 @@
package lifecycle
import (
"sync"
"testing"
"time"
)
// INV-WS-RENEW-NONBLOCKING-001 + INV-AUTH-HOLDER-IDENTITY-001: the holder host check reads the node registry from a
// committed snapshot, so a lease renewal never waits behind a registration write (which holds the store mutex across
// file I/O). The snapshot is a copy, survives a reopen, and a removed node is unpublished.
func TestNodeSnapshotDoesNotWaitForARegistrationWrite(t *testing.T) {
dir := t.TempDir()
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.RegisterNode(NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"}); err != nil {
t.Fatal(err)
}
s.mu.Lock() // the mutex RegisterNode holds across file I/O: a held registration write
var once sync.Once
release := func() { once.Do(s.mu.Unlock) }
result := make(chan NodeRegistration, 1)
joined := make(chan struct{})
t.Cleanup(func() {
release()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("snapshot reader did not join")
}
})
go func() { defer close(joined); r, _ := s.GetNodeSnapshot("node-a"); result <- r }()
var got NodeRegistration
select {
case got = <-result:
case <-time.After(time.Second):
t.Fatal("node snapshot waited for a held registration write")
}
// control: the mutex-taking read does wait while the write is held
blocked := make(chan struct{})
go func() { _, _ = s.GetNode("node-a"); close(blocked) }()
t.Cleanup(func() {
release()
select {
case <-blocked:
case <-time.After(5 * time.Second):
t.Error("control reader did not join")
}
})
select {
case <-blocked:
t.Fatal("control: GetNode did not wait for the held registration write")
case <-time.After(200 * time.Millisecond):
}
release()
select {
case <-blocked:
case <-time.After(5 * time.Second):
t.Fatal("control reader did not finish after the release")
}
if got.DataAddr != "127.0.0.1:19101" {
t.Fatalf("wrong committed registration: %+v", got)
}
got.DataAddr = "changed-by-reader"
if again, _ := s.GetNodeSnapshot("node-a"); again.DataAddr != "127.0.0.1:19101" {
t.Fatal("caller mutated the published registration")
}
reopened, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
if r, ok := reopened.GetNodeSnapshot("node-a"); !ok || r.DataAddr != "127.0.0.1:19101" {
t.Fatal("reopened snapshot lost the registration")
}
if err := s.RemoveNode("node-a"); err != nil {
t.Fatal(err)
}
if _, ok := s.GetNodeSnapshot("node-a"); ok {
t.Fatal("removed node remained published")
}
}
@@ -35,9 +35,10 @@ type PlacementIntent struct {
// PlacementIntentStore persists one placement intent per volume.
type PlacementIntentStore struct {
mu sync.Mutex
dir string
records map[string]PlacementIntent
mu sync.Mutex
dir string
records map[string]PlacementIntent
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
}
// OpenPlacementIntentStore opens or creates a placement intent store.
@@ -55,6 +56,9 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
if err := s.load(); err != nil {
return nil, err
}
for volume, rec := range s.records {
s.published.Store(volume, copyPlacementIntent(rec))
}
return s, nil
}
@@ -90,6 +94,7 @@ func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, e
return PlacementIntent{}, err
}
s.records[intent.VolumeID] = intent
s.published.Store(intent.VolumeID, copyPlacementIntent(intent))
return copyPlacementIntent(intent), nil
}
@@ -101,10 +106,11 @@ func (s *PlacementIntentStore) DeletePlacement(volumeID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.records, volumeID)
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove placement intent %s: %w", volumeID, err)
}
delete(s.records, volumeID)
s.published.Delete(volumeID)
return nil
}
@@ -116,6 +122,17 @@ func (s *PlacementIntentStore) GetPlacement(volumeID string) (PlacementIntent, b
return copyPlacementIntent(rec), ok
}
// GetPlacementSnapshot reads only committed placement, without waiting for a
// writer's filesystem I/O (INV-WS-RENEW-NONBLOCKING-001). The returned slice
// is a copy: a caller cannot change the published holder membership.
func (s *PlacementIntentStore) GetPlacementSnapshot(volumeID string) (PlacementIntent, bool) {
value, ok := s.published.Load(volumeID)
if !ok {
return PlacementIntent{}, false
}
return copyPlacementIntent(value.(PlacementIntent)), true
}
// ListPlacements returns intents ordered by VolumeID.
func (s *PlacementIntentStore) ListPlacements() []PlacementIntent {
s.mu.Lock()
@@ -0,0 +1,147 @@
package lifecycle
import (
"os"
"path/filepath"
"reflect"
"sync"
"testing"
"time"
)
// INV-WS-RENEW-NONBLOCKING-001: holder lookup cannot wait behind placement
// store I/O. A committed snapshot is also isolated from caller mutation.
func TestPlacementSnapshotDoesNotWaitForWriter(t *testing.T) {
dir := t.TempDir()
s, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err = s.ApplyPlan(PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []PlacementCandidate{{VolumeID: "v", ServerID: "node-a", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
s.mu.Lock() // the mutex a writer owns across filesystem I/O
var once sync.Once
release := func() { once.Do(s.mu.Unlock) }
result := make(chan PlacementIntent, 1)
joined := make(chan struct{})
t.Cleanup(func() {
release()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("snapshot reader did not join")
}
})
go func() { defer close(joined); r, _ := s.GetPlacementSnapshot("v"); result <- r }()
var got PlacementIntent
select {
case got = <-result:
case <-time.After(time.Second):
t.Fatal("holder snapshot waited for placement writer")
}
release()
if len(got.Slots) != 1 || got.Slots[0].ServerID != "node-a" {
t.Fatalf("wrong committed holder: %+v", got)
}
got.Slots[0].ServerID = "changed-by-reader"
again, _ := s.GetPlacementSnapshot("v")
if again.Slots[0].ServerID != "node-a" {
t.Fatal("caller mutated published holder")
}
reopened, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
if got, ok := reopened.GetPlacementSnapshot("v"); !ok || got.Slots[0].ServerID != "node-a" {
t.Fatal("reopened snapshot lost holder")
}
if err = s.DeletePlacement("v"); err != nil {
t.Fatal(err)
}
if _, ok := s.GetPlacementSnapshot("v"); ok {
t.Fatal("deleted placement remained published")
}
}
// INV-WS-RENEW-NONBLOCKING-001: publication is a committed view, not a
// speculative plan. Force a real replace/remove failure, without a hook.
func TestPlacementSnapshotFailedCommitStaysCommitted(t *testing.T) {
for _, op := range []string{"create", "replace", "delete"} {
t.Run(op, func(t *testing.T) {
dir := t.TempDir()
s, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
plan := PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []PlacementCandidate{{VolumeID: "v", ServerID: "node-a", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
path := filepath.Join(dir, "v.json")
var saved []byte
if op != "create" {
if _, err = s.ApplyPlan(plan); err != nil {
t.Fatal(err)
}
saved, err = os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
}
before, existed := s.GetPlacementSnapshot("v")
// A nonempty directory at the record path makes both replace and delete
// fail after validation, on Windows and Linux, even when run as root.
if err = os.Mkdir(path, 0755); err != nil {
t.Fatal(err)
}
blocker := filepath.Join(path, "blocker")
if err = os.WriteFile(blocker, []byte("owned test fixture"), 0600); err != nil {
t.Fatal(err)
}
plan.Candidates[0].ServerID = "node-b"
if op == "delete" {
err = s.DeletePlacement("v")
} else {
_, err = s.ApplyPlan(plan)
}
if err == nil {
t.Fatal("fixture did not fail commit")
}
got, ok := s.GetPlacementSnapshot("v")
if ok != existed || !reflect.DeepEqual(got, before) {
t.Fatalf("failed %s published %+v/%t instead of %+v/%t", op, got, ok, before, existed)
}
current, present := s.GetPlacement("v")
if present != existed || !reflect.DeepEqual(current, before) {
t.Fatal("failed commit changed the store's current placement")
}
if err = os.Remove(blocker); err != nil {
t.Fatal(err)
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
if saved != nil {
if err = os.WriteFile(path, saved, 0600); err != nil {
t.Fatal(err)
}
}
reopened, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
got, ok = reopened.GetPlacementSnapshot("v")
if ok != existed || !reflect.DeepEqual(got, before) {
t.Fatal("reopen did not retain the committed placement")
}
if _, err = s.ApplyPlan(plan); err != nil {
t.Fatal("unblocked commit", err)
}
got, ok = s.GetPlacementSnapshot("v")
if !ok || len(got.Slots) != 1 || got.Slots[0].ServerID != "node-b" {
t.Fatal("committed replacement not published", got, ok)
}
})
}
}
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -26,6 +26,7 @@ type WorkspaceIdentity struct {
VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
ReplicaId string `protobuf:"bytes,2,opt,name=replica_id,json=replicaId,proto3" json:"replica_id,omitempty"`
Epoch uint64 `protobuf:"varint,3,opt,name=epoch,proto3" json:"epoch,omitempty"`
ServerId string `protobuf:"bytes,4,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -81,6 +82,13 @@ func (x *WorkspaceIdentity) GetEpoch() uint64 {
return 0
}
func (x *WorkspaceIdentity) GetServerId() string {
if x != nil {
return x.ServerId
}
return ""
}
type WorkspaceVolume struct {
state protoimpl.MessageState `protogen:"open.v1"`
VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
@@ -1122,12 +1130,13 @@ var File_workspace_proto protoreflect.FileDescriptor
const file_workspace_proto_rawDesc = "" +
"\n" +
"\x0fworkspace.proto\x12\x17seaweedfs.block.control\"e\n" +
"\x0fworkspace.proto\x12\x17seaweedfs.block.control\"\x82\x01\n" +
"\x11WorkspaceIdentity\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1d\n" +
"\n" +
"replica_id\x18\x02 \x01(\tR\treplicaId\x12\x14\n" +
"\x05epoch\x18\x03 \x01(\x04R\x05epoch\".\n" +
"\x05epoch\x18\x03 \x01(\x04R\x05epoch\x12\x1b\n" +
"\tserver_id\x18\x04 \x01(\tR\bserverId\".\n" +
"\x0fWorkspaceVolume\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\tR\bvolumeId\"\x10\n" +
"\x0eWorkspaceEmpty\"\xc8\x01\n" +
@@ -170,6 +170,10 @@ message FrontendTarget {
uint32 lun = 5;
uint32 nsid = 6;
string transport = 7; // NVMe: "tcp" (default) | "rdma"; empty for iSCSI
// the replica this frontend belongs to (StatusResponse): a CSI client publishes a target only when the primary
// replica has a usable frontend; another replica's frontend is at most an extra path to the same target
// (INV-AUTH-HOLDER-IDENTITY-001)
string replica_id = 8;
}
message HeartbeatAck {
@@ -186,6 +190,9 @@ message SubscribeRequest {
string volume_id = 1;
string replica_id = 2;
uint64 resume_epoch = 3; // delivery hint only; does NOT influence authority
// the subscriber's --server-id: for a workspace volume the master delivers the line only to a registered server
// id whose stream comes from its registered host (INV-AUTH-HOLDER-IDENTITY-001)
string server_id = 4;
}
// ReplicaDescriptor — one entry in an AssignmentFact.peers list.
@@ -236,6 +243,9 @@ message AssignmentFact {
// protection; fake-master / test harnesses MAY use 0 for
// unversioned apply (does not advance the monotonic guard).
uint64 peer_set_generation = 8;
// Required holder identity. Empty (pre-release master) is never adopted.
string server_id = 9;
}
message StatusRequest {
+1 -1
View File
@@ -21,7 +21,7 @@ service WorkspaceService {
// write): advisory, re-checked by MoveWorkspace.
rpc PreviewWorkspaceMove(WorkspaceMove) returns (WorkspaceMovePreview);
}
message WorkspaceIdentity { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; }
message WorkspaceIdentity { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; string server_id = 4; }
message WorkspaceVolume { string volume_id = 1; }
message WorkspaceEmpty {}
message WorkspaceLeaseFact {
+21 -1
View File
@@ -244,6 +244,9 @@ type chunkLSNMapV3 struct {
syncFile func() error
syncDirectory func() error
latchPersistence func(error)
// testBeforeLiveSnapshot runs in prepareLockedV3 just before the live-set
// snapshot (tests only: a publication landing there).
testBeforeLiveSnapshot func()
// liveMu guards live (chunk_map_extents_v3.go); never held across I/O.
liveMu sync.Mutex
live chunkMapLiveV3
@@ -370,7 +373,24 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
// The live set: every page and root extent a live root references.
// Roots are only added here (under m.mu); the publisher's report only
// removes them, so this snapshot is a superset for the whole prepare.
used, liveBytes := usedPagesV3(m.liveSnapshotV3())
// Every root publisher (the flusher's checkpoint, the chunk layer's
// captured-map publication, BASE complete) prepares through here, and a
// caller captured prior before this prepare: a publication in between can
// have released it (INV-WAL-V3-MAP-PRIOR-LIVE-001). Its pages are reused
// only if it is live in the same liveMu section as this snapshot; then its
// extents are in `used`, nothing else allocates while m.mu is held, and the
// candidate below pins every page it references, the reused ones included.
// Otherwise the prepare is refused, not latched, and retried by the caller
// from the current root.
if h := m.testBeforeLiveSnapshot; h != nil {
h()
}
live, priorLive := m.liveSnapshotWithPriorV3(prior)
if !priorLive {
m.live.priorRefused.Add(1)
return nil, mapCoverageRefusal("prior_released")
}
used, liveBytes := usedPagesV3(live)
defer func() {
if err != nil {
m.failed = err
@@ -36,16 +36,18 @@ type mapRootExtentsV3 struct {
// chunkMapLiveV3 is the live set of one owned map.
type chunkMapLiveV3 struct {
roots map[mapRootKeyV3]mapRootExtentsV3
inflight map[mapRootKeyV3]bool
truncations atomic.Uint64
fileBytes atomic.Uint64 // set at open, after each prepare and truncation
roots map[mapRootKeyV3]mapRootExtentsV3
inflight map[mapRootKeyV3]bool
truncations atomic.Uint64
priorRefused atomic.Uint64 // prepares refused because their prior root was released
fileBytes atomic.Uint64 // set at open, after each prepare and truncation
}
// ChunkMapStats reports the owned map file's size, the bytes its live roots
// reference, and how many times its free tail was truncated.
// reference, how many times its free tail was truncated, and how many
// prepares were refused because their prior root had been released.
type ChunkMapStats struct {
FileBytes, LiveBytes, Truncations uint64
FileBytes, LiveBytes, Truncations, PriorReleased uint64
}
// registerRootV3 records a slot-named root read at open. Caller holds no lock
@@ -112,13 +114,26 @@ func (p *preparedMapPublicationV3) abandonV3() {
// liveSnapshotV3 copies the live roots' extents under liveMu.
func (m *chunkLSNMapV3) liveSnapshotV3() []mapRootExtentsV3 {
out, _ := m.liveSnapshotWithPriorV3(nil)
return out
}
// liveSnapshotWithPriorV3 copies the live roots' extents and reports whether
// prior's root is still live, in ONE liveMu section
// (INV-WAL-V3-MAP-PRIOR-LIVE-001): the prior's extents are then in the
// snapshot exactly when the prepare may reuse its pages. A nil prior is live.
func (m *chunkLSNMapV3) liveSnapshotWithPriorV3(prior *chunkMapCandidateV3) ([]mapRootExtentsV3, bool) {
m.liveMu.Lock()
defer m.liveMu.Unlock()
priorLive := true
if prior != nil {
_, priorLive = m.live.roots[mapRootKeyV3{prior.rootOffset, prior.generation}]
}
out := make([]mapRootExtentsV3, 0, len(m.live.roots))
for _, x := range m.live.roots {
out = append(out, x)
}
return out
return out, priorLive
}
// usedPagesV3 returns the sorted, distinct 4 KiB page indexes a live-set
@@ -205,7 +220,7 @@ func (a *extentAllocatorV3) alloc(n uint64) uint64 {
// bytes are computed on demand from a snapshot.
func (m *chunkLSNMapV3) Stats() ChunkMapStats {
_, live := usedPagesV3(m.liveSnapshotV3())
return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load()}
return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load(), PriorReleased: m.live.priorRefused.Load()}
}
// ChunkMapStatsV3 reports the owned map file's bounded-growth counters, or
@@ -511,3 +511,114 @@ func TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned(t *testing.T)
t.Fatalf("reopen selected map generation %d, want the durable one %d", g, prepared.candidate.generation)
}
}
// INV-WAL-V3-MAP-PRIOR-LIVE-001. A preparer captures prior (the current root)
// and releases the descriptor lock before it prepares. If, in that gap,
// another preparer publishes a new root and a second publication (a W sync or
// a rollover) writes it into the other slot, prior is released: its extents
// are free in the live snapshot. A prepare from that prior must not lend its
// page references: the same prepare may allocate its own page or root into
// the released extent, and the candidate then names a page whose bytes no
// longer match its hash (the next open fails). Prepare refuses a released
// prior without latching; a prepare from the current root then succeeds.
func TestChunkMapExtentsV3ReleasedPriorIsRefused(t *testing.T) {
m, d, path := extentsMapV3(t)
same := []chunkLSNEntryV3{{LSN: 500}}
c1, err := m.Prepare(1, 7, same, nil)
if err != nil {
t.Fatal(err)
}
publishV3(m, d, c1, c1) // both slots name c1; the flusher captures prior = c1
c2 := prepV3(t, m, 2, c1) // the chunk layer's cut: the page is rewritten
publishV3(m, d, c2, c1) // slot A names c2, slot B still c1
publishV3(m, d, c2, c2) // the next publication: neither slot names c1 (released)
c3, err := m.Prepare(3, 7, same, c1) // the flusher's prepare from its captured prior
if err == nil {
_, _, openErr := openChunkLSNMapV3(path, c3.descriptor(d), m.chunkBlocks)
t.Fatalf("prepare from a released prior succeeded: page ref %d reused, root at %d; opening the candidate: %v",
c3.refs[0].Offset, c3.rootOffset, openErr)
}
if !errors.Is(err, ErrMapCoverageStale) {
t.Fatalf("prepare from a released prior: %v, want a map coverage refusal", err)
}
if m.failed != nil {
t.Fatalf("the refusal latched the map: %v", m.failed)
}
if st := m.Stats(); st.PriorReleased != 1 {
t.Fatalf("PriorReleased %d, want the refusal counted once", st.PriorReleased)
}
c4, err := m.Prepare(3, 7, same, c2)
if err != nil {
t.Fatalf("prepare from the current root after the refusal: %v", err)
}
m2, _, err := openChunkLSNMapV3(path, c4.descriptor(d), m.chunkBlocks)
if err != nil {
t.Fatalf("open of the candidate prepared from the current root: %v", err)
}
m2.Close()
}
// INV-WAL-V3-MAP-PRIOR-LIVE-001, the release landing INSIDE the prepare, just
// before its live-set snapshot (the hook): the liveness check must sit in the
// snapshot's own liveMu section. Mutant: the check in a separate section
// before the snapshot passes while prior is live, the release lands, and the
// candidate reuses prior's page while its root takes that extent (the open
// fails the page hash).
func TestChunkMapExtentsV3ReleasedPriorIsRefusedInsideThePrepare(t *testing.T) {
m, d, path := extentsMapV3(t)
same := []chunkLSNEntryV3{{LSN: 500}}
c1, err := m.Prepare(1, 7, same, nil)
if err != nil {
t.Fatal(err)
}
publishV3(m, d, c1, c1)
c2 := prepV3(t, m, 2, c1)
m.testBeforeLiveSnapshot = func() {
m.testBeforeLiveSnapshot = nil
publishV3(m, d, c2, c1) // the other publisher, then the next publication:
publishV3(m, d, c2, c2) // c1 is released while this prepare runs
}
c3, err := m.Prepare(3, 7, same, c1)
if err == nil {
_, _, openErr := openChunkLSNMapV3(path, c3.descriptor(d), m.chunkBlocks)
t.Fatalf("prepare whose prior was released before its snapshot succeeded: page ref %d, root at %d; opening the candidate: %v",
c3.refs[0].Offset, c3.rootOffset, openErr)
}
if !errors.Is(err, ErrMapCoverageStale) || m.failed != nil {
t.Fatalf("refusal %v, latched %v: want a non-latching map coverage refusal", err, m.failed)
}
}
// INV-WAL-V3-MAP-PRIOR-LIVE-001, the release landing AFTER the prepare,
// before the candidate's publication: the candidate is in flight and pins
// every page it references, the reused ones included, so a later prepare
// cannot take them and the candidate stays readable. Mutant: registering the
// candidate with only its newly written extents lets the next prepare
// overwrite the reused page.
func TestChunkMapExtentsV3InFlightCandidatePinsItsReusedPages(t *testing.T) {
m, d, path := extentsMapV3(t)
same := []chunkLSNEntryV3{{LSN: 500}}
c1, err := m.Prepare(1, 7, same, nil)
if err != nil {
t.Fatal(err)
}
publishV3(m, d, c1, c1)
c2 := prepV3(t, m, 2, c1)
c3, err := m.Prepare(3, 7, same, c1) // prior live: c3 reuses c1's page
if err != nil {
t.Fatal(err)
}
if c3.refs[0] != c1.refs[0] {
t.Fatalf("setup: c3 page ref %+v, want c1's reused %+v", c3.refs[0], c1.refs[0])
}
publishV3(m, d, c2, c1)
publishV3(m, d, c2, c2) // c1 released; c3 (gen 3 > current 2) still in flight
if _, err := m.Prepare(4, 7, []chunkLSNEntryV3{{LSN: 900}}, c2); err != nil {
t.Fatal(err)
}
m2, _, err := openChunkLSNMapV3(path, c3.descriptor(d), m.chunkBlocks)
if err != nil {
t.Fatalf("in-flight candidate unreadable after a later prepare: %v", err)
}
m2.Close()
}
@@ -354,14 +354,14 @@ Lease states:
```mermaid
stateDiagram-v2
state "Lease (blockmaster)" as L {
[*] --> Granted: first Renew after bind
[*] --> Granted: first Renew after bind (registered server id, from its registered host)
[*] --> Granted: move issue starts the new holder's lease
Granted --> Granted: Renew before horizon and deadline (from memory)
Granted --> Granted: Renew before horizon and deadline (from memory; registered server id, from its registered host)
Granted --> Revoking: BeginWorkspaceRevocation
Revoking --> Acked: host acks detached HEAD gen while the lease is valid
Revoking --> Acked: host acks detached HEAD gen while the lease is valid (from its registered host)
Acked --> Moved: CLEAN move, including same host, new epoch
Granted --> Expired: horizon or deadline passes
Expired --> Granted: unchanged holder, no move/revocation, MAX expiry + skew passed; durable re-grant
Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant
Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted)
}
```
+160 -82
View File
@@ -30,6 +30,7 @@ The design is described in three documents, and this one collects their machines
- [Part C. Change rules](#part-c-change-rules)
- [Part D. Wait ownership](#part-d-wait-ownership)
- [Part E. Quantities](#part-e-quantities)
- [Part T. Terms bound to code](#part-t-terms-bound-to-code)
---
@@ -47,6 +48,7 @@ stateDiagram-v2
Opened --> Recovering: RecoverVolume
Recovering --> Serving: Recover ok, backend operational
Recovering --> RecoveryFailed: Recover error (typed reason)
Serving --> Serving: map prepare refused (prior root released, no latch, retry)
Serving --> FaultLatched: fsync or WAL append fails
FaultLatched --> Closed: Close
RecoveryFailed --> Closed: Close
@@ -61,7 +63,8 @@ stateDiagram-v2
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001` |
| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` |
| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` |
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` |
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` |
| Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` |
| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` |
| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` |
| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — |
@@ -90,18 +93,50 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
**Workspace lease and move, in blockmaster.**
TERM-HOLDER-001 uses one deciding function, `Host.workspaceLineOwner`. The
stream supplies the PublishedLine captured in its AssignmentInfo; lease/ACK
checks supply the captured leaf view; move source uses a leaf snapshot wrapper.
`Publisher.captureAssignmentOwner` captures the moved owner under the publication
lock and reloads it from that durable record's workspace journal. A moved line
with unknown owner sends an empty server id; only a move-less line falls back to
placement. Renewal never enters the publisher store-write lock for this lookup.
The stream regression injects an unavailable journal at encoding time; it does
not claim that a pre-issued publication is reachable in the current publisher.
```mermaid
flowchart LR
Reserved[Move reserved] --> Capture[Issue: capture line and moved owner under pub.mu]
Capture --> Durable[Persist line and issuing journal together]
Durable --> Published[Publish assignment and derived lease view]
Published --> Stream[Stream encodes captured line via workspaceLineOwner]
Published --> Lease[Lease and ACK use captured leaf owner]
Stream --> Known[Known moved owner: same server id]
Stream --> Unknown[Unknown moved owner: empty server id]
Stream --> Initial[Move-less epoch: placement owner]
```
Model trace: [WorkspaceRegrant round 4 pins and simulation results](../spec/WorkspaceRegrant-owner-label-results.md)
binds the owner-label switch, five configurations and reported results to exact
hashes. Captured labels use StreamLabelFromStore=FALSE; the mutant models a
lagging send-time owner store. Status is SIMULATION ONLY (3 seeds, 20,000 traces
each, depth 120); exhaustive combo10 is pending. No model proof is claimed.
The stream regression is an injected fault control; real P5 did not reproduce
a pre-issued publication.
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` |
| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001` |
| none | Granted | `RenewWorkspaceLease` from the current primary (server id, replica id) at the current epoch; a missing/foreign server is refused by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`); no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Granted | Granted | current primary server/replica/epoch required by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing server refused); renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001` |
| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` |
| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` |
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
| Expired | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` |
| Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
| Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
### M3 Replica role and peer state
@@ -110,7 +145,7 @@ The role a blockvolume takes from each assignment, its replica listener's admiss
```mermaid
stateDiagram-v2
[*] --> Unassigned: listener with a floor record, no role yet
Unassigned --> Primary: fact names self, listener fenced at e
Unassigned --> Primary: fact names self (server id + replica, delivered only to its registered host), listener fenced at e
Unassigned --> Supporting: fact names another primary, self in peers
Supporting --> Primary: promotion, fact names self at a higher epoch
Primary --> Supporting: fact names another primary, self in peers
@@ -132,9 +167,10 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S
|---|---|---|---|---|
| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` |
| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` |
| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` |
| Unassigned, Supporting | Primary at e | the primary fact names this process server and replica via assignmentNamesSelf, without comparing endpoint strings (routing data, reported as status/log warning on mismatch); missing/foreign server is refused; refused foreign facts are recorded but fence only an adopted own lineage that IsSuperseded finds strictly older (unassigned and older replay keep waiting); refusePrimaryAssignment rejects a candidate behind a newer foreign line or naming a different server at the same epoch before adapter admission; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told; for a workspace volume the master delivers the fact only to a registered server id streaming from its registered host (`SubscribeAssignments` with `refuseWorkspaceHolderHost`) | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` |
| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` |
| Primary, Supporting | Excluded | another primary excludes this replica, or IsSuperseded finds a foreign-server fact strictly newer than an adopted own lineage; record the foreign line, close ingress and gate the frontend; unassigned and older/equal foreign replay do not fence; endpoints are not identity; refusePrimaryAssignment rejects any candidate changing a recorded server within the same epoch, regardless of endpoint version | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
| Excluded | Excluded (no change) | an older recorded foreign fact cannot replace the newer epoch/endpoint-version fence; a stale replay cannot re-enable the frontend | `core/host/volume/host.go` `recordOtherLine`, `IsSuperseded` | `INV-AUTH-HOLDER-IDENTITY-001` |
| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` |
| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` |
| Supporting | promotion candidate | no active recovery session; member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least N_peers-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001`, `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001` |
@@ -149,7 +185,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S
| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-001` |
| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` |
| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` |
| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` |
| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate session (single-lane by default, dual-lane with `--recovery-mode=dual-lane`) | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` |
`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`).
@@ -259,7 +295,7 @@ stateDiagram-v2
| Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
| Guest-frozen detach | (Not reachable in this release; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` |
| Guest-frozen detach | (Not reachable in this release, except the HTTP400 validation; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` |
| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` |
| Pre-copy host drain | (Not reachable in this release; see the note below.) a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` |
@@ -272,7 +308,7 @@ stateDiagram-v2
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged.
Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach (apart from its HTTP400 validation) and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged.
Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes;
0 explicitly disables); they do not create named snapshots. One five-minute
@@ -410,7 +446,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
303 rows: 217 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 288 new.
308 rows: 237 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 293 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -442,11 +478,11 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB |
| `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 record codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing count, LSN, cursor or LBA spans, nonzero padding, a bad CRC or footer, and truncation, before allocating a payload. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | STUB |
| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB |
| `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE |
| `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing spans and truncation before allocating a payload; the scanner reads a record only after those checks bound its size, and refuses nonzero padding, a bad CRC or a bad footer before using its bytes. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | STUB |
| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | ACTIVE |
| `INV-WAL-V3-ADMISSION-001` | v3 write admission measures WAL pressure from the active v3 writer's physical head minus the both-slot reuse floor, as a fraction of WALSize. | M1 Serving (write admission) | `core/storage/walstore.go` `openInitializedV3`, `WALStore.walUsedFraction`; `core/storage/write_command_budget.go` `WALStore.writePressureSample` | `TestWALStoreV3AdmissionUsesNativeOccupancy` (`core/storage/walstore_admission_v3_test.go`); `TestWALStoreV3WritePressureSampleMatchesOccupancy` (`core/storage/write_command_budget_test.go`); liveness under pressure: `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback), `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) (`core/frontend/durable/provider_chunk_burst_test.go`) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE |
| `INV-WAL-V3-ADMISSION-FAULT-001` | A terminal I/O fault latched while a v3 write waits on WAL pressure or for an admission slot ends that wait with the fault's original typed cause, also when the deadline has expired at the same check. | M1 Serving (write admission) | `core/storage/wal_admission.go` `walAdmission.acquireContext`, `walAdmission.terminalFault`; `core/storage/write_command_budget.go` `WALStore.writeBudgetError` | `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreV3WriteBudgetKeepsTerminalFault` (`core/storage/write_command_budget_test.go`) | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-DEADLINE-001` | One command deadline, the earlier of the caller's deadline and the command's arrival plus `WriteCommandBudget`, bounds every adapter batch of a write and its store waits for the capture and lifecycle locks, on the local clock. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue` | — | ACTIVE |
@@ -458,37 +494,38 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint at cp moves retainedTail only to the end of a complete validated record whose last LSN is at most cp minus the retention window, and, while a BASE is installing, never past BaseCursor. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/wal_io_v3.go` `walWriterV3.reclaimThroughV3` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB |
| `INV-WAL-V3-RECLAIM-INDEX-001` | A physical v3 recovery rebuilds the writer's volatile record-boundary index only from trusted write records of the kept scan; an installing reopen indexes them without moving the writer's cursor. | M1 checkpoint / existing two-slot retirement | `core/storage/wal_io_v3.go` `walWriterV3.restoreScanV3`, `walWriterV3.rememberReclaimScanV3`, `walWriterV3.indexReclaimScanLockedV3`; `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | — | STUB |
| `INV-WAL-V3-RECLAIM-PUBLISH-001` | A mapped v3 checkpoint publishes retainedTail, retainedHead, the map root, CheckpointLSN and W in one slot publication, followed by a metadata-only rollover when the fallback slot still pins a lower tail. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB |
| `INV-WAL-V3-RECLAIM-FAIL-001` | When a v3 checkpoint publication or its rollover fails, no WAL byte is released for reuse and the dirty entries at or below the checkpoint stay unchanged for retry. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.rolloverCheckpointV3Locked`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB |
| `INV-WAL-V3-RECLAIM-FAIL-001` | When a v3 checkpoint publication or its rollover fails, no WAL byte is released for reuse and the dirty entries at or below the checkpoint stay unchanged for retry. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.rolloverCheckpointV3Locked`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`; `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-RECLAIM-EXCL-001` | No v3 writer is admitted between a checkpoint's slot publication and the end of both its rollover and its retirement of the dirty entries at or below the checkpoint. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.retireCheckpointDirtyV3Locked` | `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse` | — | STUB |
| `INV-WAL-V3-RECLAIM-SETTLE-001` | A pending v3 rollover (the fallback slot pinning a lower tail) is settled without a new checkpoint by the idle refresh, by a flusher cycle whose checkpoint does not advance, and by write admission. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.rolloverCheckpointV3Locked`, `WALStore.persistOwnedMapCheckpointV3`; `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.appendWriteV3` | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | — | STUB |
| `INV-WAL-V3-RECLAIM-SETTLE-001` | A pending v3 rollover (the fallback slot pinning a lower tail) is settled without a new checkpoint by the idle refresh, by a flusher cycle whose checkpoint does not advance, and by write admission. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.rolloverCheckpointV3Locked`, `WALStore.persistOwnedMapCheckpointV3`; `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.appendWriteV3` | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | — | ACTIVE |
| `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB |
| `INV-WAL-V3-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB |
| `INV-WAL-V3-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | Once a v3 store has bound a validated map, every descriptor publication carries the bound map tuple or a prepared candidate's, with merged CheckpointLSN ≤ map coverage C ≤ merged W. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `sameMapTupleV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedWithMapV3` | `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB |
| `INV-WAL-V3-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestWALStoreV3ScanLBAsIsAllOrNothing` (`core/storage/walstore_batch_v3_test.go`; default suite, asserts both clauses for a damaged first and middle record); also `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`, not run by CI) | — | ACTIVE |
| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | ACTIVE |
| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | Once a v3 store has bound a validated map, every descriptor publication carries the bound map tuple or a prepared candidate's, with merged CheckpointLSN ≤ map coverage C ≤ merged W. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `sameMapTupleV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedWithMapV3` | `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`; `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges` (`core/storage/descriptor_v3_test.go`) | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | ACTIVE |
| `INV-WAL-V3-MAP-PUBLISH-REPLACE-001` | A prepared v3 map candidate is published only with a higher map generation, coverage not below the bound map's, and the same sidecar and proof domain with its epoch and mutation token unchanged since preparation; a stale candidate writes no slot. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `prepareMapPublicationV3`, `mapPublicationProofV3.validV3` | `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend` | — | STUB |
| `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` | A v3 publication without a prepared map candidate (a W-only publication or a rollover) carries the bound map root unchanged. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3` | `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix` | — | STUB |
| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB |
| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | STUB |
| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB |
| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (dark map preparation only) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | STUB |
| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB |
| `INV-WAL-V3-FLUSH-LIFETIME-001` | A v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_CorruptionAndBounds` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | ACTIVE |
| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB |
| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | ACTIVE |
| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB |
| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (map preparation) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | ACTIVE |
| `INV-WAL-V3-MAP-PRIOR-LIVE-001` | A map prepare reuses pages only of a prior root that is live in the same section that snapshots the live set; otherwise it is refused, not latched, and retried from the current root. | M1 Serving → Serving (checkpoint) and Serving → Serving (map prepare refused) (ORDER: capture of prior, then the live-set snapshot) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3` | `TestChunkMapExtentsV3ReleasedPriorIsRefused`, `TestChunkMapExtentsV3ReleasedPriorIsRefusedInsideThePrepare`, `TestChunkMapExtentsV3InFlightCandidatePinsItsReusedPages` (`core/storage/chunk_map_extents_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor slot write after create's initial slot A goes through the one publisher, which writes the fallback slot with slotGen + 1 while holding `descMu`. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish`, `descriptorPublisherV3.publishLockedCoreV3`; create: `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-LOCKORDER-001` | The v3 publisher holds `WALStore.mu` only to take its snapshot and releases it before any slot I/O; the slot write and its fsync run in the store's fsync leaf. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishWithMapV3`; `core/storage/walstore.go` `WALStore.syncFile` | `TestDescriptorV3LockOrderRecorder` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-MERGE-001` | A v3 publication rebases onto the authoritative descriptor: W and CheckpointLSN are max-merged, and a change of identity, geometry or (outside a reset) nonce, a retainedTail regression, or a map root change without a higher map generation is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `mergeDescriptorV3`, `mergeDescriptorV3Mode` | `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`); `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-LOCKORDER-001` | Every v3 descriptor publication locks in the order `syncMu`, `WALStore.mu`, `descMu`, `fileSyncMu` and fsyncs the slot in that leaf. W publications hold no store lock during slot I/O; recovery, BASE transitions, checkpoint publication and rollovers hold `WALStore.mu` across it to exclude writers. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishWithMapV3`; `core/storage/walstore.go` `WALStore.syncFile` | `TestDescriptorV3LockOrderRecorder` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-MERGE-001` | A v3 publication rebases onto the authoritative descriptor: W and CheckpointLSN are max-merged, and a change of identity, geometry or (outside a reset) nonce, a retainedTail regression, or a map root change without a higher map generation is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `mergeDescriptorV3`, `mergeDescriptorV3Mode` | `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`); `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-PUBLISH-BASE-EDGE-001` | A v3 publication whose BASE state change is not a DESIGN 8.5 edge (none → installing, installing → installing under a new ID, installing → installed under the same ID and BaseLSN, installed → none) is refused; installed → installing is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `baseTransitionAllowedV3` | `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-FAIL-001` | A failed slot write (full or partial) or slot fsync publishes nothing: the authoritative descriptor stays, the store fault is latched, the candidate stays pinned as uncertain, and every later publication, rollover and WAL reuse is refused until reopen. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`, `descriptorPublisherV3.rolloverIfPinned`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned` (`core/storage/descriptor_v3_test.go`); `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` | — | STUB |
| `INV-WAL-V3-PUBLISH-LATCH-LEAF-001` | A descriptor slot write error latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a store Sync queued on `fileSyncMu` cannot acknowledge through the uncertain slot. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/storage/walstore.go` `WALStore.syncFile`, `noteFsyncFailure` | `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-SUCCESS-BOUNDARY-001` | A store fault latched while a v3 publication is in flight makes that publication fail at its success boundary, without advancing the authoritative descriptor. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-SUCCESS-BOUNDARY-001` | A store fault latched while a v3 publication is in flight makes that publication fail at its success boundary, without advancing the authoritative descriptor. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary` (`core/storage/descriptor_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-PUBLISH-COUNTER-001` | A v3 publication whose slotGen, W, CheckpointLSN, retainedTail, retainedHead, map generation, map coverage, BaseLSN or BaseCursor would exceed 2^64-2 is refused with `ErrCounterExhausted` before any write. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `checkCountersV3`; `core/storage/superblock_v3.go` `nextSlotGenV3` | `TestDescriptorV3PublicationCounterExhaustion` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-ROLLOVER-001` | When the fallback slot's retainedTail is below the selected slot's under the same nonce, a metadata-only rollover republishes the current descriptor unchanged into it, so the reuse floor rises to the selected tail. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` | No v3 WAL reuse floor is computed across nonces: while the two descriptor slots carry different nonces there is no floor, and no WAL byte is reused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.reuseFloor`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` | No v3 WAL reuse floor is computed across nonces: while the two descriptor slots carry different nonces there is no floor, and no WAL byte is reused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.reuseFloor`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor` (`core/storage/descriptor_v3_test.go`); `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-W-001` | A v3 Sync acknowledges a write only after an fsync that covers the write's WAL record has completed. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.Sync` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-MODE-C-001` | In mode C (the default) a Sync batch publishes W = the previous batch's acknowledged W, and that publication's one fsync covers both the batch's WAL records and the slot. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-MODE-A-001` | In mode A a Sync batch fsyncs the WAL first and only then publishes the slot with W = H, the highest LSN appended when the batch began. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
@@ -500,34 +537,34 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB |
| `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB |
| `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB |
| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving (dark) | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W; this is checked again at its completion. | M1 Installing (dark) | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (dark) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB |
| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (recovery; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (deferral only with `--durable-impl=walstore-chunk`) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W; this is checked again at its completion. | M1 Installing | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB |
| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED |
| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |
| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |
@@ -540,18 +577,22 @@ Notes:
- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged.
- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes.
- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads.
- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. Production create and open run this bind (`openWALStoreV3File`); capture does not. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The map-requiring actual-store opener (production open) now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The actual chunk capture (production with `--durable-impl=walstore-chunk`) now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the chunk transition drain (no production caller: a BASE install comes only from replication, which `walstore-chunk` refuses) and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. WAL tail reclamation is wired (`INV-WAL-V3-RECLAIM-001` family). Existing lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutabLine truncated
- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests.
- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only.
- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log.
- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired.
- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge).
- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. The precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired.
- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Production reaches it through both callers below: the legacy single-lane caller by default, the dual-lane `Receiver` with `--recovery-mode=dual-lane`. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge).
- `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation.
- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11.
- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11.
- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`).
- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. Since activation (row 12b) production create and open (`CreateWALStoreWithOptions`, `OpenWALStoreWithOptions`) reach it. Without the row-7 map candidate (unmapped test fixtures only) the v3 checkpoint and tail do not advance. `INV-WAL-V3-W-001` stays a STUB for the reason in the format v3 status note below; `INV-WAL-V3-FENCE-001` is still a STUB although the path is active, its promotion pending a per-row check of its tests. The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11.
- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). The v3 store is wired in (rows 4 and 5) and activated (row 12b); the row stays a STUB for the reason in the format v3 status note below. The v2 checkpoint path (`persistCheckpointReleasing`) is retired. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11.
- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). Since the activation commit (plan row 12b) production walstore open and create reach the v3 codec; the row stays a STUB for the reason in the format v3 status note below. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`).
- Format v3 status: the rows from `INV-WAL-V3-DESCRIPTOR-001` to `INV-WAL-V3-W-001` that were `STUB` (production reaches each by default) were checked clause by clause. A row is `ACTIVE` when a test in the default suite (no build tag) asserts every clause of its statement. The others stay `STUB`; the clause without an asserting test is in brackets.
- No test asserts the clause: `INV-WAL-V3-DESCRIPTOR-001` (geometry under checked arithmetic), `INV-WAL-V3-DESCRIPTOR-BASE-001` (mapCoveredCheckpoint ≤ W), `INV-WAL-V3-RECORD-REFUSE-001` (before allocating a payload), `INV-WAL-V3-OWNER-001` (read-only open takes the same exclusive lock; no byte changes under contention), `INV-WAL-V3-RECLAIM-001` (never past BaseCursor while installing), `INV-WAL-V3-RECLAIM-INDEX-001` (only trusted records of the kept scan), `INV-WAL-V3-RECLAIM-PUBLISH-001` (the five fields in one slot publication), `INV-WAL-V3-CATCHUP-REVALIDATE-001` (unchanged nonce and install epoch), `INV-WAL-V3-FLUSH-LIFETIME-001` (a cycle spanning a reset), `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` (a rollover keeps the root), `INV-WAL-V3-MAP-VALIDATE-001` (file bounds; no entry returned on refusal), `INV-WAL-V3-MAP-PERSIST-FAIL-001` (a Stat error latches nothing), `INV-WAL-V3-MAP-TRUNCATE-001` (the four-times threshold; truncation to the end of the highest live page), `INV-WAL-V3-PUBLISH-001` (every slot write goes through the publisher), `INV-WAL-V3-PUBLISH-LOCKORDER-001` (the callers that hold `WALStore.mu` across slot I/O), `INV-WAL-V3-PUBLISH-BASE-EDGE-001` (installing → installed with another BaseLSN), `INV-WAL-V3-PUBLISH-FAIL-001` (after a failed slot fsync: latch, pin, rollover and reuse refusal), `INV-WAL-V3-PUBLISH-LATCH-LEAF-001` (a real store Sync; the test uses a stand-in leaf), `INV-WAL-V3-PUBLISH-COUNTER-001` (slotGen, retainedTail, map coverage, BaseLSN, BaseCursor), `INV-WAL-V3-PUBLISH-ROLLOVER-001` (written into the fallback slot, otherwise unchanged).
- The tests only exercise the path: `INV-WAL-V3-SCAN-BINDING-001` (nonce and cursor checked before Length or count), `INV-WAL-V3-SCAN-STOP-001` (no search inside a payload), `INV-WAL-V3-RECLAIM-EXCL-001` (the test writes after the window), `INV-WAL-V3-W-001` (mode C), `INV-WAL-V3-MAP-PUBLISH-REPLACE-001` (coverage not below the bound map's; same sidecar).
- Asserted only by tests under build tag `swblock_format_v3_test`: `INV-WAL-V3-CATCHUP-001` (an empty request at the head), `INV-WAL-V3-CATCHUP-BASE-001`.
- `INV-WAL-V3-ACTIVATION-001` family: writable and read-only open validate the owned-map dependencies of the selected slot and of every valid fallback slot before the store or reader is returned, and refuse a valid legacy superblock with `ErrUnsupportedLegacyFormat` without changing a byte: see M1 — → Opened (tests `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies` with its fallback-page case, `TestNativeReplacementLegacyBytesRefusedWithoutMutation`). A zero chunk geometry option becomes 1024 blocks per chunk, so every public create is mapped; create persists an all-UNKNOWN initial map before its first slot.
- `INV-WAL-V3-DESCRIPTOR-CONFLICT-001`: the old statement said the two slots must not disagree on identity; of the identity fields, open compares the UUID, together with the geometry. The next publication's slotGen comes from `nextSlotGenV3` (`INV-WAL-V3-PUBLISH-COUNTER-001`). `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` is a store-level control of the selection: a v3 `Close` writes no slot, and reopen selects the newest one.
- `INV-WAL-V3-RECORD-001`: codec success alone is not nonce, cursor or lap replay admission; that belongs to the scanner (`INV-WAL-V3-SCAN-BINDING-001`).
@@ -561,6 +602,7 @@ Notes:
- `INV-WAL-V3-BINDING-001` family: a writer whose pwrite failed refuses every later append, and the store latches the fault: see M1 Serving → FaultLatched and FaultLatched → FaultLatched (test `TestWALIOV3_FloorAndPwriteFailureRefuse`). A scan result (`walScanResultV3`) is a typed read-only result, never an acknowledgement or serving permission; recovery decides from it (`INV-WAL-V3-W-RECOVERY-001`). The scan start for a BASE descriptor is in `INV-WAL-V3-BASE-SUPERSEDED-001`.
- `INV-WAL-V3-MAP-PUBLISH-001` family: binding validates the map root and pages of the selected slot and of every valid fallback slot before serving: see M1 — → Opened (tests `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`). Recover invalidates the map proof epoch at its start and at its end, on success and on failure: see M1 Recovering → Serving (tests `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`). A candidate whose slot publication outcome is unknown stays pinned until reopen (`INV-WAL-V3-MAP-EXTENT-REUSE-001`, `INV-WAL-V3-PUBLISH-FAIL-001`). Controls of the capture, seed and provider callers described in the next note, not of the publication rule itself: `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_DefaultSelectorCreatesV3`, `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`; `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` is also a control of `INV-WAL-V3-ACTIVATION-PROVIDER-001`.
- `INV-WAL-V3-MAP-BYTES-001` family: root and pages are addressed by offset and SHA-256; with 4096-byte alignment, distinct page offsets that do not overlap the root rule out a partial overlap. Truncation keeps a root the fallback slot names readable.
- `INV-WAL-V3-MAP-PRIOR-LIVE-001`: every root preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) goes through the guard, but the harmful pair without it is narrower: a stale flusher prepare, a chunk-layer publication in its gap that cleared no UNKNOWN entry (so the proof does not move), then any publication that releases the flusher's prior. BASE complete is harmless on both sides (as the intervening publisher it invalidates the proof under the same lock; as the stale preparer it is refused by coverage). No other allocation is needed for the damage: the stale prepare's own new page or root lands on the freed extent (lowest free extent first). The outage it caused was not one open: later roots reuse the bad page reference for the unchanged page, so the volume stays unopenable until two root publications have rewritten that page, and a failing fallback root refuses open too. A store damaged before the fix is not cured by a restart; there is no offline rebuild of the owned map from the WAL and the extent, so recovery is a replica rebuild or a HEAD restore onto a fresh store (an offline map rebuild is the post-RC tool this failure would need). Modeled: bounded simulation reaches the bad state in 18 steps without the guard and never with it; each of the three facts (the check in the snapshot's liveMu section, prepares under the map lock, the candidate pinning its reused references) fails as a mutant; exhaustive model checking is pending.
- `INV-WAL-V3-PUBLISH-001` family: create writes the initial descriptor into slot A directly (`createWALStoreV3Configured`) before the store opens; every later slot write is the publisher's. The lock graph is metadata callbacks, then `WALStore.mu` (snapshot only), then `descMu`, then `fileSyncMu` (the leaf, inside `syncFile`). An fsync error is latched by the leaf itself (`noteFsyncFailure`); the publisher latches a slot write error because the leaf does not. The success-boundary refusal is the #172 rule. `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` drives the failure rule through an append's rollover.
- `INV-WAL-V3-W-001` family: because mode C's slot carries the previous batch's W, the acknowledged writes above the slot W are at most those of the newest acknowledged batch, which is unprotected only against media corruption before the next Sync or the idle refresh (`INV-WAL-V3-W-REFRESH-001`; test `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`). For an installing descriptor, recovery reports a short prefix (R < W*) or a scan error as `ErrBaseIncomplete`, not `wal_corrupt` (`installingErrorV3`; test `TestWALStoreV3InstallingScanErrorIsTypedNotReady` covers the scan error). A Sync acknowledges nothing when a store fault has latched by its final check (`INV-WAL-FSYNC-STICKY-001`).
- `INV-WAL-V3-FENCE-001`: with mixed slot nonces (a reset stopped between its two publications) the fence interval is empty, because old-nonce bytes fail the scanner's nonce binding (`fenceRangesV3`). A fence write error latches the store inside the leaf.
@@ -574,6 +616,7 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: trusts the network peer address (no NAT or proxy between volume and master in OSS); not authentication | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | 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` | `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`) | `ControlPlane` `UniqueEpoch` | 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, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_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 |
@@ -582,7 +625,7 @@ Notes:
| `INV-LEASE-VIEW-OWNED-001` | The granted deadline and the extender flag exist only in the lease view; refreshing the view from its derive inputs never changes either of them. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `setLeaseDeadlineLocked`, `extendWorkspaceLease` | — | — | STUB |
| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch, the `Lease.ExpiresAtNS` persisted in the authority store is at least the published horizon, and the published horizon is at least every grant issued since the last reload. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`, `newWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked`, `issueWorkspaceMove` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE |
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE |
| `INV-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-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/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_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 |
@@ -707,7 +750,7 @@ Notes:
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
@@ -735,11 +778,14 @@ Notes:
| `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on per-process fallback limits that claim no host-wide bound and are reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE |
| `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
| `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE |
| `INV-HOST-URGENT-PENDING-001` | While an urgent cut holds its slot, or a caller holds HoldUrgentPending, every Normal admission on the host is refused with ErrUrgentPending (a held-slot wait); urgent admissions still run. | M7 host cut admission (Normal before a slot) | `core/hostlimit/limiter.go` `pool`, `Admit`; `core/hostlimit/pending.go` `HoldUrgentPending` | `TestNormalWaitsWhileUrgentPendingIsHeld`, `TestUrgentLeaseHoldsThePendingSignal` (`core/hostlimit/pending_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
| `INV-HOST-LAUNCH-CHECK-001` | blockvolume refuses to start with a --host-limit-dir that is missing or not a directory, under a temporary directory, on a network file system, or already in use with different host-limit flags. | M7 host cut admission (process start) | `core/hostlimit/launch.go` `CheckLaunch`; `core/hostlimit/remotefs_linux.go`; `cmd/blockvolume/main.go` | `TestCheckLaunch` (`core/hostlimit/pending_test.go`) | — | ACTIVE |
| `INV-HOST-SLOT-BUSY-CODE-001` | The chunk control API refuses a cut, snapshot or detach that host admission refused because every slot is held (or urgent work is pending) with 503 host_slot_busy, retryable; every other capture refusal keeps capture_refused. | M7 free → admitted (refused, wait) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestHostSlotHeldHasItsOwnCode` (`core/host/volume/chunk_host_slot_code_test.go`) | — | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, an intent naming every key of that kind the round preallocated is durable in the filer: one for all candidate chunks, however many upload waves the round uses, and one for all new segments. | M5 Intent → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_FailedPutIntentUploadsNothing` (`core/storage/chunk_layer_intent_test.go`); `TestCutPayloadIntentCountIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE |
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE |
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff or minimum spacing; it retries after a random delay under 200 ms that shrinks with lateness, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestNewSlotDelay_ShrinksWithLateness`, `TestCutPolicy_OneSlotWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
@@ -749,7 +795,7 @@ A guest read has a cooperative arrival budget; internal contextless readers keep
Notes:
- `INV-CUT-TIMER-RESTART-001`, `INV-CUT-TIMER-SKIP-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` (except its estimate and quiesce-slack report, which every successful cut returns) and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`.
- `INV-WS-FREEZE-REFUSAL-001`: a generic `bad_request` is not proof of a clean refusal. The validation also refuses a non-frozen request that carries a freeze origin (`handleChunkDetach`). `INV-WS-FREEZE-REFUSAL-INPUTS-001` compares the caller's Unix-nanosecond origin with blockvolume's `time.Now`, with no skew bound.
- `INV-HOST-CUT-BUDGET-001`: an unavailable pool skips normal, fill and idle work with an alarm: see M7 (test `TestUnusablePoolClassPolicy`). Coordinated reservations do not account retained crash spill, fallback leases or process RSS (`HostBudget` excludes fallback). Guest I/O and WAL reclamation never take a slot (M7). Hold expiry (`MaxHold`, `INV-HOST-CUT-BUDGET-SETTLE-001`) and upload pacing (`INV-HOST-CUT-BUDGET-PACING-001`) run on the process's local clock.
- Enforced by reading (no test asserts it): the refusal of a non-frozen request that carries a freeze origin; and an explicit zero freeze origin, which the test sends only as a missing origin (both decode to zero).
@@ -924,16 +970,16 @@ One row per wait in the data and control paths. Guest-visible rows on one path m
|---|---|---|---|---|---|---|
| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) |
Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step.
Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step.
### Dark v3 offline reader (row12a)
### v3 offline reader (row12a)
- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b.
- `INV-WAL-V3-READONLY-001` (ACTIVE; the public selector `OpenReadOnly` opens this reader): the reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. Its production caller is `cmd/m01verify`.
- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition.
### Dark v3 chunk/BASE integration (row12a)
### v3 chunk/BASE integration (row12a)
- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu.
- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for mapped v3; no production caller of begin/complete with a layer attached: a layer attaches only with `--durable-impl=walstore-chunk`, which refuses replica roles): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu.
- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission.
- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam.
@@ -956,3 +1002,35 @@ Frozen estimate reporting: a tail above the existing 60 s estimator ceiling repo
| Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap |
|---|---|---|---|---|---|
| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; the free space is read once per cut and that cap bounds both staging and the copy window; off Linux, the configured cap. Shown per cut in the layer stats (`COWSpillCap`, `COWSpillCapReason`: `no_room_to_cut` when the free space is within the reserve, `free_space_unreadable` when the read fails) | the saver: `core/storage/chunk_cut_cow.go` `readCutSpill`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (retryable), counted as `cow_capacity`, or as `no_room_to_cut` / `free_space_unreadable` when the free space made the cap 0; the guest write completes and nothing partial is published |
## Part T. Terms bound to code
Some facts are read by many parts of the code: who the holder is, whether the lease is valid, whether the volume may serve. Each such fact is a term. For each term this part lists the fields that carry it, the one function that decides it on each side, and the role that owns it. **A second derivation of a term is a defect.** Code that needs a term calls its deciding function, or a function that only wraps that call. It never compares the term's fields again itself. Known second derivations are listed in each row together with the pull request that removes them, or "open".
A reviewer applies the rule to every pull request:
1. If the diff reads or compares a field listed in a row anywhere other than that row's deciding function, it must call the deciding function instead. Otherwise it changes the row in the same pull request, and the description says why.
2. A pull request that removes a listed second derivation also deletes it from the row. A pull request that adds a new one is refused, unless it adds the new derivation to the row as open, with a reason.
3. Renaming, moving or splitting a deciding function updates its row in the same pull request.
A row that names a function existing only on an open pull request says so ("on #N"). The qualifier is dropped when that pull request merges. Code references name a file and a function, as in the rest of this document. A checker will later verify that every deciding function named here exists on `main`.
10 rows for 5 terms. They name 13 deciding functions: 10 on `main` and 3 only on open pull requests (2 on #411, 1 on #409). One row (`TERM-STOP-STALE-ROOT-001`) has no named function yet.
| Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role |
|---|---|---|---|---|---|
| `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. A local-root nonce joins the pair later (pending). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `<server id>/<replica id>` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines. The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) |
| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, at most 30 s. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `Publisher.AckWorkspaceRevocation` (`core/authority/workspace.go`) checks expiry again inline, without the skew term: open. `leaseFact` (`core/host/master/workspace_service.go`) recomputes the host validity with `time.Now` instead of the publisher's clock, with a 20 s skew fallback, while `RenewWorkspaceLease` refuses a grant on the same term inline: open (one helper for both). `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The 30 s TTL is written three times: the publisher's default TTL (`core/authority/authority.go`), the cap in `leaseFact`, and the reply bound in `Refresh`: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. | authority (grant); volume host (guard) |
| `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host |
| `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host |
| `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host |
| `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer |
| `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published is refused before the claim and never served. The process stays up without serving. | HEAD `Holder`; `ProviderConfig.ChunkHolder` | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | It compares the holder only, so a rolled-back root of the same holder passes: pending the local-root nonce. | volume host |
| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) reimplements the proof check for the revocation ACK: open. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) |
| `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host |
| `TERM-ONE-PROCESS-001` One live process per holder | At most one blockvolume process serves a holder at a time. Today a second process is refused only when it opens the same store file. A local-root nonce in the holder identity is to close the other cases (pending). | The store file `<--durable-root>/<volume id>.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); its exclusive OS file lock; the HEAD `Holder` | Volume: `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the lock's limit: it covers one file. A second process is not refused when it uses another `--durable-root`, runs on another host with the same server id, or runs on a copied root. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open, pending the local-root nonce. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine |
Notes:
- `TERM-SERVING-001` and `TERM-STOP-*`: in this release a workspace primary that can no longer serve should stop, not linger. Today `TERM-STOP-HEAD-FENCED-001` and `TERM-STOP-STALE-ROOT-001` leave the process up and its lease renewing. A forced move then waits for that lease. The open entries in those rows track this.
- `TERM-HOLDER-001`: supporting replicas (RF greater than 1) are not holders, and their replica-keyed checks (`AdapterProjectionView.supportingReplicaReady`) are outside this row.
+2
View File
@@ -4,6 +4,7 @@ Seaweed Block release notes use narrow product claims. Each alpha version names
what a user or reviewer can actually run, what QA evidence backs it, and what
is still outside the supported boundary.
- [Holder identity and pre-release upgrades](holder-identity.md)
- [v0.1 Alpha — Kubernetes Block Foundation](v0.1-alpha.md)
- [v0.2 Alpha — Day-1 Activation And First Volume](v0.2-alpha.md)
- [v0.3 Alpha — Helm Install And Observable First Volume](v0.3-alpha.md)
@@ -93,3 +94,4 @@ The WAL multi-block record opt-in is documented separately because it is a
backend/WAL-format optimization boundary, not a RoCE, NVMe/RDMA, or performance
claim. It remains default-off and source-gated; a future published-image smoke
is still required before any public release-image claim.
@@ -0,0 +1,21 @@
# Holder identity and pre-release upgrades
Assignments and workspace lease requests carry the holder's server id as well
as its replica id. Replica ids and loopback addresses may be reused on another
host, so they do not identify the holder by themselves. A volume refuses an
assignment with a missing or different server id, or different carried data or
control endpoints. The master refuses workspace lease requests and revocation ACKs whose server
id is missing or does not match the assigned primary holder. A refused ACK is
not recorded and cannot license a clean move.
Upgrade the master first, then the volumes, using binaries from the same
release. A new volume connected to an older pre-release master stays not
serving until the master is upgraded. An old volume does not gain the new
assignment guard merely because its master has been upgraded. The new master also
refuses lease calls from old volumes that omit the server id, so plan for a
service interruption while replacing pre-release components. There is no
compatibility flag or endpoint-based fallback.
This affects pre-release version mixing; it does not change the local volume
or remote HEAD format.
@@ -0,0 +1,48 @@
# Workspace owner-label model: round 4 pins
This is a citation of claude06's external model and its reported simulations,
not an exhaustive public-spec result. Source bundle:
`V:/share/rdma/claude06-sw-tla-regrant-r0-20261122/`.
`WorkspaceRegrant.tla` round 4 maps `StreamLabelFromStore = FALSE` to
`Publisher.captureAssignmentOwner` -> immutable `AssignmentInfo` ->
`services.assignmentFact` -> `Host.workspaceLineOwner`. The lease view derives
the same owner metadata (`INV-LEASE-VIEW-001`). A moved unknown owner is empty;
only a move-less line falls back to placement (`INV-AUTH-HOLDER-IDENTITY-001`).
The TRUE switch injects a send-time owner store that can lag. This is a model
fault schedule, not evidence of a reachable pre-issued publication in current
Go code; the real P5 trace showed the old host refusing both foreign facts.
## Results and limits
Status: **SIMULATION ONLY**. `summary-r4.tsv` reports 3 seeds x 20,000 traces,
depth 120, with these exact configurations:
| Configuration | Reported result |
|---|---|
| `WR_id4_fix_label.cfg` | No violation in the simulations |
| `WR_id4_fix_label_ownline.cfg` | No violation in the simulations |
| `WR_id4_RED_label.cfg` | `NoForeignAdoption` violated at traces 14, 17, 15 |
| `WR_id4_RED_label_safety.cfg` | No safety-invariant violation in the simulations; lease layer stops the adopter |
| `WR_id4_fix_label_volguard.cfg` | `NoForeignAdoption` still violated at traces 14, 17, 15; a fresh process has no recorded foreign line |
The result interpretation is in `REGRANT-REPORT.md`, "Round 4: adoption fence".
A simulation finding is a counterexample; no sampled violation does not prove
an invariant. Exhaustive round 4 is **PENDING** in claude06's next Azure slot,
bundle `combo10`, results expected under
`V:/share/rdma/claude06-tlc-azure-results-20261120/tlc-combo10-*`.
Date depends on the open budget decision. No exhaustive state count or GO claim
is made here. This pending model is not added to the Exhausted bounds table.
## Exact source pins
| Artifact (relative to source bundle) | SHA-256 |
|---|---|
| `WorkspaceRegrant.tla` | `d92922331afa2bb127d4f29b9d6fc266354c30b8d11a9a0bd3931e67d2c27d1c` |
| `cfg/WR_id4_fix_label.cfg` | `d716ed5a9d4fce039e2dda084901c789f85f5a44e03d2db28d30a17312ad199f` |
| `cfg/WR_id4_fix_label_ownline.cfg` | `49188ae6776114c9c4358bac0e0dbf8187622feba25a69c1aaf97ed0da8bcdc1` |
| `cfg/WR_id4_RED_label.cfg` | `d22cf52f84bc6b2eed4f0696e4f84285daba2fe5ad0111bbae3358da7a3d1d50` |
| `cfg/WR_id4_RED_label_safety.cfg` | `ca1b0b66fdeb4fef31d43a5efb4e3bb5ef501270f1a6441c8250fb084d4f0e69` |
| `cfg/WR_id4_fix_label_volguard.cfg` | `86fad07c3a9e321ea5dd52a1e4b104c61bdc34a3ce08b4bc123d9b2d97e47f65` |
| `summary-r4.tsv` | `4ca8155ff7c3922d5ff6b0880c41ef59ef13169cc1af9cc630f7fd06256cdbd3` |
| `REGRANT-REPORT.md` | `eab94a6d2e5d81ad9318cb56a90b77958b1a73719258c9500cf71f9c95fc286a` |
+93 -2
View File
@@ -13,6 +13,13 @@ For a first, read-only try without services, see
[first volume (read-only check)](#first-volume-read-only-check). For a write
test, see [write test (scratch host only)](#write-test-scratch-host-only).
## Upgrade order
Upgrade `blockmaster` first, then `blockvolume`. Assignments and workspace
lease requests require the assigned server id. A new volume against an older
pre-release master stays not serving until the master is upgraded; an older
volume must also be upgraded to gain the assignment guard. Do not use endpoint
matching as a compatibility fallback. See [holder identity and upgrades](releases/holder-identity.md).
## Get the matching files
The unit and settings files must come from the same commit as your
@@ -65,20 +72,99 @@ sudo install -m 0640 -g sw-block deploy/config/*.env deploy/config/topology.yaml
sudo install -m 0644 deploy/systemd/*.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now sw-blockmaster sw-blockvolume
journalctl -u sw-blockvolume -f # wait for "nvme-listening"
journalctl -u sw-blockvolume -f # wait for "adopted as PRIMARY" (see the required setup below)
```
The binaries take command-line flags. The `SWB_*` variables are read only by
the example units, which turn them into flags. blockvolume itself reads only
`SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`.
## Required setup: make the volume known to blockmaster
blockmaster gives a blockvolume an assignment only for a volume and replica
slot it already knows. It does not learn volumes from heartbeats. Without an
assignment, blockvolume starts, opens its storage and its listeners, and
serves no I/O.
Outside Kubernetes, a volume becomes known through the accepted-topology file.
Do these steps before you start blockvolume:
1. **Write the topology file.** One entry per volume, one slot per replica;
`volume_id`, `replica_id` and `server_id` are required. This is
[`deploy/config/topology.yaml`](../deploy/config/topology.yaml):
```yaml
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: s1
```
2. **Start blockmaster with the file and the matching slot count.**
`--expected-slots-per-volume` must equal the number of slots of each
volume: `1` here (the default is `3`).
```bash
blockmaster --authority-store /var/lib/sw-block-master/authority --listen 127.0.0.1:9180 \
--topology /etc/sw-block/topology.yaml --expected-slots-per-volume 1
```
In `blockmaster.env` these are `SWB_MASTER_TOPOLOGY` and
`SWB_MASTER_EXPECTED_SLOTS`. blockmaster reads the file only at start:
after you change it, run `sudo systemctl restart sw-blockmaster`.
3. **Start blockvolume with the identity of one slot.** `--volume-id`,
`--replica-id` and `--server-id` (`SWB_VOLUME_ID`, `SWB_REPLICA_ID`,
`SWB_SERVER_ID`) must equal one slot of the file: `v1`, `r1`, `s1` here.
**Check before starting blockvolume.** Without a usable topology, blockmaster
logs this line at start; if `journalctl -u sw-blockmaster` shows it, redo
steps 1 and 2:
```
blockmaster: WARNING: --topology not supplied or empty; controller will not mint assignments until topology is provided
```
A file that cannot be read or parsed stops blockmaster with
`blockmaster: topology: ...`.
**Check after.** blockvolume logs `blockvolume: volume v1 adopted as PRIMARY
at r1@<epoch>`, and its status shows a positive `Epoch`, `"Healthy":true` and
`"AuthorityRole":"primary"`:
```bash
journalctl -u sw-blockvolume | grep 'adopted as PRIMARY'
curl -s 'http://127.0.0.1:9203/status?volume=v1'; echo
```
`nvme-listening` alone does not prove this: blockvolume starts its NVMe/TCP
listener before it has an assignment. Without one, the status shows
`"Epoch":0`, `"Healthy":false` and `"AuthorityRole":"unknown"`.
| What you see | Missing step |
|---|---|
| blockvolume logs `blockvolume: subscribe stream: rpc error: code = Unknown desc = subscribe: volume "v1" not in accepted topology`, again every few seconds | blockmaster has no topology, or `v1` is not in it (steps 1, 2) |
| `walstore-chunk` only: `durable: chunk layer for volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0`, and 30 s later `durable: chunk authority wait for volume=v1 ended after ...: assignment unavailable, not serving (projection lacks healthy=false epoch=0)` | The same. This wait runs once per start: after the fix, restart blockvolume too |
| No error in either log, and `"Epoch":0` stays | `--expected-slots-per-volume` differs from the slot count (step 2), or `--server-id` or `--replica-id` differ from the slot (step 3) |
| blockmaster logs `authority: rejected ask ...: workspace publication: no lifecycle VolumeRecord for v1; register it (CreateVolume) before publishing` | blockmaster runs with `--lifecycle-store`: a topology slot is then not enough, the volume also needs a volume record (below) |
**Workspace lease volumes (`--workspace-lease`).** Besides the steps above,
blockmaster needs `--workspace-rpc`, `--workspace-head-base-url` and
`--lifecycle-store`, and the volume needs a single-replica volume record in
that store. This release has no `sw-block` command that creates that record. Check with `sw-block ops workspace show --master 127.0.0.1:9180
--volume v1`; it names the first missing piece: `workspace RPC disabled`,
`lifecycle store unavailable`, or `workspace move requires an existing RF1
volume`. A move target must also be a registered node, or the move is refused
with `move target node "s2" is not registered`.
## blockmaster settings
| Variable | Flag | Default | Meaning |
|---|---|---|---|
| `SWB_MASTER_AUTHORITY_STORE` | `--authority-store` | required | Durable authority store: assignments, epochs, leases |
| `SWB_MASTER_LISTEN` | `--listen` | `127.0.0.1:0` | gRPC address; unauthenticated, keep it on loopback or a trusted network |
| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted) | Accepted-topology YAML: volumes and replica slots |
| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted: no volume serves) | Accepted-topology YAML: volumes and replica slots; required outside Kubernetes, read only at start |
| `SWB_MASTER_EXPECTED_SLOTS` | `--expected-slots-per-volume` | `3` | Replica slots per volume; `1` for a single replica |
| `SWB_MASTER_FRESHNESS_WINDOW` | `--freshness-window` | `30s` | How long a heartbeat stays fresh |
| `SWB_MASTER_PENDING_GRACE` | `--pending-grace` | `1s` | Startup grace before a missing observation is unsupported |
@@ -154,6 +240,10 @@ group while volumes run.
- **On an NVMe root,** and in that disk's other attaches: the fsync took 50-75 microseconds and the publish 2-3 milliseconds.
- **Cause:** not yet established.
- **Check the device:** `lsblk -d -o NAME,ROTA,TRAN,MODEL`, and the line blockvolume logs at start, `storage: WAL/extent sync=... file=... reason=...`, whose reason names the root's device.
- **NVMe/TCP needs native NVMe multipath on the host (`nvme_core multipath=Y`, the Ubuntu default).**
The device lookup below, and the CSI node plugin's, find the namespace as an `nvmeXnY` entry under
`/sys/class/nvme-subsystem/nvme-subsysN/`; with multipath off that directory holds no namespace entry and
neither finds the device. Check: `cat /sys/module/nvme_core/parameters/multipath` must print `Y`.
- ublk needs root. Use `sw-blockvolume-ublk.service` instead of editing the
unprivileged unit, and load `ublk_drv` at boot
(`echo ublk_drv | sudo tee /etc/modules-load.d/ublk.conf`).
@@ -473,3 +563,4 @@ A restore makes a new, independent volume from a snapshot. The source volume and
- Follow it with `sw-block ops chunk restore --volume v2 --status-addr STATUS_OF_V2 --status`.
- Until v2 is independent, a snapshot of v2 is refused (`restore_incomplete`).
- While v2 still fetches chunks, its scheduled snapshots are skipped and counted as `restoring`. After that, until it is independent, they are refused like any snapshot and show as failed attempts with that code.
+1 -1
View File
@@ -35,7 +35,7 @@ The volume's authority and health projection. Go type `volume.StatusProjection`.
| `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) |
| `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. |
| `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. |
| `Warnings[]` | string | Warnings are the durable store's typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) |
| `Warnings[]` | string | Warnings include routing disagreements and typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) |
### `GET /status/peers`