fix: registry read from a committed snapshot; CSI publishes only a primary-owned target; deletion keeps the stream check

codex01 review of #416 e56f1de1 (INV-AUTH-HOLDER-IDENTITY-001, INV-WS-RENEW-NONBLOCKING-001):
- P1-1: the holder host check reads NodeInventoryStore.GetNodeSnapshot (published after each
  committed write), never the store mutex RegisterNode holds across file I/O.
  Held-registration-write control in core/lifecycle.
- P1-2: a primary slot with no frontend lists nothing; status frontends carry their replica
  (FrontendTarget.replica_id = 8); CSI publishes a target only when the primary has a usable
  frontend, another replica's frontend joining only as an extra path to the same target.
  Real CSI lookup negatives (no primary frontend; rejected loopback primary).
- P2: a deletion-reserved workspace volume keeps the assignment stream host check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-22 04:44:21 -08:00
1 parent fc6365232b
commit abc57ceb61
10 files changed
+843 -552

No files matched your search

+53
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(),
@@ -247,6 +254,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, 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(), true
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,45 @@
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)
}
// 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)
}
}
@@ -25,7 +25,7 @@ func (h *Host) registryHosts(serverID string) (hosts map[string]bool, named stri
if h.lifecycle == nil || h.lifecycle.Nodes == nil || serverID == "" {
return nil, "", false
}
reg, ok := h.lifecycle.Nodes.GetNode(serverID)
reg, ok := h.lifecycle.Nodes.GetNodeSnapshot(serverID) // committed snapshot: never the store mutex (INV-WS-RENEW-NONBLOCKING-001)
if !ok {
return nil, "", false
}
@@ -321,3 +321,79 @@ func TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing(t *testing.T) {
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)
}
}
+4 -3
View File
@@ -393,7 +393,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
}
// 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.workspaceVolumeForRenewal(req.VolumeId) == nil {
if s.isWorkspaceVolume(req.VolumeId) {
if err := s.host.refuseWorkspaceHolderHost(ctx, "assignment stream", req.GetServerId()); err != nil {
return status.Error(codes.FailedPrecondition, err.Error())
}
@@ -587,8 +587,8 @@ func statusFrontendsFor(obs *authority.ObservationHost, volumeID string, replica
slotOf = func(replicaID string) (authority.SlotFact, bool) { return obs.Store().SlotFact(volumeID, replicaID) }
}
if primary != "" {
if _, ok := slotOf(primary); !ok {
return nil
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))
@@ -602,6 +602,7 @@ func statusFrontendsFor(obs *authority.ObservationHost, volumeID string, replica
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
@@ -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
+20 -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,23 @@ 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
}
// RegisterNode records the latest observed inventory for a server.
// Repeating registration replaces observation fields, but still does not
// publish authority or readiness.
@@ -104,6 +119,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 +135,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,71 @@
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) }()
select {
case <-blocked:
t.Fatal("control: GetNode did not wait for the held registration write")
case <-time.After(200 * time.Millisecond):
}
release()
<-blocked
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")
}
}
File diff suppressed because it is too large. Load diff
@@ -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 {