From 1e4106e4b1f9866000afcc718e05b5e1031d3292 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 20:30:54 -0700 Subject: [PATCH 01/10] G9D: add lifecycle registration fact stores --- .../core/lifecycle/node_inventory.go | 280 ++++++++++++++++++ .../core/lifecycle/node_inventory_test.go | 176 +++++++++++ seaweed-block/core/lifecycle/store.go | 264 +++++++++++++++++ seaweed-block/core/lifecycle/store_test.go | 155 ++++++++++ 4 files changed, 875 insertions(+) create mode 100644 seaweed-block/core/lifecycle/node_inventory.go create mode 100644 seaweed-block/core/lifecycle/node_inventory_test.go create mode 100644 seaweed-block/core/lifecycle/store.go create mode 100644 seaweed-block/core/lifecycle/store_test.go diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go new file mode 100644 index 0000000000..d290c97ec9 --- /dev/null +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -0,0 +1,280 @@ +package lifecycle + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "sync" + "time" +) + +var ( + ErrInvalidNodeRegistration = errors.New("lifecycle: invalid node registration") + ErrNodeNotFound = errors.New("lifecycle: node not found") +) + +// StoragePool reports allocatable local capacity. It is placement input, +// not a create decision. +type StoragePool struct { + PoolID string `json:"pool_id"` + TotalBytes uint64 `json:"total_bytes"` + FreeBytes uint64 `json:"free_bytes"` + BlockSize uint64 `json:"block_size"` + Labels map[string]string `json:"labels,omitempty"` +} + +// ReplicaInventory reports durable local replica identity discovered on a +// node. It is controller evidence only; it does not imply replica_ready. +type ReplicaInventory struct { + VolumeID string `json:"volume_id"` + ReplicaID string `json:"replica_id"` + StoreUUID string `json:"store_uuid"` + SizeBytes uint64 `json:"size_bytes"` + DurableLSN uint64 `json:"durable_lsn"` + State string `json:"state"` +} + +// NodeRegistration is the durable node/inventory fact produced by node +// registration or heartbeat ingestion. It deliberately has no authority +// fields. +type NodeRegistration struct { + ServerID string `json:"server_id"` + Addr string `json:"addr"` + Labels map[string]string `json:"labels,omitempty"` + Pools []StoragePool `json:"pools,omitempty"` + Replicas []ReplicaInventory `json:"replicas,omitempty"` + SeenAt time.Time `json:"seen_at"` +} + +// NodeInventoryStore persists one JSON registration record per server. +type NodeInventoryStore struct { + mu sync.Mutex + dir string + records map[string]NodeRegistration +} + +// OpenNodeInventoryStore opens or creates a node inventory store. +func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { + if dir == "" { + return nil, fmt.Errorf("%w: empty dir", ErrInvalidNodeRegistration) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("lifecycle: mkdir node inventory %q: %w", dir, err) + } + s := &NodeInventoryStore{ + dir: dir, + records: make(map[string]NodeRegistration), + } + if err := s.load(); err != nil { + return nil, err + } + return s, nil +} + +// RegisterNode records the latest observed inventory for a server. +// Repeating registration replaces observation fields, but still does not +// publish authority or readiness. +func (s *NodeInventoryStore) RegisterNode(reg NodeRegistration) (NodeRegistration, error) { + if err := validateNodeRegistration(reg); err != nil { + return NodeRegistration{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if reg.SeenAt.IsZero() { + reg.SeenAt = time.Now().UTC() + } + reg = normalizeNodeRegistration(reg) + if err := s.putLocked(reg); err != nil { + return NodeRegistration{}, err + } + s.records[reg.ServerID] = reg + return reg, nil +} + +// RemoveNode deletes one registration record. Missing nodes are a +// successful no-op so cleanup is retry-safe. +func (s *NodeInventoryStore) RemoveNode(serverID string) error { + if err := validateServerID(serverID); err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + delete(s.records, serverID) + if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err) + } + return nil +} + +// GetNode returns a copy of one registration record. +func (s *NodeInventoryStore) GetNode(serverID string) (NodeRegistration, bool) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[serverID] + return copyNodeRegistration(rec), ok +} + +// ListNodes returns registration records ordered by ServerID. +func (s *NodeInventoryStore) ListNodes() []NodeRegistration { + s.mu.Lock() + defer s.mu.Unlock() + keys := make([]string, 0, len(s.records)) + for k := range s.records { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]NodeRegistration, 0, len(keys)) + for _, k := range keys { + out = append(out, copyNodeRegistration(s.records[k])) + } + return out +} + +func (s *NodeInventoryStore) load() error { + entries, err := os.ReadDir(s.dir) + if err != nil { + return fmt.Errorf("lifecycle: readdir node inventory %q: %w", s.dir, err) + } + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { + continue + } + path := filepath.Join(s.dir, entry.Name()) + raw, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("lifecycle: read node %q: %w", path, err) + } + var rec NodeRegistration + if err := json.Unmarshal(raw, &rec); err != nil { + return fmt.Errorf("lifecycle: parse node %q: %w", path, err) + } + if err := validateNodeRegistration(rec); err != nil { + return fmt.Errorf("lifecycle: invalid node record %q: %w", path, err) + } + if filepath.Base(s.path(rec.ServerID)) != entry.Name() { + return fmt.Errorf("lifecycle: node filename %q does not match server_id %q", entry.Name(), rec.ServerID) + } + s.records[rec.ServerID] = normalizeNodeRegistration(rec) + } + return nil +} + +func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { + raw, err := json.MarshalIndent(rec, "", " ") + if err != nil { + return fmt.Errorf("lifecycle: marshal node %s: %w", rec.ServerID, err) + } + path := s.path(rec.ServerID) + tmp, err := os.CreateTemp(s.dir, rec.ServerID+".*.tmp") + if err != nil { + return fmt.Errorf("lifecycle: temp node %s: %w", rec.ServerID, err) + } + tmpName := tmp.Name() + defer func() { _ = os.Remove(tmpName) }() + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: write node temp %s: %w", rec.ServerID, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("lifecycle: close node temp %s: %w", rec.ServerID, err) + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("lifecycle: replace node %s: %w", rec.ServerID, err) + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("lifecycle: rename node %s: %w", rec.ServerID, err) + } + return nil +} + +func (s *NodeInventoryStore) path(serverID string) string { + return filepath.Join(s.dir, serverID+".json") +} + +func validateNodeRegistration(reg NodeRegistration) error { + if err := validateServerID(reg.ServerID); err != nil { + return err + } + if reg.Addr == "" { + return fmt.Errorf("%w: empty addr", ErrInvalidNodeRegistration) + } + for _, pool := range reg.Pools { + if pool.PoolID == "" { + return fmt.Errorf("%w: empty pool id", ErrInvalidNodeRegistration) + } + if pool.BlockSize == 0 { + return fmt.Errorf("%w: pool %s block_size must be > 0", ErrInvalidNodeRegistration, pool.PoolID) + } + if pool.FreeBytes > pool.TotalBytes { + return fmt.Errorf("%w: pool %s free_bytes exceeds total_bytes", ErrInvalidNodeRegistration, pool.PoolID) + } + } + for _, replica := range reg.Replicas { + if err := validateReplicaInventory(replica); err != nil { + return err + } + } + return nil +} + +func validateReplicaInventory(replica ReplicaInventory) error { + if err := validateVolumeID(replica.VolumeID); err != nil { + return err + } + if replica.ReplicaID == "" { + return fmt.Errorf("%w: empty replica id", ErrInvalidNodeRegistration) + } + if replica.StoreUUID == "" { + return fmt.Errorf("%w: empty store uuid", ErrInvalidNodeRegistration) + } + if replica.SizeBytes == 0 { + return fmt.Errorf("%w: replica %s/%s size_bytes must be > 0", ErrInvalidNodeRegistration, replica.VolumeID, replica.ReplicaID) + } + if replica.State == "" { + return fmt.Errorf("%w: replica %s/%s empty state", ErrInvalidNodeRegistration, replica.VolumeID, replica.ReplicaID) + } + return nil +} + +func validateServerID(serverID string) error { + if serverID == "" { + return fmt.Errorf("%w: empty server id", ErrInvalidNodeRegistration) + } + if !volumeIDPattern.MatchString(serverID) { + return fmt.Errorf("%w: invalid server id %q", ErrInvalidNodeRegistration, serverID) + } + return nil +} + +func normalizeNodeRegistration(reg NodeRegistration) NodeRegistration { + reg.Labels = copyStringMap(reg.Labels) + for i := range reg.Pools { + reg.Pools[i].Labels = copyStringMap(reg.Pools[i].Labels) + } + return reg +} + +func copyNodeRegistration(reg NodeRegistration) NodeRegistration { + out := reg + out.Labels = copyStringMap(reg.Labels) + out.Pools = append([]StoragePool(nil), reg.Pools...) + for i := range out.Pools { + out.Pools[i].Labels = copyStringMap(out.Pools[i].Labels) + } + out.Replicas = append([]ReplicaInventory(nil), reg.Replicas...) + return out +} + +func copyStringMap(in map[string]string) map[string]string { + if len(in) == 0 { + return nil + } + out := make(map[string]string, len(in)) + for k, v := range in { + out[k] = v + } + return out +} diff --git a/seaweed-block/core/lifecycle/node_inventory_test.go b/seaweed-block/core/lifecycle/node_inventory_test.go new file mode 100644 index 0000000000..764b1019eb --- /dev/null +++ b/seaweed-block/core/lifecycle/node_inventory_test.go @@ -0,0 +1,176 @@ +package lifecycle + +import ( + "reflect" + "testing" + "time" +) + +func TestNodeInventoryStore_RegisterNodePersistsCapacityAndReplicas(t *testing.T) { + dir := t.TempDir() + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatalf("open: %v", err) + } + seen := time.Date(2026, 5, 2, 12, 0, 0, 0, time.UTC) + reg := NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9100", + Labels: map[string]string{"rack": "r1"}, + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 29, + BlockSize: 4096, + Labels: map[string]string{"media": "ssd"}, + }}, + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r2", + StoreUUID: "store-1", + SizeBytes: 1 << 20, + DurableLSN: 42, + State: "existing", + }}, + SeenAt: seen, + } + if _, err := s.RegisterNode(reg); err != nil { + t.Fatalf("register: %v", err) + } + + reopened, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatalf("reopen: %v", err) + } + got, ok := reopened.GetNode("node-a") + if !ok { + t.Fatal("reopened store missing node") + } + if !reflect.DeepEqual(got, reg) { + t.Fatalf("node record mismatch:\ngot %+v\nwant %+v", got, reg) + } +} + +func TestNodeInventoryStore_RegisterNodeReplacesObservation(t *testing.T) { + s, err := OpenNodeInventoryStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + first := NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9100", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 100, + FreeBytes: 50, + BlockSize: 4096, + }}, + SeenAt: time.Unix(1, 0).UTC(), + } + if _, err := s.RegisterNode(first); err != nil { + t.Fatalf("first register: %v", err) + } + second := first + second.Pools[0].FreeBytes = 25 + second.SeenAt = time.Unix(2, 0).UTC() + if _, err := s.RegisterNode(second); err != nil { + t.Fatalf("second register: %v", err) + } + got, ok := s.GetNode("node-a") + if !ok { + t.Fatal("missing node") + } + if got.Pools[0].FreeBytes != 25 { + t.Fatalf("free_bytes=%d want 25", got.Pools[0].FreeBytes) + } + if !got.SeenAt.Equal(second.SeenAt) { + t.Fatalf("seen_at=%s want %s", got.SeenAt, second.SeenAt) + } +} + +func TestNodeInventoryStore_ReplicaInventoryDoesNotImplyReady(t *testing.T) { + s, err := OpenNodeInventoryStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + reg := NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9100", + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r2", + StoreUUID: "store-1", + SizeBytes: 1 << 20, + DurableLSN: 100, + State: "existing", + }}, + } + if _, err := s.RegisterNode(reg); err != nil { + t.Fatalf("register: %v", err) + } + got, ok := s.GetNode("node-a") + if !ok { + t.Fatal("missing node") + } + if got.Replicas[0].State != "existing" { + t.Fatalf("state=%q want existing", got.Replicas[0].State) + } + typ := reflect.TypeOf(got.Replicas[0]) + if _, ok := typ.FieldByName("Ready"); ok { + t.Fatal("replica inventory must not carry Ready; controller/recovery owns readiness") + } + if _, ok := typ.FieldByName("Primary"); ok { + t.Fatal("replica inventory must not carry Primary; publisher owns authority") + } +} + +func TestNodeInventoryStore_BlankCapacityIsInventoryOnly(t *testing.T) { + s, err := OpenNodeInventoryStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := s.RegisterNode(NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9100", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register: %v", err) + } + got, ok := s.GetNode("node-a") + if !ok { + t.Fatal("missing node") + } + if len(got.Pools) != 1 || len(got.Replicas) != 0 { + t.Fatalf("blank node inventory got pools=%d replicas=%d", len(got.Pools), len(got.Replicas)) + } + if _, ok := reflect.TypeOf(got).FieldByName("Assignment"); ok { + t.Fatal("node registration must not carry assignment") + } +} + +func TestNodeInventoryStore_RemoveNodeIsIdempotent(t *testing.T) { + s, err := OpenNodeInventoryStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := s.RegisterNode(NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9100", + }); err != nil { + t.Fatalf("register: %v", err) + } + if err := s.RemoveNode("node-a"); err != nil { + t.Fatalf("remove: %v", err) + } + if err := s.RemoveNode("node-a"); err != nil { + t.Fatalf("idempotent remove: %v", err) + } + if _, ok := s.GetNode("node-a"); ok { + t.Fatal("removed node still present") + } +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go new file mode 100644 index 0000000000..cde71af59e --- /dev/null +++ b/seaweed-block/core/lifecycle/store.go @@ -0,0 +1,264 @@ +// Package lifecycle owns product-shaped volume lifecycle intent. +// +// It deliberately stops before authority publication: +// create/attach/delete records are desired product state, not +// AssignmentInfo and not epoch/endpoint-version truth. Later placement +// and publisher slices consume this state through a planner seam. +package lifecycle + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "sync" +) + +var ( + ErrInvalidVolumeSpec = errors.New("lifecycle: invalid volume spec") + ErrVolumeConflict = errors.New("lifecycle: volume already exists with different spec") + ErrVolumeNotFound = errors.New("lifecycle: volume not found") + ErrAlreadyAttached = errors.New("lifecycle: volume already attached to another node") + ErrAttachedElsewhere = errors.New("lifecycle: volume attached to another node") +) + +var volumeIDPattern = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) + +// VolumeSpec is the product-level desired volume shape. It carries no +// authority lineage and no placement decision. +type VolumeSpec struct { + VolumeID string `json:"volume_id"` + SizeBytes uint64 `json:"size_bytes"` + ReplicationFactor int `json:"replication_factor"` +} + +// VolumeRecord is the durable lifecycle state for one volume. +type VolumeRecord struct { + Spec VolumeSpec `json:"spec"` + AttachedTo string `json:"attached_to,omitempty"` +} + +// FileStore persists one JSON record per volume ID. +type FileStore struct { + mu sync.Mutex + dir string + records map[string]VolumeRecord +} + +// OpenFileStore opens or creates a lifecycle intent store. +func OpenFileStore(dir string) (*FileStore, error) { + if dir == "" { + return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("lifecycle: mkdir %q: %w", dir, err) + } + s := &FileStore{ + dir: dir, + records: make(map[string]VolumeRecord), + } + if err := s.load(); err != nil { + return nil, err + } + return s, nil +} + +// CreateVolume records desired volume state. Repeating the same spec is +// idempotent; changing a previously-created spec is rejected. +func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { + if err := validateSpec(spec); err != nil { + return VolumeRecord{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if existing, ok := s.records[spec.VolumeID]; ok { + if existing.Spec != spec { + return VolumeRecord{}, ErrVolumeConflict + } + return existing, nil + } + rec := VolumeRecord{Spec: spec} + if err := s.putLocked(rec); err != nil { + return VolumeRecord{}, err + } + s.records[spec.VolumeID] = rec + return rec, nil +} + +// DeleteVolume removes a desired volume record. Missing volumes are a +// successful no-op so delete is safe to retry. +func (s *FileStore) DeleteVolume(volumeID string) error { + if err := validateVolumeID(volumeID); err != nil { + return err + } + 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 %s: %w", volumeID, err) + } + return nil +} + +// AttachVolume records a publish/attach intent. Attaching to the same node +// is idempotent; attaching elsewhere requires a detach first. +func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error) { + if err := validateVolumeID(volumeID); err != nil { + return VolumeRecord{}, err + } + if nodeID == "" { + return VolumeRecord{}, fmt.Errorf("%w: empty node id", ErrInvalidVolumeSpec) + } + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + if !ok { + return VolumeRecord{}, ErrVolumeNotFound + } + if rec.AttachedTo != "" && rec.AttachedTo != nodeID { + return VolumeRecord{}, ErrAlreadyAttached + } + rec.AttachedTo = nodeID + if err := s.putLocked(rec); err != nil { + return VolumeRecord{}, err + } + s.records[volumeID] = rec + return rec, nil +} + +// DetachVolume clears an attach intent. Repeating the same detach is +// idempotent; detaching a volume attached elsewhere is rejected. +func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error) { + if err := validateVolumeID(volumeID); err != nil { + return VolumeRecord{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + if !ok { + return VolumeRecord{}, ErrVolumeNotFound + } + if rec.AttachedTo != "" && nodeID != "" && rec.AttachedTo != nodeID { + return VolumeRecord{}, ErrAttachedElsewhere + } + rec.AttachedTo = "" + if err := s.putLocked(rec); err != nil { + return VolumeRecord{}, err + } + s.records[volumeID] = rec + return rec, nil +} + +// GetVolume returns a copy of a volume record. +func (s *FileStore) GetVolume(volumeID string) (VolumeRecord, bool) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + return rec, ok +} + +// ListVolumes returns records ordered by VolumeID. +func (s *FileStore) ListVolumes() []VolumeRecord { + s.mu.Lock() + defer s.mu.Unlock() + keys := make([]string, 0, len(s.records)) + for k := range s.records { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]VolumeRecord, 0, len(keys)) + for _, k := range keys { + out = append(out, s.records[k]) + } + return out +} + +func (s *FileStore) load() error { + entries, err := os.ReadDir(s.dir) + if err != nil { + return fmt.Errorf("lifecycle: readdir %q: %w", s.dir, err) + } + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { + continue + } + path := filepath.Join(s.dir, entry.Name()) + raw, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("lifecycle: read %q: %w", path, err) + } + var rec VolumeRecord + if err := json.Unmarshal(raw, &rec); err != nil { + return fmt.Errorf("lifecycle: parse %q: %w", path, err) + } + if err := validateSpec(rec.Spec); err != nil { + return fmt.Errorf("lifecycle: invalid record %q: %w", path, err) + } + if filepath.Base(s.path(rec.Spec.VolumeID)) != entry.Name() { + return fmt.Errorf("lifecycle: record filename %q does not match volume_id %q", entry.Name(), rec.Spec.VolumeID) + } + s.records[rec.Spec.VolumeID] = rec + } + return nil +} + +func (s *FileStore) putLocked(rec VolumeRecord) error { + raw, err := json.MarshalIndent(rec, "", " ") + if err != nil { + return fmt.Errorf("lifecycle: marshal %s: %w", rec.Spec.VolumeID, err) + } + path := s.path(rec.Spec.VolumeID) + tmp, err := os.CreateTemp(s.dir, rec.Spec.VolumeID+".*.tmp") + if err != nil { + return fmt.Errorf("lifecycle: temp %s: %w", rec.Spec.VolumeID, err) + } + tmpName := tmp.Name() + defer func() { _ = os.Remove(tmpName) }() + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: write temp %s: %w", rec.Spec.VolumeID, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("lifecycle: close temp %s: %w", rec.Spec.VolumeID, err) + } + // Windows os.Rename does not replace existing files. Remove first; + // lifecycle records are intent metadata, and the in-memory state is + // updated only after this write succeeds. + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("lifecycle: replace %s: %w", rec.Spec.VolumeID, err) + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("lifecycle: rename %s: %w", rec.Spec.VolumeID, err) + } + return nil +} + +func (s *FileStore) path(volumeID string) string { + return filepath.Join(s.dir, volumeID+".json") +} + +func validateSpec(spec VolumeSpec) error { + if err := validateVolumeID(spec.VolumeID); err != nil { + return err + } + if spec.SizeBytes == 0 { + return fmt.Errorf("%w: size_bytes must be > 0", ErrInvalidVolumeSpec) + } + if spec.ReplicationFactor <= 0 { + return fmt.Errorf("%w: replication_factor must be > 0", ErrInvalidVolumeSpec) + } + return nil +} + +func validateVolumeID(volumeID string) error { + if volumeID == "" { + return fmt.Errorf("%w: empty volume id", ErrInvalidVolumeSpec) + } + if !volumeIDPattern.MatchString(volumeID) { + return fmt.Errorf("%w: invalid volume id %q", ErrInvalidVolumeSpec, volumeID) + } + return nil +} diff --git a/seaweed-block/core/lifecycle/store_test.go b/seaweed-block/core/lifecycle/store_test.go new file mode 100644 index 0000000000..6123d467a3 --- /dev/null +++ b/seaweed-block/core/lifecycle/store_test.go @@ -0,0 +1,155 @@ +package lifecycle + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFileStore_CreateVolumePersistsAndIsIdempotent(t *testing.T) { + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatalf("open: %v", err) + } + spec := VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 2} + rec, err := s.CreateVolume(spec) + if err != nil { + t.Fatalf("create: %v", err) + } + if rec.Spec != spec { + t.Fatalf("record spec=%+v want %+v", rec.Spec, spec) + } + rec2, err := s.CreateVolume(spec) + if err != nil { + t.Fatalf("idempotent create: %v", err) + } + if rec2 != rec { + t.Fatalf("idempotent create changed record: got %+v want %+v", rec2, rec) + } + + reopened, err := OpenFileStore(dir) + if err != nil { + t.Fatalf("reopen: %v", err) + } + got, ok := reopened.GetVolume("vol-a") + if !ok { + t.Fatal("reopened store missing volume") + } + if got.Spec != spec { + t.Fatalf("reopened spec=%+v want %+v", got.Spec, spec) + } +} + +func TestFileStore_CreateVolumeRejectsConflictingSpec(t *testing.T) { + s, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + spec := VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 2} + if _, err := s.CreateVolume(spec); err != nil { + t.Fatalf("create: %v", err) + } + if _, err := s.CreateVolume(VolumeSpec{VolumeID: "vol-a", SizeBytes: 2 << 20, ReplicationFactor: 2}); err == nil { + t.Fatal("conflicting create must fail") + } +} + +func TestFileStore_AttachDetachAreIdempotent(t *testing.T) { + s, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + spec := VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 2} + if _, err := s.CreateVolume(spec); err != nil { + t.Fatalf("create: %v", err) + } + rec, err := s.AttachVolume("vol-a", "node-1") + if err != nil { + t.Fatalf("attach: %v", err) + } + if rec.AttachedTo != "node-1" { + t.Fatalf("attached_to=%q want node-1", rec.AttachedTo) + } + if _, err := s.AttachVolume("vol-a", "node-1"); err != nil { + t.Fatalf("idempotent attach: %v", err) + } + if _, err := s.AttachVolume("vol-a", "node-2"); err == nil { + t.Fatal("attach to a different node must fail until detached") + } + if _, err := s.DetachVolume("vol-a", "node-1"); err != nil { + t.Fatalf("detach: %v", err) + } + rec, err = s.DetachVolume("vol-a", "node-1") + if err != nil { + t.Fatalf("idempotent detach: %v", err) + } + if rec.AttachedTo != "" { + t.Fatalf("detached volume attached_to=%q want empty", rec.AttachedTo) + } +} + +func TestFileStore_DeleteVolumeRemovesRecord(t *testing.T) { + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := s.CreateVolume(VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 2}); err != nil { + t.Fatalf("create: %v", err) + } + if err := s.DeleteVolume("vol-a"); err != nil { + t.Fatalf("delete: %v", err) + } + if err := s.DeleteVolume("vol-a"); err != nil { + t.Fatalf("idempotent delete: %v", err) + } + reopened, err := OpenFileStore(dir) + if err != nil { + t.Fatalf("reopen: %v", err) + } + if _, ok := reopened.GetVolume("vol-a"); ok { + t.Fatal("deleted volume still present after reopen") + } +} + +func TestLifecyclePackageDoesNotImportAdapterOrAssignmentInfo(t *testing.T) { + root := "." + entries, err := os.ReadDir(root) + if err != nil { + t.Fatalf("readdir: %v", err) + } + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".go" || strings.HasSuffix(entry.Name(), "_test.go") { + continue + } + path := filepath.Join(root, entry.Name()) + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly) + if err != nil { + t.Fatalf("parse imports %s: %v", path, err) + } + for _, imp := range file.Imports { + if imp.Path.Value == `"github.com/seaweedfs/seaweed-block/core/adapter"` { + t.Fatalf("lifecycle package must not import adapter: %s", path) + } + } + full, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + ast.Inspect(full, func(n ast.Node) bool { + if ident, ok := n.(*ast.Ident); ok && ident.Name == "AssignmentInfo" { + t.Fatalf("lifecycle package must not mention AssignmentInfo: %s", path) + } + if ident, ok := n.(*ast.Ident); ok && ident.Name == "AssignmentFact" { + t.Fatalf("lifecycle package must not mention AssignmentFact: %s", path) + } + return true + }) + } +} From ebae9e2369170db60c82869637eab0a0b74c8763 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 20:35:21 -0700 Subject: [PATCH 02/10] G9D: add placement planner candidates --- seaweed-block/core/lifecycle/planner.go | 132 ++++++++++++ seaweed-block/core/lifecycle/planner_test.go | 208 +++++++++++++++++++ 2 files changed, 340 insertions(+) create mode 100644 seaweed-block/core/lifecycle/planner.go create mode 100644 seaweed-block/core/lifecycle/planner_test.go diff --git a/seaweed-block/core/lifecycle/planner.go b/seaweed-block/core/lifecycle/planner.go new file mode 100644 index 0000000000..2404dcdece --- /dev/null +++ b/seaweed-block/core/lifecycle/planner.go @@ -0,0 +1,132 @@ +package lifecycle + +import ( + "fmt" + "sort" +) + +const ( + PlacementSourceBlankPool = "blank_pool" + PlacementSourceExistingReplica = "existing_replica" +) + +// PlacementCandidate is planner output. It is a candidate for future +// controller action, not an assignment and not readiness. +type PlacementCandidate struct { + VolumeID string + ServerID string + PoolID string + ReplicaID string + Source string +} + +// PlacementConflict records inventory that blocks automatic placement. +type PlacementConflict struct { + VolumeID string + ServerID string + Reason string +} + +// PlacementPlan summarizes candidate slots for one desired volume. +type PlacementPlan struct { + VolumeID string + DesiredRF int + Candidates []PlacementCandidate + Conflicts []PlacementConflict +} + +// PlanPlacement converts desired volume state plus node inventory into +// placement candidates. It deliberately stops before authority: callers must +// pass the plan through a controller/publisher seam before any assignment can +// exist. +func PlanPlacement(volume VolumeRecord, nodes []NodeRegistration) PlacementPlan { + spec := volume.Spec + plan := PlacementPlan{ + VolumeID: spec.VolumeID, + DesiredRF: spec.ReplicationFactor, + } + seenServers := make(map[string]bool) + nodes = append([]NodeRegistration(nil), nodes...) + sort.Slice(nodes, func(i, j int) bool { + return nodes[i].ServerID < nodes[j].ServerID + }) + for _, node := range nodes { + if seenServers[node.ServerID] { + plan.Conflicts = append(plan.Conflicts, PlacementConflict{ + VolumeID: spec.VolumeID, + ServerID: node.ServerID, + Reason: "duplicate server inventory", + }) + continue + } + seenServers[node.ServerID] = true + if existing, ok := matchingReplica(spec.VolumeID, node.Replicas); ok { + if existing.SizeBytes != spec.SizeBytes { + plan.Conflicts = append(plan.Conflicts, PlacementConflict{ + VolumeID: spec.VolumeID, + ServerID: node.ServerID, + Reason: fmt.Sprintf("existing replica %s size %d != desired %d", + existing.ReplicaID, existing.SizeBytes, spec.SizeBytes), + }) + continue + } + plan.Candidates = append(plan.Candidates, PlacementCandidate{ + VolumeID: spec.VolumeID, + ServerID: node.ServerID, + ReplicaID: existing.ReplicaID, + Source: PlacementSourceExistingReplica, + }) + continue + } + if pool, ok := firstPoolWithCapacity(spec.SizeBytes, node.Pools); ok { + plan.Candidates = append(plan.Candidates, PlacementCandidate{ + VolumeID: spec.VolumeID, + ServerID: node.ServerID, + PoolID: pool.PoolID, + Source: PlacementSourceBlankPool, + }) + continue + } + plan.Conflicts = append(plan.Conflicts, PlacementConflict{ + VolumeID: spec.VolumeID, + ServerID: node.ServerID, + Reason: "no matching replica and no pool with enough free capacity", + }) + } + if len(plan.Candidates) > spec.ReplicationFactor { + plan.Candidates = plan.Candidates[:spec.ReplicationFactor] + } + return plan +} + +// EnoughCandidates reports whether the plan has enough candidate slots to +// satisfy the desired replication factor. This is a planner predicate only; +// it must not be treated as authority or replica_ready. +func (p PlacementPlan) EnoughCandidates() bool { + return p.DesiredRF > 0 && len(p.Candidates) >= p.DesiredRF +} + +func matchingReplica(volumeID string, replicas []ReplicaInventory) (ReplicaInventory, bool) { + for _, replica := range replicas { + if replica.VolumeID == volumeID { + return replica, true + } + } + return ReplicaInventory{}, false +} + +func firstPoolWithCapacity(sizeBytes uint64, pools []StoragePool) (StoragePool, bool) { + pools = append([]StoragePool(nil), pools...) + sort.Slice(pools, func(i, j int) bool { + if pools[i].FreeBytes == pools[j].FreeBytes { + return pools[i].PoolID < pools[j].PoolID + } + return pools[i].FreeBytes > pools[j].FreeBytes + }) + for _, pool := range pools { + if pool.FreeBytes >= sizeBytes { + return pool, true + } + } + return StoragePool{}, false +} diff --git a/seaweed-block/core/lifecycle/planner_test.go b/seaweed-block/core/lifecycle/planner_test.go new file mode 100644 index 0000000000..5a944d4cd7 --- /dev/null +++ b/seaweed-block/core/lifecycle/planner_test.go @@ -0,0 +1,208 @@ +package lifecycle + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "testing" +) + +func TestPlanPlacement_BlankCapacityProducesCandidatesOnly(t *testing.T) { + volume := VolumeRecord{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }} + nodes := []NodeRegistration{ + { + ServerID: "node-b", + Addr: "127.0.0.1:9102", + Pools: []StoragePool{{ + PoolID: "pool-b", + TotalBytes: 1 << 30, + FreeBytes: 1 << 29, + BlockSize: 4096, + }}, + }, + { + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }, + } + plan := PlanPlacement(volume, nodes) + if !plan.EnoughCandidates() { + t.Fatalf("plan should have enough candidates: %+v", plan) + } + if len(plan.Candidates) != 2 { + t.Fatalf("candidate count=%d want 2", len(plan.Candidates)) + } + if plan.Candidates[0].ServerID != "node-a" || plan.Candidates[1].ServerID != "node-b" { + t.Fatalf("candidates should be deterministic by server id: %+v", plan.Candidates) + } + for _, c := range plan.Candidates { + if c.Source != PlacementSourceBlankPool { + t.Fatalf("source=%q want %q", c.Source, PlacementSourceBlankPool) + } + if c.ReplicaID != "" { + t.Fatalf("blank-pool candidate must not assign replica id: %+v", c) + } + } +} + +func TestPlanPlacement_ExistingReplicaIsCandidateButNotReady(t *testing.T) { + volume := VolumeRecord{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }} + plan := PlanPlacement(volume, []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r2", + StoreUUID: "store-1", + SizeBytes: 1 << 20, + DurableLSN: 99, + State: "existing", + }}, + }}) + if !plan.EnoughCandidates() { + t.Fatalf("plan should have existing candidate: %+v", plan) + } + got := plan.Candidates[0] + if got.Source != PlacementSourceExistingReplica || got.ReplicaID != "r2" { + t.Fatalf("existing candidate mismatch: %+v", got) + } + typ := mustParseStruct(t, "planner.go", "PlacementCandidate") + if _, ok := typ.Fields["Ready"]; ok { + t.Fatal("placement candidate must not carry Ready") + } + if _, ok := typ.Fields["Primary"]; ok { + t.Fatal("placement candidate must not carry Primary") + } +} + +func TestPlanPlacement_ExistingReplicaSizeMismatchConflicts(t *testing.T) { + volume := VolumeRecord{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }} + plan := PlanPlacement(volume, []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r2", + StoreUUID: "store-1", + SizeBytes: 2 << 20, + State: "existing", + }}, + }}) + if plan.EnoughCandidates() { + t.Fatalf("conflicting existing replica must not be candidate: %+v", plan) + } + if len(plan.Conflicts) != 1 { + t.Fatalf("conflict count=%d want 1: %+v", len(plan.Conflicts), plan) + } + if plan.Candidates != nil { + t.Fatalf("candidates=%+v want none", plan.Candidates) + } +} + +func TestPlanPlacement_InsufficientCapacityDoesNotOverclaim(t *testing.T) { + volume := VolumeRecord{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }} + plan := PlanPlacement(volume, []NodeRegistration{ + { + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 29, + BlockSize: 4096, + }}, + }, + { + ServerID: "node-b", + Addr: "127.0.0.1:9102", + Pools: []StoragePool{{ + PoolID: "pool-b", + TotalBytes: 1 << 30, + FreeBytes: 512, + BlockSize: 4096, + }}, + }, + }) + if plan.EnoughCandidates() { + t.Fatalf("plan must not claim enough candidates: %+v", plan) + } + if len(plan.Candidates) != 1 || len(plan.Conflicts) != 1 { + t.Fatalf("candidate/conflict counts got %d/%d want 1/1: %+v", + len(plan.Candidates), len(plan.Conflicts), plan) + } +} + +func TestPlannerPackageDoesNotMentionAuthorityTypes(t *testing.T) { + for _, name := range []string{"PlacementCandidate", "PlacementPlan"} { + typ := mustParseStruct(t, "planner.go", name) + for _, forbidden := range []string{"Epoch", "EndpointVersion", "Assignment", "Ready", "Healthy"} { + if _, ok := typ.Fields[forbidden]; ok { + t.Fatalf("%s must not carry %s", name, forbidden) + } + } + } +} + +type parsedStruct struct { + Fields map[string]struct{} +} + +func mustParseStruct(t *testing.T, fileName, structName string) parsedStruct { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, filepath.Clean(fileName), nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", fileName, err) + } + var out parsedStruct + ast.Inspect(file, func(n ast.Node) bool { + typeSpec, ok := n.(*ast.TypeSpec) + if !ok || typeSpec.Name.Name != structName { + return true + } + st, ok := typeSpec.Type.(*ast.StructType) + if !ok { + t.Fatalf("%s is not a struct", structName) + } + out.Fields = make(map[string]struct{}) + for _, field := range st.Fields.List { + for _, name := range field.Names { + out.Fields[name.Name] = struct{}{} + } + } + return false + }) + if out.Fields == nil { + t.Fatalf("struct %s not found in %s", structName, fileName) + } + return out +} From 7e8f8a1a7b6cdf2be13204d860e21eabab81199c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 20:40:26 -0700 Subject: [PATCH 03/10] G9D: add placement intent store --- .../core/lifecycle/placement_intent.go | 230 ++++++++++++++++++ .../core/lifecycle/placement_intent_test.go | 119 +++++++++ 2 files changed, 349 insertions(+) create mode 100644 seaweed-block/core/lifecycle/placement_intent.go create mode 100644 seaweed-block/core/lifecycle/placement_intent_test.go diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go new file mode 100644 index 0000000000..4480fbcf5d --- /dev/null +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -0,0 +1,230 @@ +package lifecycle + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "sync" +) + +var ErrInsufficientPlacementCandidates = errors.New("lifecycle: insufficient placement candidates") + +// PlacementSlotIntent is the controller-facing desired slot generated from a +// placement plan. It is still not authority: no epoch, no endpoint version, +// no readiness. +type PlacementSlotIntent struct { + ServerID string `json:"server_id"` + PoolID string `json:"pool_id,omitempty"` + ReplicaID string `json:"replica_id,omitempty"` + Source string `json:"source"` +} + +// PlacementIntent is durable controller input for one volume. +type PlacementIntent struct { + VolumeID string `json:"volume_id"` + DesiredRF int `json:"desired_rf"` + Slots []PlacementSlotIntent `json:"slots"` +} + +// PlacementIntentStore persists one placement intent per volume. +type PlacementIntentStore struct { + mu sync.Mutex + dir string + records map[string]PlacementIntent +} + +// OpenPlacementIntentStore opens or creates a placement intent store. +func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { + if dir == "" { + return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("lifecycle: mkdir placement intent %q: %w", dir, err) + } + s := &PlacementIntentStore{ + dir: dir, + records: make(map[string]PlacementIntent), + } + if err := s.load(); err != nil { + return nil, err + } + return s, nil +} + +// ApplyPlan records placement intent from a sufficient plan. Insufficient +// plans are rejected rather than persisted as partial authority-shaped state. +func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, error) { + if !plan.EnoughCandidates() { + return PlacementIntent{}, ErrInsufficientPlacementCandidates + } + intent := PlacementIntent{ + VolumeID: plan.VolumeID, + DesiredRF: plan.DesiredRF, + Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF), + } + for _, candidate := range plan.Candidates[:plan.DesiredRF] { + intent.Slots = append(intent.Slots, PlacementSlotIntent{ + ServerID: candidate.ServerID, + PoolID: candidate.PoolID, + ReplicaID: candidate.ReplicaID, + Source: candidate.Source, + }) + } + if err := validatePlacementIntent(intent); err != nil { + return PlacementIntent{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := s.putLocked(intent); err != nil { + return PlacementIntent{}, err + } + s.records[intent.VolumeID] = intent + return copyPlacementIntent(intent), nil +} + +// DeletePlacement removes one placement intent. Missing intents are a +// successful no-op so reconciliation cleanup is retry-safe. +func (s *PlacementIntentStore) DeletePlacement(volumeID string) error { + if err := validateVolumeID(volumeID); err != nil { + return err + } + 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) + } + return nil +} + +// GetPlacement returns a copy of one placement intent. +func (s *PlacementIntentStore) GetPlacement(volumeID string) (PlacementIntent, bool) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + return copyPlacementIntent(rec), ok +} + +// ListPlacements returns intents ordered by VolumeID. +func (s *PlacementIntentStore) ListPlacements() []PlacementIntent { + s.mu.Lock() + defer s.mu.Unlock() + keys := make([]string, 0, len(s.records)) + for k := range s.records { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]PlacementIntent, 0, len(keys)) + for _, k := range keys { + out = append(out, copyPlacementIntent(s.records[k])) + } + return out +} + +func (s *PlacementIntentStore) load() error { + entries, err := os.ReadDir(s.dir) + if err != nil { + return fmt.Errorf("lifecycle: readdir placement intent %q: %w", s.dir, err) + } + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { + continue + } + path := filepath.Join(s.dir, entry.Name()) + raw, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("lifecycle: read placement intent %q: %w", path, err) + } + var rec PlacementIntent + if err := json.Unmarshal(raw, &rec); err != nil { + return fmt.Errorf("lifecycle: parse placement intent %q: %w", path, err) + } + if err := validatePlacementIntent(rec); err != nil { + return fmt.Errorf("lifecycle: invalid placement intent %q: %w", path, err) + } + if filepath.Base(s.path(rec.VolumeID)) != entry.Name() { + return fmt.Errorf("lifecycle: placement filename %q does not match volume_id %q", entry.Name(), rec.VolumeID) + } + s.records[rec.VolumeID] = rec + } + return nil +} + +func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { + raw, err := json.MarshalIndent(rec, "", " ") + if err != nil { + return fmt.Errorf("lifecycle: marshal placement intent %s: %w", rec.VolumeID, err) + } + path := s.path(rec.VolumeID) + tmp, err := os.CreateTemp(s.dir, rec.VolumeID+".*.tmp") + if err != nil { + return fmt.Errorf("lifecycle: temp placement intent %s: %w", rec.VolumeID, err) + } + tmpName := tmp.Name() + defer func() { _ = os.Remove(tmpName) }() + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: write placement intent temp %s: %w", rec.VolumeID, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("lifecycle: close placement intent temp %s: %w", rec.VolumeID, err) + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("lifecycle: replace placement intent %s: %w", rec.VolumeID, err) + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("lifecycle: rename placement intent %s: %w", rec.VolumeID, err) + } + return nil +} + +func (s *PlacementIntentStore) path(volumeID string) string { + return filepath.Join(s.dir, volumeID+".json") +} + +func validatePlacementIntent(intent PlacementIntent) error { + if err := validateVolumeID(intent.VolumeID); err != nil { + return err + } + if intent.DesiredRF <= 0 { + return fmt.Errorf("%w: desired_rf must be > 0", ErrInvalidVolumeSpec) + } + if len(intent.Slots) != intent.DesiredRF { + return fmt.Errorf("%w: slot count %d != desired_rf %d", ErrInvalidVolumeSpec, len(intent.Slots), intent.DesiredRF) + } + seenServers := make(map[string]bool) + for _, slot := range intent.Slots { + if err := validateServerID(slot.ServerID); err != nil { + return err + } + if seenServers[slot.ServerID] { + return fmt.Errorf("%w: duplicate server %s", ErrInvalidVolumeSpec, slot.ServerID) + } + seenServers[slot.ServerID] = true + switch slot.Source { + case PlacementSourceBlankPool: + if slot.PoolID == "" { + return fmt.Errorf("%w: blank-pool slot on %s missing pool id", ErrInvalidVolumeSpec, slot.ServerID) + } + if slot.ReplicaID != "" { + return fmt.Errorf("%w: blank-pool slot on %s must not preassign replica id", ErrInvalidVolumeSpec, slot.ServerID) + } + case PlacementSourceExistingReplica: + if slot.ReplicaID == "" { + return fmt.Errorf("%w: existing-replica slot on %s missing replica id", ErrInvalidVolumeSpec, slot.ServerID) + } + default: + return fmt.Errorf("%w: unknown placement source %q", ErrInvalidVolumeSpec, slot.Source) + } + } + return nil +} + +func copyPlacementIntent(in PlacementIntent) PlacementIntent { + out := in + out.Slots = append([]PlacementSlotIntent(nil), in.Slots...) + return out +} diff --git a/seaweed-block/core/lifecycle/placement_intent_test.go b/seaweed-block/core/lifecycle/placement_intent_test.go new file mode 100644 index 0000000000..5814855e22 --- /dev/null +++ b/seaweed-block/core/lifecycle/placement_intent_test.go @@ -0,0 +1,119 @@ +package lifecycle + +import ( + "errors" + "reflect" + "testing" +) + +func TestPlacementIntentStore_ApplyPlanPersistsSufficientPlan(t *testing.T) { + dir := t.TempDir() + s, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatalf("open: %v", err) + } + plan := PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 2, + Candidates: []PlacementCandidate{ + {VolumeID: "vol-a", ServerID: "node-a", PoolID: "pool-a", Source: PlacementSourceBlankPool}, + {VolumeID: "vol-a", ServerID: "node-b", ReplicaID: "r2", Source: PlacementSourceExistingReplica}, + }, + } + intent, err := s.ApplyPlan(plan) + if err != nil { + t.Fatalf("apply plan: %v", err) + } + if intent.VolumeID != "vol-a" || intent.DesiredRF != 2 || len(intent.Slots) != 2 { + t.Fatalf("intent mismatch: %+v", intent) + } + + reopened, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatalf("reopen: %v", err) + } + got, ok := reopened.GetPlacement("vol-a") + if !ok { + t.Fatal("reopened store missing placement intent") + } + if !reflect.DeepEqual(got, intent) { + t.Fatalf("reopened intent mismatch:\ngot %+v\nwant %+v", got, intent) + } +} + +func TestPlacementIntentStore_RejectsInsufficientPlan(t *testing.T) { + s, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + _, err = s.ApplyPlan(PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 2, + Candidates: []PlacementCandidate{ + {VolumeID: "vol-a", ServerID: "node-a", PoolID: "pool-a", Source: PlacementSourceBlankPool}, + }, + }) + if !errors.Is(err, ErrInsufficientPlacementCandidates) { + t.Fatalf("err=%v want ErrInsufficientPlacementCandidates", err) + } + if _, ok := s.GetPlacement("vol-a"); ok { + t.Fatal("insufficient plan must not persist placement intent") + } +} + +func TestPlacementIntentStore_UsesOnlyDesiredRFSlots(t *testing.T) { + s, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + intent, err := s.ApplyPlan(PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 1, + Candidates: []PlacementCandidate{ + {VolumeID: "vol-a", ServerID: "node-a", PoolID: "pool-a", Source: PlacementSourceBlankPool}, + {VolumeID: "vol-a", ServerID: "node-b", PoolID: "pool-b", Source: PlacementSourceBlankPool}, + }, + }) + if err != nil { + t.Fatalf("apply: %v", err) + } + if len(intent.Slots) != 1 || intent.Slots[0].ServerID != "node-a" { + t.Fatalf("intent slots=%+v want only node-a", intent.Slots) + } +} + +func TestPlacementIntentStore_RejectsAuthorityShapedIntent(t *testing.T) { + for _, name := range []string{"PlacementIntent", "PlacementSlotIntent"} { + typ := mustParseStruct(t, "placement_intent.go", name) + for _, forbidden := range []string{"Epoch", "EndpointVersion", "Assignment", "Ready", "Healthy", "Primary"} { + if _, ok := typ.Fields[forbidden]; ok { + t.Fatalf("%s must not carry %s", name, forbidden) + } + } + } +} + +func TestPlacementIntentStore_DeletePlacementIsIdempotent(t *testing.T) { + s, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := s.ApplyPlan(PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 1, + Candidates: []PlacementCandidate{ + {VolumeID: "vol-a", ServerID: "node-a", PoolID: "pool-a", Source: PlacementSourceBlankPool}, + }, + }); err != nil { + t.Fatalf("apply: %v", err) + } + if err := s.DeletePlacement("vol-a"); err != nil { + t.Fatalf("delete: %v", err) + } + if err := s.DeletePlacement("vol-a"); err != nil { + t.Fatalf("idempotent delete: %v", err) + } + if _, ok := s.GetPlacement("vol-a"); ok { + t.Fatal("deleted placement still present") + } +} From 992e411261fab80f34b1d834012eaf7b25fb16df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 20:46:48 -0700 Subject: [PATCH 04/10] G9D: reconcile lifecycle placement intents --- seaweed-block/core/lifecycle/reconciler.go | 36 +++++ .../core/lifecycle/reconciler_test.go | 126 ++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 seaweed-block/core/lifecycle/reconciler.go create mode 100644 seaweed-block/core/lifecycle/reconciler_test.go diff --git a/seaweed-block/core/lifecycle/reconciler.go b/seaweed-block/core/lifecycle/reconciler.go new file mode 100644 index 0000000000..639aefe39d --- /dev/null +++ b/seaweed-block/core/lifecycle/reconciler.go @@ -0,0 +1,36 @@ +package lifecycle + +// ReconcileResult reports one desired volume reconciliation attempt. +type ReconcileResult struct { + VolumeID string + Plan PlacementPlan + Intent PlacementIntent + Applied bool + Err error +} + +// ReconcilePlacement plans every desired volume against the latest node +// inventory and persists placement intent only when enough candidates exist. +// This is still controller input: no authority is minted here. +func ReconcilePlacement(volumes []VolumeRecord, nodes []NodeRegistration, placements *PlacementIntentStore) []ReconcileResult { + volumes = append([]VolumeRecord(nil), volumes...) + nodes = append([]NodeRegistration(nil), nodes...) + results := make([]ReconcileResult, 0, len(volumes)) + for _, volume := range volumes { + plan := PlanPlacement(volume, nodes) + result := ReconcileResult{ + VolumeID: volume.Spec.VolumeID, + Plan: plan, + } + intent, err := placements.ApplyPlan(plan) + if err != nil { + result.Err = err + results = append(results, result) + continue + } + result.Intent = intent + result.Applied = true + results = append(results, result) + } + return results +} diff --git a/seaweed-block/core/lifecycle/reconciler_test.go b/seaweed-block/core/lifecycle/reconciler_test.go new file mode 100644 index 0000000000..16c012460b --- /dev/null +++ b/seaweed-block/core/lifecycle/reconciler_test.go @@ -0,0 +1,126 @@ +package lifecycle + +import ( + "errors" + "testing" +) + +func TestReconcilePlacement_HappyPathWritesPlacementIntent(t *testing.T) { + volumes := []VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }}} + nodes := []NodeRegistration{ + nodeWithPool("node-a", "pool-a", 1<<30), + nodeWithPool("node-b", "pool-b", 1<<30), + } + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + results := ReconcilePlacement(volumes, nodes, store) + if len(results) != 1 { + t.Fatalf("result count=%d want 1", len(results)) + } + if !results[0].Applied || results[0].Err != nil { + t.Fatalf("result not applied: %+v", results[0]) + } + intent, ok := store.GetPlacement("vol-a") + if !ok { + t.Fatal("placement intent not written") + } + if intent.DesiredRF != 2 || len(intent.Slots) != 2 { + t.Fatalf("intent=%+v want RF=2 slots=2", intent) + } +} + +func TestReconcilePlacement_InsufficientInventoryReportsButDoesNotPersist(t *testing.T) { + volumes := []VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }}} + nodes := []NodeRegistration{nodeWithPool("node-a", "pool-a", 1<<30)} + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + results := ReconcilePlacement(volumes, nodes, store) + if len(results) != 1 { + t.Fatalf("result count=%d want 1", len(results)) + } + if results[0].Applied { + t.Fatalf("insufficient plan must not apply: %+v", results[0]) + } + if !errors.Is(results[0].Err, ErrInsufficientPlacementCandidates) { + t.Fatalf("err=%v want ErrInsufficientPlacementCandidates", results[0].Err) + } + if _, ok := store.GetPlacement("vol-a"); ok { + t.Fatal("insufficient reconcile must not persist placement") + } +} + +func TestReconcilePlacement_ExistingReplicaConflictIsReportOnly(t *testing.T) { + volumes := []VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }}} + nodes := []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Pools: []StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r2", + StoreUUID: "store-1", + SizeBytes: 2 << 20, + State: "existing", + }}, + }} + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + results := ReconcilePlacement(volumes, nodes, store) + if len(results) != 1 { + t.Fatalf("result count=%d want 1", len(results)) + } + if results[0].Applied { + t.Fatalf("conflict must not apply: %+v", results[0]) + } + if len(results[0].Plan.Conflicts) != 1 { + t.Fatalf("conflict count=%d want 1: %+v", len(results[0].Plan.Conflicts), results[0].Plan) + } + if _, ok := store.GetPlacement("vol-a"); ok { + t.Fatal("conflicting existing replica must not persist placement") + } +} + +func TestReconcilePlacement_ResultIsNotAuthorityShaped(t *testing.T) { + typ := mustParseStruct(t, "reconciler.go", "ReconcileResult") + for _, forbidden := range []string{"Epoch", "EndpointVersion", "Assignment", "Ready", "Healthy", "Primary"} { + if _, ok := typ.Fields[forbidden]; ok { + t.Fatalf("ReconcileResult must not carry %s", forbidden) + } + } +} + +func nodeWithPool(serverID, poolID string, freeBytes uint64) NodeRegistration { + return NodeRegistration{ + ServerID: serverID, + Addr: "127.0.0.1:9100", + Pools: []StoragePool{{ + PoolID: poolID, + TotalBytes: 1 << 30, + FreeBytes: freeBytes, + BlockSize: 4096, + }}, + } +} From 70a75606aff1f74624c221aac11cfbaa1bcfe6d4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 20:54:57 -0700 Subject: [PATCH 05/10] G9D: wire lifecycle stores into blockmaster --- seaweed-block/cmd/blockmaster/main.go | 3 + seaweed-block/cmd/blockmaster/main_test.go | 16 ++++ seaweed-block/core/host/master/host.go | 87 ++++++++++++++---- .../core/host/master/lifecycle_test.go | 90 +++++++++++++++++++ 4 files changed, 179 insertions(+), 17 deletions(-) create mode 100644 seaweed-block/cmd/blockmaster/main_test.go create mode 100644 seaweed-block/core/host/master/lifecycle_test.go diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 703910abef..81ac5f0385 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -20,6 +20,7 @@ import ( type flags struct { authorityStore string + lifecycleStore string listen string topology string expectedSlotsPerVol int @@ -36,6 +37,7 @@ func parseFlags(args []string) (flags, error) { var f flags fs := flag.NewFlagSet("blockmaster", flag.ContinueOnError) fs.StringVar(&f.authorityStore, "authority-store", "", "durable authority store directory (required)") + fs.StringVar(&f.lifecycleStore, "lifecycle-store", "", "optional G9D product lifecycle registration store directory (desired volumes, node inventory, placement intents); read-only with respect to assignment publication") fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180)") fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)") fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)") @@ -82,6 +84,7 @@ func run(f flags) int { } cfg := master.Config{ AuthorityStoreDir: f.authorityStore, + LifecycleStoreDir: f.lifecycleStore, Listen: f.listen, Topology: topo, Freshness: authority.FreshnessConfig{FreshnessWindow: f.freshnessWindow, PendingGrace: f.pendingGrace}, diff --git a/seaweed-block/cmd/blockmaster/main_test.go b/seaweed-block/cmd/blockmaster/main_test.go new file mode 100644 index 0000000000..7368ef132a --- /dev/null +++ b/seaweed-block/cmd/blockmaster/main_test.go @@ -0,0 +1,16 @@ +package main + +import "testing" + +func TestParseFlags_LifecycleStoreOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.lifecycleStore != "lifecycle-dir" { + t.Fatalf("lifecycleStore=%q want lifecycle-dir", f.lifecycleStore) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 42d2274981..31d83547b7 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -20,11 +20,13 @@ import ( "fmt" "log" "net" + "path/filepath" "sync" "sync/atomic" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/host/bootstrap" + "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" ) @@ -51,24 +53,40 @@ type Config struct { // ControllerConfig tunes controller knobs (retry window etc). ControllerConfig authority.TopologyControllerConfig + // LifecycleStoreDir, when non-empty, opens product lifecycle + // registration stores (desired volumes, node inventory, placement + // intents). This is read-only composition for G9D: these stores do + // NOT drive assignment publication. + LifecycleStoreDir string + // Logger is used for structured startup and error logging. If // nil, the default log package logger is used. Logger *log.Logger } +// LifecycleStores groups the product registration stores hosted by +// blockmaster. The stores are controller input only; assignment +// publication remains owned by authority.Controller/Publisher. +type LifecycleStores struct { + Volumes *lifecycle.FileStore + Nodes *lifecycle.NodeInventoryStore + Placements *lifecycle.PlacementIntentStore +} + // Host is the composed master-side block product daemon. Lifecycle // is: New -> Start -> (serve requests) -> Close. type Host struct { - cfg Config - log *log.Logger - boot *bootstrap.DurableAuthorityBootstrap - ctrl *authority.TopologyController - obs *authority.ObservationHost - ln net.Listener - grpc *grpc.Server - topo authority.AcceptedTopology - cancel context.CancelFunc - wg sync.WaitGroup + cfg Config + log *log.Logger + boot *bootstrap.DurableAuthorityBootstrap + ctrl *authority.TopologyController + obs *authority.ObservationHost + ln net.Listener + grpc *grpc.Server + topo authority.AcceptedTopology + lifecycle *LifecycleStores + cancel context.CancelFunc + wg sync.WaitGroup started atomic.Bool } @@ -150,6 +168,12 @@ func New(cfg Config) (*Host, error) { Reader: boot.Publisher, }) + lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) + if err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) + } + ln, err := net.Listen("tcp", cfg.Listen) if err != nil { _ = boot.Close() @@ -157,13 +181,14 @@ func New(cfg Config) (*Host, error) { } h := &Host{ - cfg: cfg, - log: lg, - boot: boot, - ctrl: ctrl, - obs: obs, - ln: ln, - topo: cfg.Topology, + cfg: cfg, + log: lg, + boot: boot, + ctrl: ctrl, + obs: obs, + ln: ln, + topo: cfg.Topology, + lifecycle: lifecycleStores, } grpcSrv := grpc.NewServer() @@ -181,6 +206,29 @@ func New(cfg Config) (*Host, error) { return h, nil } +func openLifecycleStores(dir string) (*LifecycleStores, error) { + if dir == "" { + return nil, nil + } + volumes, err := lifecycle.OpenFileStore(filepath.Join(dir, "volumes")) + if err != nil { + return nil, err + } + nodes, err := lifecycle.OpenNodeInventoryStore(filepath.Join(dir, "nodes")) + if err != nil { + return nil, err + } + placements, err := lifecycle.OpenPlacementIntentStore(filepath.Join(dir, "placements")) + if err != nil { + return nil, err + } + return &LifecycleStores{ + Volumes: volumes, + Nodes: nodes, + Placements: placements, + }, nil +} + // Addr returns the bound listener address. Valid after New. func (h *Host) Addr() string { return h.ln.Addr().String() } @@ -194,6 +242,11 @@ func (h *Host) Controller() *authority.TopologyController { return h.ctrl } // ObservationHost exposes the observation host for tests. func (h *Host) ObservationHost() *authority.ObservationHost { return h.obs } +// Lifecycle returns product registration stores when configured. Nil means +// the daemon is running in static-topology-only mode. Reading these stores +// must not be treated as assignment authority. +func (h *Host) Lifecycle() *LifecycleStores { return h.lifecycle } + // replicaSlotsFor returns the accepted-topology replica IDs for a // volume, or nil if the volume isn't in accepted topology. Used // by AssignmentService to fan-in per-(vol, rid) publisher diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go new file mode 100644 index 0000000000..70128abab6 --- /dev/null +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -0,0 +1,90 @@ +package master + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestMasterLifecycleStore_OptionalNilByDefault(t *testing.T) { + h := newTestMaster(t, "") + defer closeTestMaster(t, h) + if h.Lifecycle() != nil { + t.Fatal("Lifecycle() = non-nil without LifecycleStoreDir") + } +} + +func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + if stores == nil { + t.Fatal("Lifecycle() = nil with LifecycleStoreDir") + } + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }); err != nil { + t.Fatalf("create desired volume: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + Pools: []lifecycle.StoragePool{{ + PoolID: "pool-a", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register node: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "node-b", + Addr: "127.0.0.1:9102", + Pools: []lifecycle.StoragePool{{ + PoolID: "pool-b", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register second node: %v", err) + } + results := lifecycle.ReconcilePlacement(stores.Volumes.ListVolumes(), stores.Nodes.ListNodes(), stores.Placements) + if len(results) != 1 || !results[0].Applied { + t.Fatalf("reconcile results=%+v want one applied", results) + } + if _, ok := stores.Placements.GetPlacement("vol-a"); !ok { + t.Fatal("placement intent not written") + } + if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { + t.Fatal("lifecycle registration must not mint authority") + } +} + +func newTestMaster(t *testing.T, lifecycleDir string) *Host { + t.Helper() + h, err := New(Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: lifecycleDir, + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + return h +} + +func closeTestMaster(t *testing.T, h *Host) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := h.Close(ctx); err != nil { + t.Fatalf("close: %v", err) + } +} From b9df8b6e04701fc1c758ab29bc75d3bacf6ca071 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 21:00:06 -0700 Subject: [PATCH 06/10] G9D: pin lifecycle read-only and reconcile behavior --- .../core/host/master/lifecycle_snapshot.go | 24 +++++ .../core/host/master/lifecycle_test.go | 56 +++++++++++ .../core/lifecycle/reconciler_test.go | 93 +++++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 seaweed-block/core/host/master/lifecycle_snapshot.go diff --git a/seaweed-block/core/host/master/lifecycle_snapshot.go b/seaweed-block/core/host/master/lifecycle_snapshot.go new file mode 100644 index 0000000000..0566d797f5 --- /dev/null +++ b/seaweed-block/core/host/master/lifecycle_snapshot.go @@ -0,0 +1,24 @@ +package master + +import "github.com/seaweedfs/seaweed-block/core/lifecycle" + +// LifecycleSnapshot is a read-only product registration view. It is +// deliberately not authority-shaped. +type LifecycleSnapshot struct { + Volumes []lifecycle.VolumeRecord + Nodes []lifecycle.NodeRegistration + Placements []lifecycle.PlacementIntent +} + +// LifecycleSnapshot returns copies of lifecycle facts when configured. +func (h *Host) LifecycleSnapshot() (LifecycleSnapshot, bool) { + stores := h.Lifecycle() + if stores == nil { + return LifecycleSnapshot{}, false + } + return LifecycleSnapshot{ + Volumes: stores.Volumes.ListVolumes(), + Nodes: stores.Nodes.ListNodes(), + Placements: stores.Placements.ListPlacements(), + }, true +} diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index 70128abab6..f7aacf4eff 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -2,6 +2,10 @@ package master import ( "context" + "go/ast" + "go/parser" + "go/token" + "path/filepath" "testing" "time" @@ -64,6 +68,23 @@ func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { t.Fatal("lifecycle registration must not mint authority") } + snapshot, ok := h.LifecycleSnapshot() + if !ok { + t.Fatal("missing lifecycle snapshot") + } + if len(snapshot.Volumes) != 1 || len(snapshot.Nodes) != 2 || len(snapshot.Placements) != 1 { + t.Fatalf("snapshot counts got volumes=%d nodes=%d placements=%d", + len(snapshot.Volumes), len(snapshot.Nodes), len(snapshot.Placements)) + } +} + +func TestMasterLifecycleSnapshot_IsNotAuthorityShaped(t *testing.T) { + typ := mustParseStruct(t, "lifecycle_snapshot.go", "LifecycleSnapshot") + for _, forbidden := range []string{"Epoch", "EndpointVersion", "Assignment", "Ready", "Healthy", "Primary"} { + if _, ok := typ.Fields[forbidden]; ok { + t.Fatalf("LifecycleSnapshot must not carry %s", forbidden) + } + } } func newTestMaster(t *testing.T, lifecycleDir string) *Host { @@ -80,6 +101,41 @@ func newTestMaster(t *testing.T, lifecycleDir string) *Host { return h } +type parsedStruct struct { + Fields map[string]struct{} +} + +func mustParseStruct(t *testing.T, fileName, structName string) parsedStruct { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, filepath.Clean(fileName), nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", fileName, err) + } + var out parsedStruct + ast.Inspect(file, func(n ast.Node) bool { + typeSpec, ok := n.(*ast.TypeSpec) + if !ok || typeSpec.Name.Name != structName { + return true + } + st, ok := typeSpec.Type.(*ast.StructType) + if !ok { + t.Fatalf("%s is not a struct", structName) + } + out.Fields = make(map[string]struct{}) + for _, field := range st.Fields.List { + for _, name := range field.Names { + out.Fields[name.Name] = struct{}{} + } + } + return false + }) + if out.Fields == nil { + t.Fatalf("struct %s not found in %s", structName, fileName) + } + return out +} + func closeTestMaster(t *testing.T, h *Host) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/seaweed-block/core/lifecycle/reconciler_test.go b/seaweed-block/core/lifecycle/reconciler_test.go index 16c012460b..c2f2dc941d 100644 --- a/seaweed-block/core/lifecycle/reconciler_test.go +++ b/seaweed-block/core/lifecycle/reconciler_test.go @@ -2,6 +2,7 @@ package lifecycle import ( "errors" + "reflect" "testing" ) @@ -112,6 +113,98 @@ func TestReconcilePlacement_ResultIsNotAuthorityShaped(t *testing.T) { } } +func TestReconcilePlacement_IdempotentSameInputsProduceSameIntent(t *testing.T) { + volumes := []VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }}} + nodes := []NodeRegistration{ + nodeWithPool("node-a", "pool-a", 1<<30), + nodeWithPool("node-b", "pool-b", 1<<30), + } + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + first := ReconcilePlacement(volumes, nodes, store) + second := ReconcilePlacement(volumes, nodes, store) + if len(first) != 1 || len(second) != 1 || !first[0].Applied || !second[0].Applied { + t.Fatalf("unexpected results first=%+v second=%+v", first, second) + } + if !reflect.DeepEqual(first[0].Intent, second[0].Intent) { + t.Fatalf("same inputs changed intent:\nfirst %+v\nsecond %+v", first[0].Intent, second[0].Intent) + } + got, ok := store.GetPlacement("vol-a") + if !ok { + t.Fatal("missing persisted intent") + } + if !reflect.DeepEqual(got, first[0].Intent) { + t.Fatalf("persisted intent drifted:\ngot %+v\nwant %+v", got, first[0].Intent) + } +} + +func TestReconcilePlacement_DesiredRFChangeUpdatesExistingIntent(t *testing.T) { + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + nodes := []NodeRegistration{ + nodeWithPool("node-a", "pool-a", 1<<30), + nodeWithPool("node-b", "pool-b", 1<<30), + nodeWithPool("node-c", "pool-c", 1<<30), + } + first := ReconcilePlacement([]VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }}}, nodes, store) + if len(first) != 1 || !first[0].Applied { + t.Fatalf("first reconcile failed: %+v", first) + } + second := ReconcilePlacement([]VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 3, + }}}, nodes, store) + if len(second) != 1 || !second[0].Applied { + t.Fatalf("second reconcile failed: %+v", second) + } + got, ok := store.GetPlacement("vol-a") + if !ok { + t.Fatal("missing placement") + } + if got.DesiredRF != 3 || len(got.Slots) != 3 { + t.Fatalf("RF change did not update intent: %+v", got) + } +} + +func TestReconcilePlacement_ExistingIntentSameInputsOverwritesSameValue(t *testing.T) { + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + volumes := []VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }}} + nodes := []NodeRegistration{nodeWithPool("node-a", "pool-a", 1<<30)} + first := ReconcilePlacement(volumes, nodes, store) + if len(first) != 1 || !first[0].Applied { + t.Fatalf("first reconcile failed: %+v", first) + } + before, _ := store.GetPlacement("vol-a") + again := ReconcilePlacement(volumes, nodes, store) + if len(again) != 1 || !again[0].Applied { + t.Fatalf("second reconcile failed: %+v", again) + } + after, _ := store.GetPlacement("vol-a") + if !reflect.DeepEqual(before, after) { + t.Fatalf("existing intent changed under same inputs:\nbefore %+v\nafter %+v", before, after) + } +} + func nodeWithPool(serverID, poolID string, freeBytes uint64) NodeRegistration { return NodeRegistration{ ServerID: serverID, From 4add465b653b12998632d946a43a5f82d458a57f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 21:10:28 -0700 Subject: [PATCH 07/10] G9F: verify placement intent against node observation --- .../core/lifecycle/verified_placement.go | 98 ++++++++++++++ .../core/lifecycle/verified_placement_test.go | 122 ++++++++++++++++++ 2 files changed, 220 insertions(+) create mode 100644 seaweed-block/core/lifecycle/verified_placement.go create mode 100644 seaweed-block/core/lifecycle/verified_placement_test.go diff --git a/seaweed-block/core/lifecycle/verified_placement.go b/seaweed-block/core/lifecycle/verified_placement.go new file mode 100644 index 0000000000..0e6436622b --- /dev/null +++ b/seaweed-block/core/lifecycle/verified_placement.go @@ -0,0 +1,98 @@ +package lifecycle + +import ( + "time" +) + +const ( + VerifiedByNodeRegistration = "node_registration" + + VerifyReasonOK = "ok" + VerifyReasonMissingObservation = "missing_observation" + VerifyReasonStaleObservation = "stale_observation" + VerifyReasonMissingAddress = "missing_address" + VerifyReasonReplicaMismatch = "replica_mismatch" + VerifyReasonInvalidIntent = "invalid_intent" +) + +// VerificationConfig controls freshness evaluation for placement intent +// verification. +type VerificationConfig struct { + Now time.Time + FreshnessWindow time.Duration +} + +// VerifiedPlacement is a non-authority controller bridge output. It proves +// that placement intent intersects with fresh observation; it is still not an +// assignment and not readiness. +type VerifiedPlacement struct { + VolumeID string + Slots []VerifiedPlacementSlot + Verified bool + Reason string +} + +// VerifiedPlacementSlot is a fresh, address-bearing placement slot. +type VerifiedPlacementSlot struct { + ServerID string + PoolID string + ReplicaID string + Source string + DataAddr string + CtrlAddr string + VerifiedBy string +} + +// VerifyPlacementIntent intersects placement intent with fresh node +// registration facts. Missing or stale observation fails closed. +func VerifyPlacementIntent(intent PlacementIntent, nodes []NodeRegistration, cfg VerificationConfig) VerifiedPlacement { + out := VerifiedPlacement{ + VolumeID: intent.VolumeID, + Reason: VerifyReasonOK, + } + if err := validatePlacementIntent(intent); err != nil { + out.Reason = VerifyReasonInvalidIntent + return out + } + if cfg.Now.IsZero() { + cfg.Now = time.Now().UTC() + } + nodeByID := make(map[string]NodeRegistration, len(nodes)) + for _, node := range nodes { + nodeByID[node.ServerID] = node + } + for _, slot := range intent.Slots { + node, ok := nodeByID[slot.ServerID] + if !ok { + out.Reason = VerifyReasonMissingObservation + return out + } + if !node.SeenAt.IsZero() && cfg.FreshnessWindow > 0 && cfg.Now.Sub(node.SeenAt) > cfg.FreshnessWindow { + out.Reason = VerifyReasonStaleObservation + return out + } + if node.Addr == "" { + out.Reason = VerifyReasonMissingAddress + return out + } + verified := VerifiedPlacementSlot{ + ServerID: slot.ServerID, + PoolID: slot.PoolID, + ReplicaID: slot.ReplicaID, + Source: slot.Source, + DataAddr: node.Addr, + CtrlAddr: node.Addr, + VerifiedBy: VerifiedByNodeRegistration, + } + if slot.Source == PlacementSourceExistingReplica { + replica, ok := matchingReplica(intent.VolumeID, node.Replicas) + if !ok || replica.ReplicaID != slot.ReplicaID { + out.Reason = VerifyReasonReplicaMismatch + return out + } + } + out.Slots = append(out.Slots, verified) + } + out.Verified = true + return out +} diff --git a/seaweed-block/core/lifecycle/verified_placement_test.go b/seaweed-block/core/lifecycle/verified_placement_test.go new file mode 100644 index 0000000000..cbf49172e4 --- /dev/null +++ b/seaweed-block/core/lifecycle/verified_placement_test.go @@ -0,0 +1,122 @@ +package lifecycle + +import ( + "testing" + "time" +) + +func TestG9F_PlacementIntentWithoutObservation_DoesNotVerify(t *testing.T) { + intent := PlacementIntent{ + VolumeID: "vol-a", + DesiredRF: 1, + Slots: []PlacementSlotIntent{{ + ServerID: "node-a", + PoolID: "pool-a", + Source: PlacementSourceBlankPool, + }}, + } + got := VerifyPlacementIntent(intent, nil, VerificationConfig{Now: time.Now(), FreshnessWindow: time.Second}) + if got.Verified { + t.Fatalf("placement intent without observation verified: %+v", got) + } + if got.Reason != VerifyReasonMissingObservation { + t.Fatalf("reason=%q want %q", got.Reason, VerifyReasonMissingObservation) + } +} + +func TestG9F_PlacementIntentWithStaleObservation_DoesNotVerify(t *testing.T) { + now := time.Date(2026, 5, 2, 12, 0, 0, 0, time.UTC) + intent := PlacementIntent{ + VolumeID: "vol-a", + DesiredRF: 1, + Slots: []PlacementSlotIntent{{ + ServerID: "node-a", + PoolID: "pool-a", + Source: PlacementSourceBlankPool, + }}, + } + got := VerifyPlacementIntent(intent, []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + SeenAt: now.Add(-2 * time.Minute), + }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) + if got.Verified { + t.Fatalf("stale observation verified: %+v", got) + } + if got.Reason != VerifyReasonStaleObservation { + t.Fatalf("reason=%q want %q", got.Reason, VerifyReasonStaleObservation) + } +} + +func TestG9F_VerifiedPlacement_IsNotAuthorityShaped(t *testing.T) { + for _, name := range []string{"VerifiedPlacement", "VerifiedPlacementSlot"} { + typ := mustParseStruct(t, "verified_placement.go", name) + for _, forbidden := range []string{"Epoch", "EndpointVersion", "Assignment", "Ready", "Healthy", "Primary"} { + if _, ok := typ.Fields[forbidden]; ok { + t.Fatalf("%s must not carry %s", name, forbidden) + } + } + } +} + +func TestG9F_BlankPoolIntentWithFreshObservation_VerifiesCreateNeededSlot(t *testing.T) { + now := time.Date(2026, 5, 2, 12, 0, 0, 0, time.UTC) + intent := PlacementIntent{ + VolumeID: "vol-a", + DesiredRF: 1, + Slots: []PlacementSlotIntent{{ + ServerID: "node-a", + PoolID: "pool-a", + Source: PlacementSourceBlankPool, + }}, + } + got := VerifyPlacementIntent(intent, []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + SeenAt: now, + }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) + if !got.Verified { + t.Fatalf("fresh blank-pool intent did not verify: %+v", got) + } + if len(got.Slots) != 1 { + t.Fatalf("slot count=%d want 1", len(got.Slots)) + } + slot := got.Slots[0] + if slot.Source != PlacementSourceBlankPool || slot.PoolID != "pool-a" || slot.ReplicaID != "" { + t.Fatalf("verified blank slot mismatch: %+v", slot) + } + if slot.DataAddr == "" || slot.CtrlAddr == "" { + t.Fatalf("verified slot missing addresses: %+v", slot) + } +} + +func TestG9F_ExistingReplicaIntentWithWrongInventory_DoesNotVerify(t *testing.T) { + now := time.Date(2026, 5, 2, 12, 0, 0, 0, time.UTC) + intent := PlacementIntent{ + VolumeID: "vol-a", + DesiredRF: 1, + Slots: []PlacementSlotIntent{{ + ServerID: "node-a", + ReplicaID: "r2", + Source: PlacementSourceExistingReplica, + }}, + } + got := VerifyPlacementIntent(intent, []NodeRegistration{{ + ServerID: "node-a", + Addr: "127.0.0.1:9101", + SeenAt: now, + Replicas: []ReplicaInventory{{ + VolumeID: "vol-a", + ReplicaID: "r3", + StoreUUID: "store-1", + SizeBytes: 1 << 20, + State: "existing", + }}, + }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) + if got.Verified { + t.Fatalf("wrong replica inventory verified: %+v", got) + } + if got.Reason != VerifyReasonReplicaMismatch { + t.Fatalf("reason=%q want %q", got.Reason, VerifyReasonReplicaMismatch) + } +} From 0b1f278083954e8db5ec118587e164ffe03e8c56 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 21:15:13 -0700 Subject: [PATCH 08/10] G9F: expose verified placement in lifecycle snapshot --- .../core/host/master/lifecycle_snapshot.go | 30 ++++++++++---- .../core/host/master/lifecycle_test.go | 41 +++++++++++++++++++ 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/host/master/lifecycle_snapshot.go b/seaweed-block/core/host/master/lifecycle_snapshot.go index 0566d797f5..b2b321dd59 100644 --- a/seaweed-block/core/host/master/lifecycle_snapshot.go +++ b/seaweed-block/core/host/master/lifecycle_snapshot.go @@ -1,13 +1,18 @@ package master -import "github.com/seaweedfs/seaweed-block/core/lifecycle" +import ( + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) // LifecycleSnapshot is a read-only product registration view. It is // deliberately not authority-shaped. type LifecycleSnapshot struct { - Volumes []lifecycle.VolumeRecord - Nodes []lifecycle.NodeRegistration - Placements []lifecycle.PlacementIntent + Volumes []lifecycle.VolumeRecord + Nodes []lifecycle.NodeRegistration + Placements []lifecycle.PlacementIntent + VerifiedPlacements []lifecycle.VerifiedPlacement } // LifecycleSnapshot returns copies of lifecycle facts when configured. @@ -16,9 +21,20 @@ func (h *Host) LifecycleSnapshot() (LifecycleSnapshot, bool) { if stores == nil { return LifecycleSnapshot{}, false } + nodes := stores.Nodes.ListNodes() + placements := stores.Placements.ListPlacements() + verified := make([]lifecycle.VerifiedPlacement, 0, len(placements)) + cfg := lifecycle.VerificationConfig{ + Now: time.Now().UTC(), + FreshnessWindow: h.cfg.Freshness.FreshnessWindow, + } + for _, placement := range placements { + verified = append(verified, lifecycle.VerifyPlacementIntent(placement, nodes, cfg)) + } return LifecycleSnapshot{ - Volumes: stores.Volumes.ListVolumes(), - Nodes: stores.Nodes.ListNodes(), - Placements: stores.Placements.ListPlacements(), + Volumes: stores.Volumes.ListVolumes(), + Nodes: nodes, + Placements: placements, + VerifiedPlacements: verified, }, true } diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index f7aacf4eff..06b424448d 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -76,6 +76,12 @@ func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing t.Fatalf("snapshot counts got volumes=%d nodes=%d placements=%d", len(snapshot.Volumes), len(snapshot.Nodes), len(snapshot.Placements)) } + if len(snapshot.VerifiedPlacements) != 1 || !snapshot.VerifiedPlacements[0].Verified { + t.Fatalf("verified placements=%+v want one verified", snapshot.VerifiedPlacements) + } + if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { + t.Fatal("verified lifecycle snapshot must not mint authority") + } } func TestMasterLifecycleSnapshot_IsNotAuthorityShaped(t *testing.T) { @@ -87,6 +93,41 @@ func TestMasterLifecycleSnapshot_IsNotAuthorityShaped(t *testing.T) { } } +func TestMasterLifecycleSnapshot_PlacementWithoutNodeObservationIsNotVerified(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{ + VolumeID: "vol-a", + ServerID: "node-a", + PoolID: "pool-a", + Source: lifecycle.PlacementSourceBlankPool, + }}, + }); err != nil { + t.Fatalf("apply placement: %v", err) + } + snapshot, ok := h.LifecycleSnapshot() + if !ok { + t.Fatal("missing lifecycle snapshot") + } + if len(snapshot.VerifiedPlacements) != 1 { + t.Fatalf("verified count=%d want 1", len(snapshot.VerifiedPlacements)) + } + got := snapshot.VerifiedPlacements[0] + if got.Verified { + t.Fatalf("placement without node observation verified: %+v", got) + } + if got.Reason != lifecycle.VerifyReasonMissingObservation { + t.Fatalf("reason=%q want %q", got.Reason, lifecycle.VerifyReasonMissingObservation) + } + if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { + t.Fatal("unverified placement must not mint authority") + } +} + func newTestMaster(t *testing.T, lifecycleDir string) *Host { t.Helper() h, err := New(Config{ From 8d77ca5b569359e9d2a20bc12eaf02fda472e2e1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 21:33:06 -0700 Subject: [PATCH 09/10] G9F: split node data and control addresses --- .../core/host/master/lifecycle_test.go | 6 ++-- .../core/lifecycle/node_inventory.go | 12 ++++--- .../core/lifecycle/verified_placement.go | 14 ++++++-- .../core/lifecycle/verified_placement_test.go | 36 +++++++++++++++++-- 4 files changed, 56 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index 06b424448d..48798e7d5a 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -36,7 +36,8 @@ func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing } if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ ServerID: "node-a", - Addr: "127.0.0.1:9101", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", Pools: []lifecycle.StoragePool{{ PoolID: "pool-a", TotalBytes: 1 << 30, @@ -48,7 +49,8 @@ func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing } if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ ServerID: "node-b", - Addr: "127.0.0.1:9102", + DataAddr: "127.0.0.1:9202", + CtrlAddr: "127.0.0.1:9102", Pools: []lifecycle.StoragePool{{ PoolID: "pool-b", TotalBytes: 1 << 30, diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index d290c97ec9..c6209b19a4 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -41,8 +41,12 @@ type ReplicaInventory struct { // registration or heartbeat ingestion. It deliberately has no authority // fields. type NodeRegistration struct { - ServerID string `json:"server_id"` - Addr string `json:"addr"` + ServerID string `json:"server_id"` + // Addr is legacy node-level address. DataAddr/CtrlAddr are the + // explicit block data/control endpoints used by G9F verification. + Addr string `json:"addr,omitempty"` + DataAddr string `json:"data_addr,omitempty"` + CtrlAddr string `json:"ctrl_addr,omitempty"` Labels map[string]string `json:"labels,omitempty"` Pools []StoragePool `json:"pools,omitempty"` Replicas []ReplicaInventory `json:"replicas,omitempty"` @@ -198,8 +202,8 @@ func validateNodeRegistration(reg NodeRegistration) error { if err := validateServerID(reg.ServerID); err != nil { return err } - if reg.Addr == "" { - return fmt.Errorf("%w: empty addr", ErrInvalidNodeRegistration) + if reg.Addr == "" && (reg.DataAddr == "" || reg.CtrlAddr == "") { + return fmt.Errorf("%w: empty address; provide addr or data_addr+ctrl_addr", ErrInvalidNodeRegistration) } for _, pool := range reg.Pools { if pool.PoolID == "" { diff --git a/seaweed-block/core/lifecycle/verified_placement.go b/seaweed-block/core/lifecycle/verified_placement.go index 0e6436622b..287fc9ca1f 100644 --- a/seaweed-block/core/lifecycle/verified_placement.go +++ b/seaweed-block/core/lifecycle/verified_placement.go @@ -71,7 +71,8 @@ func VerifyPlacementIntent(intent PlacementIntent, nodes []NodeRegistration, cfg out.Reason = VerifyReasonStaleObservation return out } - if node.Addr == "" { + dataAddr, ctrlAddr := nodePlacementAddrs(node) + if dataAddr == "" || ctrlAddr == "" { out.Reason = VerifyReasonMissingAddress return out } @@ -80,8 +81,8 @@ func VerifyPlacementIntent(intent PlacementIntent, nodes []NodeRegistration, cfg PoolID: slot.PoolID, ReplicaID: slot.ReplicaID, Source: slot.Source, - DataAddr: node.Addr, - CtrlAddr: node.Addr, + DataAddr: dataAddr, + CtrlAddr: ctrlAddr, VerifiedBy: VerifiedByNodeRegistration, } if slot.Source == PlacementSourceExistingReplica { @@ -96,3 +97,10 @@ func VerifyPlacementIntent(intent PlacementIntent, nodes []NodeRegistration, cfg out.Verified = true return out } + +func nodePlacementAddrs(node NodeRegistration) (dataAddr, ctrlAddr string) { + if node.DataAddr != "" || node.CtrlAddr != "" { + return node.DataAddr, node.CtrlAddr + } + return node.Addr, node.Addr +} diff --git a/seaweed-block/core/lifecycle/verified_placement_test.go b/seaweed-block/core/lifecycle/verified_placement_test.go index cbf49172e4..ac4413d806 100644 --- a/seaweed-block/core/lifecycle/verified_placement_test.go +++ b/seaweed-block/core/lifecycle/verified_placement_test.go @@ -37,7 +37,8 @@ func TestG9F_PlacementIntentWithStaleObservation_DoesNotVerify(t *testing.T) { } got := VerifyPlacementIntent(intent, []NodeRegistration{{ ServerID: "node-a", - Addr: "127.0.0.1:9101", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", SeenAt: now.Add(-2 * time.Minute), }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) if got.Verified { @@ -72,7 +73,8 @@ func TestG9F_BlankPoolIntentWithFreshObservation_VerifiesCreateNeededSlot(t *tes } got := VerifyPlacementIntent(intent, []NodeRegistration{{ ServerID: "node-a", - Addr: "127.0.0.1:9101", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", SeenAt: now, }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) if !got.Verified { @@ -88,6 +90,33 @@ func TestG9F_BlankPoolIntentWithFreshObservation_VerifiesCreateNeededSlot(t *tes if slot.DataAddr == "" || slot.CtrlAddr == "" { t.Fatalf("verified slot missing addresses: %+v", slot) } + if slot.DataAddr != "127.0.0.1:9201" || slot.CtrlAddr != "127.0.0.1:9101" { + t.Fatalf("verified slot addresses=%s/%s want explicit data/control addrs", slot.DataAddr, slot.CtrlAddr) + } +} + +func TestG9F_FreshObservationMissingControlAddress_DoesNotVerify(t *testing.T) { + now := time.Date(2026, 5, 2, 12, 0, 0, 0, time.UTC) + intent := PlacementIntent{ + VolumeID: "vol-a", + DesiredRF: 1, + Slots: []PlacementSlotIntent{{ + ServerID: "node-a", + PoolID: "pool-a", + Source: PlacementSourceBlankPool, + }}, + } + got := VerifyPlacementIntent(intent, []NodeRegistration{{ + ServerID: "node-a", + DataAddr: "127.0.0.1:9201", + SeenAt: now, + }}, VerificationConfig{Now: now, FreshnessWindow: time.Minute}) + if got.Verified { + t.Fatalf("missing control address verified: %+v", got) + } + if got.Reason != VerifyReasonMissingAddress { + t.Fatalf("reason=%q want %q", got.Reason, VerifyReasonMissingAddress) + } } func TestG9F_ExistingReplicaIntentWithWrongInventory_DoesNotVerify(t *testing.T) { @@ -103,7 +132,8 @@ func TestG9F_ExistingReplicaIntentWithWrongInventory_DoesNotVerify(t *testing.T) } got := VerifyPlacementIntent(intent, []NodeRegistration{{ ServerID: "node-a", - Addr: "127.0.0.1:9101", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", SeenAt: now, Replicas: []ReplicaInventory{{ VolumeID: "vol-a", From 3102dd80aeb89bd75e6ca32184669522af913959 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 21:38:03 -0700 Subject: [PATCH 10/10] G9F: verify lifecycle placements from observation store --- .../core/host/master/lifecycle_snapshot.go | 70 ++++++++++++++++--- .../core/host/master/lifecycle_test.go | 44 +++++++++++- 2 files changed, 105 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/host/master/lifecycle_snapshot.go b/seaweed-block/core/host/master/lifecycle_snapshot.go index b2b321dd59..b21388fb6a 100644 --- a/seaweed-block/core/host/master/lifecycle_snapshot.go +++ b/seaweed-block/core/host/master/lifecycle_snapshot.go @@ -3,6 +3,7 @@ package master import ( "time" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" ) @@ -23,14 +24,7 @@ func (h *Host) LifecycleSnapshot() (LifecycleSnapshot, bool) { } nodes := stores.Nodes.ListNodes() placements := stores.Placements.ListPlacements() - verified := make([]lifecycle.VerifiedPlacement, 0, len(placements)) - cfg := lifecycle.VerificationConfig{ - Now: time.Now().UTC(), - FreshnessWindow: h.cfg.Freshness.FreshnessWindow, - } - for _, placement := range placements { - verified = append(verified, lifecycle.VerifyPlacementIntent(placement, nodes, cfg)) - } + verified := h.verifyPlacements(placements, nodes) return LifecycleSnapshot{ Volumes: stores.Volumes.ListVolumes(), Nodes: nodes, @@ -38,3 +32,63 @@ func (h *Host) LifecycleSnapshot() (LifecycleSnapshot, bool) { VerifiedPlacements: verified, }, true } + +func (h *Host) verifyPlacements(placements []lifecycle.PlacementIntent, nodes []lifecycle.NodeRegistration) []lifecycle.VerifiedPlacement { + verified := make([]lifecycle.VerifiedPlacement, 0, len(placements)) + var obsStore *authority.ObservationStore + if h.obs != nil { + obsStore = h.obs.Store() + } + if obsStore != nil { + for _, placement := range placements { + verified = append(verified, verifyPlacementWithObservationStore(placement, obsStore)) + } + return verified + } + cfg := lifecycle.VerificationConfig{ + Now: time.Now().UTC(), + FreshnessWindow: h.cfg.Freshness.FreshnessWindow, + } + for _, placement := range placements { + verified = append(verified, lifecycle.VerifyPlacementIntent(placement, nodes, cfg)) + } + return verified +} + +func verifyPlacementWithObservationStore(intent lifecycle.PlacementIntent, obsStore *authority.ObservationStore) lifecycle.VerifiedPlacement { + out := lifecycle.VerifiedPlacement{ + VolumeID: intent.VolumeID, + Reason: lifecycle.VerifyReasonOK, + } + if obsStore == nil { + out.Reason = lifecycle.VerifyReasonMissingObservation + return out + } + for _, slot := range intent.Slots { + if slot.Source == lifecycle.PlacementSourceBlankPool { + // Blank pool candidates have no replica slot yet. They can + // only be verified by node inventory in this slice. + out.Reason = lifecycle.VerifyReasonMissingObservation + return out + } + fact, ok := obsStore.SlotFact(intent.VolumeID, slot.ReplicaID) + if !ok { + out.Reason = lifecycle.VerifyReasonMissingObservation + return out + } + if fact.DataAddr == "" || fact.CtrlAddr == "" { + out.Reason = lifecycle.VerifyReasonMissingAddress + return out + } + out.Slots = append(out.Slots, lifecycle.VerifiedPlacementSlot{ + ServerID: slot.ServerID, + ReplicaID: slot.ReplicaID, + Source: slot.Source, + DataAddr: fact.DataAddr, + CtrlAddr: fact.CtrlAddr, + VerifiedBy: "observation_store", + }) + } + out.Verified = true + return out +} diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index 48798e7d5a..4cbbc29a0d 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" ) @@ -78,11 +79,52 @@ func TestMasterLifecycleStore_OpensRegistrationStoresWithoutAuthority(t *testing t.Fatalf("snapshot counts got volumes=%d nodes=%d placements=%d", len(snapshot.Volumes), len(snapshot.Nodes), len(snapshot.Placements)) } + if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { + t.Fatal("verified lifecycle snapshot must not mint authority") + } +} + +func TestMasterLifecycleSnapshot_ExistingReplicaVerifiesFromObservationStore(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{ + VolumeID: "vol-a", + ServerID: "node-a", + ReplicaID: "r2", + Source: lifecycle.PlacementSourceExistingReplica, + }}, + }); err != nil { + t.Fatalf("apply placement: %v", err) + } + if err := h.ObservationHost().Ingest(authority.Observation{ + ServerID: "node-a", + ObservedAt: time.Now().UTC(), + Slots: []authority.SlotFact{{ + VolumeID: "vol-a", + ReplicaID: "r2", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", + }}, + }); err != nil { + t.Fatalf("ingest observation: %v", err) + } + snapshot, ok := h.LifecycleSnapshot() + if !ok { + t.Fatal("missing lifecycle snapshot") + } if len(snapshot.VerifiedPlacements) != 1 || !snapshot.VerifiedPlacements[0].Verified { t.Fatalf("verified placements=%+v want one verified", snapshot.VerifiedPlacements) } + slot := snapshot.VerifiedPlacements[0].Slots[0] + if slot.DataAddr != "127.0.0.1:9201" || slot.CtrlAddr != "127.0.0.1:9101" { + t.Fatalf("slot addrs=%s/%s want observation addrs", slot.DataAddr, slot.CtrlAddr) + } if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok { - t.Fatal("verified lifecycle snapshot must not mint authority") + t.Fatal("observation-backed verified placement must not mint authority") } }