diff --git a/seaweed-block/cmd/blockvolume/workspace_lease.go b/seaweed-block/cmd/blockvolume/workspace_lease.go index b0724b8288..4362b51e82 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease.go @@ -60,13 +60,9 @@ func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (st if err != nil { return 0, err } - head, err := remote.GetHead(ctx) + head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder) if err != nil { return 0, err } - proof := head.DetachedBy - if head.Gen == 0 || head.Epoch != id.Epoch || head.Holder != holder || head.State != storage.ChunkHeadDetached || proof == nil || proof.Gen != head.Gen || proof.Epoch != head.Epoch || proof.Holder != head.Holder { - return 0, fmt.Errorf("workspace shutdown has no matching stored detached HEAD") - } return head.Gen, nil } diff --git a/seaweed-block/cmd/blockvolume/workspace_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_proof_test.go new file mode 100644 index 0000000000..3ecf940654 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_proof_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "errors" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +type workspaceProofRemote struct { + storage.ChunkRemote + head storage.ChunkHead + err error + reads int +} + +func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) { + r.reads++ + return r.head, r.err +} + +func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) { + for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "missing-proof", "proof-gen", "proof-epoch", "proof-holder", "foreign-holder", "foreign-epoch", "zero-gen", "read-error"} { + t.Run(name, func(t *testing.T) { + h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}} + id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2} + holder := "s/r" + r := &workspaceProofRemote{head: h} + switch name { + case "zero-epoch": + id.Epoch = 0 + r.head.Epoch = 0 + r.head.DetachedBy.Epoch = 0 + case "empty-holder": + holder = "" + r.head.Holder = "" + r.head.DetachedBy.Holder = "" + case "active": + r.head.State = storage.ChunkHeadActive + case "missing-proof": + r.head.DetachedBy = nil + case "zero-gen": + r.head.Gen = 0 + r.head.DetachedBy.Gen = 0 + case "proof-epoch": + r.head.DetachedBy.Epoch = 1 + case "proof-holder": + r.head.DetachedBy.Holder = "other/r" + case "foreign-epoch": + r.head.Epoch = 1 + case "proof-gen": + r.head.DetachedBy.Gen = 6 + case "foreign-holder": + r.head.Holder = "other/r" + case "read-error": + r.err = errors.New("HEAD answer lost") + } + gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder) + if name == "valid" { + if err != nil || gen != 7 || r.reads != 1 { + t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err) + } + } else if err == nil || gen != 0 { + t.Fatalf("unproven ACK gen%d err%v", gen, err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/one_process_per_volume_test.go b/seaweed-block/core/frontend/durable/one_process_per_volume_test.go index 55af4a8d40..98b3329fe1 100644 --- a/seaweed-block/core/frontend/durable/one_process_per_volume_test.go +++ b/seaweed-block/core/frontend/durable/one_process_per_volume_test.go @@ -98,6 +98,25 @@ func TestHostVolumeLockDirectoryCreatedOrRefused(t *testing.T) { } } +// A lock path that exists but is not a directory refuses, as before the +// lock directory was laid out by the provider. +func TestHostVolumeLockRefusesNonDirectoryLockPath(t *testing.T) { + locks := filepath.Join(t.TempDir(), "locks") + if err := os.WriteFile(locks, nil, 0o600); err != nil { + t.Fatal(err) + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, + HostVolumeLock: true, VolumeLockDirTestOnly: locks, + }, v1View()) + if err == nil { + _ = p.Close() + } + if !errors.Is(err, durable.ErrVolumeLockDirUnavailable) { + t.Fatalf("a regular file as the lock directory was accepted: %v", err) + } +} + // A lock file this process cannot write (one another user created, as the // root ublk unit does) is still taken: the lock opens it read-only. func TestHostVolumeLockTakesReadOnlyLockFile(t *testing.T) { diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index eb391db3d8..e99ada32b2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -405,7 +405,7 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.VolumeLockDirTestOnly == "" { cfg.VolumeLockDirTestOnly = HostVolumeLockDir } - if err := os.MkdirAll(cfg.VolumeLockDirTestOnly, 0o700); err != nil { + if err := makeVolumeLockDir(cfg.VolumeLockDirTestOnly); err != nil { return nil, fmt.Errorf("%w %s: %w; %s", ErrVolumeLockDirUnavailable, cfg.VolumeLockDirTestOnly, err, volumeLockCure) } } @@ -560,7 +560,40 @@ var ErrVolumeLockDirUnavailable = errors.New("durable: host volume lock director // volumeLockCure names the operator's cure. A directory or lock file a root // process created is root-owned: an unprivileged unit then cannot use it. -const volumeLockCure = "install the tmpfiles.d entry (deploy/systemd/sw-block.tmpfiles.conf), or chown the directory and its lock files to this process's user" +const volumeLockCure = "install the tmpfiles.d entry (deploy/systemd/sw-block.tmpfiles.conf), or make its parent directory traversable (0755) and chown the directory and its lock files to this process's user" + +// makeVolumeLockDir lays out a missing lock directory as the tmpfiles.d +// entry does: its parent 0755 (traversable by the unit's user even when root +// created it) and the directory itself 0700. Only a directory this call +// creates is chmod'ed (the umask cannot narrow it); one that exists, or that +// another process creates meanwhile, keeps its mode. An existing lock path +// that is not a directory refuses. +func makeVolumeLockDir(dir string) error { + parent := filepath.Dir(dir) + if err := os.MkdirAll(filepath.Dir(parent), 0o755); err != nil { + return err + } + if err := os.Mkdir(parent, 0o755); err == nil { + if err := os.Chmod(parent, 0o755); err != nil { + return err + } + } else if !errors.Is(err, os.ErrExist) { + return err + } + if err := os.Mkdir(dir, 0o700); err == nil { + return os.Chmod(dir, 0o700) + } else if !errors.Is(err, os.ErrExist) { + return err + } + fi, err := os.Lstat(dir) + if err != nil { + return err + } + if !fi.IsDir() { + return fmt.Errorf("%s exists and is not a directory", dir) + } + return nil +} // lockVolumeOnHost takes the volume's host lock (nil without // HostVolumeLock). A second live process for the volume on this host gets diff --git a/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go b/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go new file mode 100644 index 0000000000..ba85f454d9 --- /dev/null +++ b/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go @@ -0,0 +1,88 @@ +//go:build unix + +package durable_test + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// V1-SPEC r2.45 (1), as the tmpfiles.d entry lays it out: a lock directory +// the provider creates gets a traversable parent (0755) and is itself 0700, +// whatever the umask. A 0700 parent created by root would keep the unit's +// user out even after the locks directory is chowned to it. +func TestHostVolumeLockCreatesParent0755AndLocks0700(t *testing.T) { + old := syscall.Umask(0o077) // a strict umask must not narrow the parent + defer syscall.Umask(old) + parent := filepath.Join(t.TempDir(), "sw-block") + locks := filepath.Join(parent, "locks") + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, + HostVolumeLock: true, VolumeLockDirTestOnly: locks, + }, v1View()) + if err != nil { + t.Fatal(err) + } + _ = p.Close() + for path, want := range map[string]os.FileMode{parent: 0o755, locks: 0o700} { + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if got := fi.Mode().Perm(); got != want { + t.Fatalf("%s created %v, want %v", path, got, want) + } + } +} + +// newLockProvider opens a provider whose host lock directory is locks. +func newLockProvider(t *testing.T, locks string) { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, + HostVolumeLock: true, VolumeLockDirTestOnly: locks, + }, v1View()) + if err != nil { + t.Fatal(err) + } + _ = p.Close() +} + +func wantPerm(t *testing.T, path string, want os.FileMode) { + t.Helper() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if got := fi.Mode().Perm(); got != want { + t.Fatalf("%s is %v, want %v", path, got, want) + } +} + +// Directories the provider did not create keep their modes: an existing +// parent with a missing lock directory, and both existing. +func TestHostVolumeLockKeepsExistingDirectoryModes(t *testing.T) { + parent := filepath.Join(t.TempDir(), "sw-block") + if err := os.Mkdir(parent, 0o711); err != nil { + t.Fatal(err) + } + if err := os.Chmod(parent, 0o711); err != nil { + t.Fatal(err) + } + locks := filepath.Join(parent, "locks") + newLockProvider(t, locks) + wantPerm(t, parent, 0o711) + wantPerm(t, locks, 0o700) + + if err := os.Chmod(locks, 0o750); err != nil { + t.Fatal(err) + } + newLockProvider(t, locks) + wantPerm(t, parent, 0o711) + wantPerm(t, locks, 0o750) +} + diff --git a/seaweed-block/core/host/master/server_host_identity.go b/seaweed-block/core/host/master/server_host_identity.go index 0ed05e436e..d3ab7afa29 100644 --- a/seaweed-block/core/host/master/server_host_identity.go +++ b/seaweed-block/core/host/master/server_host_identity.go @@ -54,7 +54,7 @@ func (h *Host) refuseServerIDFromOtherHost(r *control.HeartbeatReport) error { for _, s := range r.Slots { for _, a := range []string{s.DataAddr, s.CtrlAddr} { if a != "" && !hosts[addrHost(a)] { - return fmt.Errorf("heartbeat: server id %s is registered on host %s; refused from %s (volume %s replica %s): one server id names one host", + return fmt.Errorf("heartbeat: server id %s is registered on host %s but advertises %s (volume %s replica %s): advertise the registered address, or register the node by the address it uses, in the cluster spec", r.ServerId, named, addrHost(a), s.VolumeId, s.ReplicaId) } } @@ -85,7 +85,7 @@ func (h *Host) refuseWorkspaceHolderHost(ctx context.Context, rpc, server string if ph == "" { ph = "an unknown peer" } - err = fmt.Errorf("%s: server id %s is registered on host %s; refused from %s: one server id names one host", rpc, server, named, ph) + err = fmt.Errorf("%s: server id %s is registered on host %s but connects from %s: register the node by the address it connects from (not loopback) in the cluster spec", rpc, server, named, ph) } if err != nil { h.log.Print(err) diff --git a/seaweed-block/core/host/master/server_host_identity_test.go b/seaweed-block/core/host/master/server_host_identity_test.go index 645103f1a2..1067bda980 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -141,10 +141,17 @@ func TestServerIDRefusedFromAHostOtherThanItsRegisteredOne(t *testing.T) { if err := r.heartbeatFrom("node-a", "127.0.0.1"); err != nil { t.Fatalf("heartbeat from node-a's registered host refused: %v", err) } - err := r.heartbeatFrom("node-a", "127.0.0.2") + // The peer is the registered host; only the advertised slot address is wrong. + obs := control.NewObservationServiceClient(r.dialFrom(t, "127.0.0.1")) + _, err := obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "hb-node-a", ReplicaId: "r-node-a", DataAddr: "127.0.0.2:19611", CtrlAddr: "127.0.0.2:19612"}}}) if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1") { t.Fatalf("same --server-id from a second host: %v, want FailedPrecondition naming the registered host", err) } + want := "registered on host 127.0.0.1 but advertises 127.0.0.2 (volume hb-node-a replica r-node-a): advertise the registered address, or register the node by the address it uses, in the cluster spec" + if !strings.Contains(status.Convert(err).Message(), want) { + t.Fatalf("heartbeat refusal lacks the cure or slot detail: %v", err) + } if slot, ok := r.m.ObservationHost().Store().SlotFactOnServer("node-a", "hb-node-a", "r-node-a"); !ok || !strings.HasPrefix(slot.DataAddr, "127.0.0.1:") { t.Fatalf("refused heartbeat reached the observations: %+v ok=%v", slot, ok) } @@ -241,9 +248,12 @@ func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) wsOther, asnOther := control.NewWorkspaceServiceClient(other), control.NewAssignmentServiceClient(other) refusedFrom2 := func(what string, err error) { t.Helper() - if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1; refused from 127.0.0.2") { + if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1 but connects from 127.0.0.2") { t.Fatalf("%s from 127.0.0.2 as node-a: %v, want the host refusal", what, err) } + if !strings.Contains(status.Convert(err).Message(), "register the node by the address it connects from (not loopback) in the cluster spec") { + t.Fatalf("%s refusal has no registration cure: %v", what, err) + } } _, err := wsOther.RenewWorkspaceLease(r.ctx, id) refusedFrom2("renew", err) @@ -254,7 +264,7 @@ func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) _, err = stream.Recv() } refusedFrom2("assignment stream", err) - if n := strings.Count(r.logs.String(), "refused from 127.0.0.2"); n < 3 { + if n := strings.Count(r.logs.String(), "connects from 127.0.0.2"); n < 3 { t.Fatalf("refusals logged %d times, want 3:\n%s", n, r.logs.String()) } // the registered host is unaffected: it renews and receives the line @@ -393,7 +403,7 @@ func TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck(t *testing.T) { if err == nil { _, err = stream.Recv() } - if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "refused from 127.0.0.2") { + if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "connects from 127.0.0.2") { t.Fatalf("deletion-reserved workspace volume, stream from another host: %v, want the host refusal", err) } } diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index c241b644da..798569ef4b 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "sort" @@ -75,9 +76,24 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidNodeRegistration) } + dir, err := filepath.Abs(filepath.Clean(dir)) + if err != nil { + return nil, fmt.Errorf("lifecycle: resolve store path: %w", err) + } if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir node inventory %q: %w", dir, err) } + // INV-LIFECYCLE-STORE-DURABLE-001: existence does not prove durability. + // Every open syncs the full ancestor chain, also after a failed first open. + for parent := filepath.Dir(dir); ; parent = filepath.Dir(parent) { + if err := syncBindingParent(parent); err != nil { + log.Printf("lifecycle: could not sync %s (%v): the store directory entry may not survive a crash right after its creation", parent, err) + } + if parent == filepath.Dir(parent) { + break + } + } + s := &NodeInventoryStore{ dir: dir, records: make(map[string]NodeRegistration), @@ -205,27 +221,7 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { 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 + return writeRecordDurably(s.dir, rec.ServerID+".json", raw) } func (s *NodeInventoryStore) path(serverID string) string { diff --git a/seaweed-block/core/lifecycle/node_inventory_crash_test.go b/seaweed-block/core/lifecycle/node_inventory_crash_test.go new file mode 100644 index 0000000000..aba4ef1e86 --- /dev/null +++ b/seaweed-block/core/lifecycle/node_inventory_crash_test.go @@ -0,0 +1,100 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func crashNodeRegistration(updated bool) NodeRegistration { + value := "old" + if updated { + value = "new" + } + return NodeRegistration{ + ServerID: "node-a", Addr: "127.0.0.1:9100", + SeenAt: time.Unix(1, 0).UTC(), + Labels: map[string]string{"payload": strings.Repeat(value, 4096)}, + } +} + +// RegisterNode must leave a complete old or new registration across a process +// crash at either side of the publication rename (INV-LIFECYCLE-STORE-DURABLE-001). +func TestNodeInventoryCrashKeepsCompleteRegistration(t *testing.T) { + for _, phase := range []string{"before-rename", "after-rename"} { + t.Run(phase, func(t *testing.T) { + dir := t.TempDir() + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + old, next := crashNodeRegistration(false), crashNodeRegistration(true) + if _, err := s.RegisterNode(old); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNodeInventoryCrashChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "NODE_INVENTORY_CRASH_DIR="+dir, "NODE_INVENTORY_CRASH_PHASE="+phase) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 73 { + t.Fatalf("crash point not reached: err=%v context=%v output=%s", err, ctx.Err(), out) + } + raw, err := os.ReadFile(filepath.Join(dir, "node-a.json")) + if err != nil { + t.Fatalf("crash lost the committed registration: %v", err) + } + var got NodeRegistration + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatalf("crash left a partial registration: %v", err) + } + if !reflect.DeepEqual(got, old) && !reflect.DeepEqual(got, next) { + t.Fatal("crash left neither the complete old nor the complete new registration") + } + want := old + if phase == "after-rename" { + want = next + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("wrong generation at %s", phase) + } + reopened, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + if got, ok := reopened.GetNodeSnapshot("node-a"); !ok || !reflect.DeepEqual(got, want) { + t.Fatal("reopened snapshot lost the complete registration") + } + }) + } +} + +func TestNodeInventoryCrashChild(t *testing.T) { + dir := os.Getenv("NODE_INVENTORY_CRASH_DIR") + if dir == "" { + t.Skip("subprocess crash injector") + } + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + durableRecordHooksForTest.Store(&durableRecordHooks{crash: func(phase string) { + if phase == os.Getenv("NODE_INVENTORY_CRASH_PHASE") { + os.Exit(73) // abrupt exit: no deferred cleanup or close + } + }}) + if _, err := s.RegisterNode(crashNodeRegistration(true)); err != nil { + t.Fatal(err) + } + t.Fatal("write returned without reaching the crash point") +} diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index 7d4a58ef8a..69216ae01c 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "sort" @@ -46,9 +47,24 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } + dir, err := filepath.Abs(filepath.Clean(dir)) + if err != nil { + return nil, fmt.Errorf("lifecycle: resolve store path: %w", err) + } if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir placement intent %q: %w", dir, err) } + // INV-LIFECYCLE-STORE-DURABLE-001: existence does not prove durability. + // Every open syncs the full ancestor chain, also after a failed first open. + for parent := filepath.Dir(dir); ; parent = filepath.Dir(parent) { + if err := syncBindingParent(parent); err != nil { + log.Printf("lifecycle: could not sync %s (%v): the store directory entry may not survive a crash right after its creation", parent, err) + } + if parent == filepath.Dir(parent) { + break + } + } + s := &PlacementIntentStore{ dir: dir, records: make(map[string]PlacementIntent), @@ -183,27 +199,7 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { 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 + return writeRecordDurably(s.dir, rec.VolumeID+".json", raw) } func (s *PlacementIntentStore) path(volumeID string) string { diff --git a/seaweed-block/core/lifecycle/record_file.go b/seaweed-block/core/lifecycle/record_file.go new file mode 100644 index 0000000000..04e5b5e772 --- /dev/null +++ b/seaweed-block/core/lifecycle/record_file.go @@ -0,0 +1,61 @@ +package lifecycle + +import ( + "fmt" + "os" + "path/filepath" + "sync/atomic" +) + +// Hooks are installed only in isolated subprocess tests. Production uses +// the real filesystem operations; one helper owns all publication seams. +type durableRecordHooks struct { + crash func(string) + fileSync func(*os.File) error + dirSync func(string) error +} + +var durableRecordHooksForTest atomic.Pointer[durableRecordHooks] + +// writeRecordDurably implements INV-LIFECYCLE-STORE-DURABLE-001 for puts and +// replacements. A post-rename error may leave the new record on disk. +func writeRecordDurably(dir, name string, raw []byte) error { + f, err := os.CreateTemp(dir, name+".*.tmp") + if err != nil { + return fmt.Errorf("lifecycle: temp record %s: %w", name, err) + } + defer os.Remove(f.Name()) + if _, err := f.Write(raw); err != nil { + _ = f.Close() + return fmt.Errorf("lifecycle: write record %s: %w", name, err) + } + hooks := durableRecordHooksForTest.Load() + fileSync := f.Sync + if hooks != nil && hooks.fileSync != nil { + fileSync = func() error { return hooks.fileSync(f) } + } + if err := fileSync(); err != nil { + _ = f.Close() + return fmt.Errorf("lifecycle: sync record %s: %w", name, err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("lifecycle: close record %s: %w", name, err) + } + if hooks != nil && hooks.crash != nil { + hooks.crash("before-rename") + } + if err := os.Rename(f.Name(), filepath.Join(dir, name)); err != nil { + return fmt.Errorf("lifecycle: rename record %s: %w", name, err) + } + if hooks != nil && hooks.crash != nil { + hooks.crash("after-rename") + } + dirSync := syncBindingParent + if hooks != nil && hooks.dirSync != nil { + dirSync = hooks.dirSync + } + if err := dirSync(dir); err != nil { + return fmt.Errorf("lifecycle: sync record directory %s: %w", name, err) + } + return nil +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 89b1e6ae66..01f297c9d4 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "regexp" @@ -87,9 +88,24 @@ func OpenFileStore(dir string) (*FileStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } + dir, err := filepath.Abs(filepath.Clean(dir)) + if err != nil { + return nil, fmt.Errorf("lifecycle: resolve store path: %w", err) + } if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir %q: %w", dir, err) } + // INV-LIFECYCLE-STORE-DURABLE-001: existence does not prove durability. + // Every open syncs the full ancestor chain, also after a failed first open. + for parent := filepath.Dir(dir); ; parent = filepath.Dir(parent) { + if err := syncBindingParent(parent); err != nil { + log.Printf("lifecycle: could not sync %s (%v): the store directory entry may not survive a crash right after its creation", parent, err) + } + if parent == filepath.Dir(parent) { + break + } + } + s := &FileStore{ dir: dir, records: make(map[string]VolumeRecord), @@ -291,30 +307,7 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { 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 + return writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw) } func (s *FileStore) path(volumeID string) string { diff --git a/seaweed-block/core/lifecycle/store_crash_test.go b/seaweed-block/core/lifecycle/store_crash_test.go new file mode 100644 index 0000000000..c28e073981 --- /dev/null +++ b/seaweed-block/core/lifecycle/store_crash_test.go @@ -0,0 +1,254 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +// INV-LIFECYCLE-STORE-DURABLE-001: each public write retains the complete +// old/new record across abrupt process exit at both rename boundaries. +func TestFileStoreCrashKeepsCompleteRecord(t *testing.T) { checkStoreCrash(t, "volume") } +func TestPlacementStoreCrashKeepsCompleteRecord(t *testing.T) { checkStoreCrash(t, "placement") } + +type recordCrashFixture struct { + old, next any + put func(bool) error + get func() (any, bool) +} + +func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) recordCrashFixture { + t.Helper() + durableRecordHooksForTest.Store(nil) + if hook != nil { + durableRecordHooksForTest.Store(&durableRecordHooks{crash: hook}) + } + if kind == "node" { + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + return recordCrashFixture{old: crashNodeRegistration(false), next: crashNodeRegistration(true), + put: func(updated bool) error { _, err := s.RegisterNode(crashNodeRegistration(updated)); return err }, + get: func() (any, bool) { + r, ok := s.GetNodeSnapshot("node-a") + memory, exists := s.GetNode("node-a") + if exists != ok || !reflect.DeepEqual(memory, r) { + t.Fatal("node records and snapshot diverged") + } + return r, ok + }, + } + } + if kind == "volume" { + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + old := VolumeRecord{Spec: VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1, Protocol: "iscsi", PVCName: strings.Repeat("payload", 1024)}} + next := old + next.AttachedTo = "node-b" + return recordCrashFixture{old: old, next: next, + put: func(updated bool) error { + if updated { + _, err := s.AttachVolume("vol-a", "node-b") + return err + } + _, err := s.CreateVolume(old.Spec) + return err + }, get: func() (any, bool) { + r, ok := s.GetVolumeSnapshot("vol-a") + memory, exists := s.GetVolume("vol-a") + if exists != ok || !reflect.DeepEqual(memory, r) { + t.Fatal("volume records and snapshot diverged") + } + return r, ok + }, + } + } + if kind != "placement" { + t.Fatalf("unknown fixture %q", kind) + } + s, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + old := PlacementIntent{VolumeID: "vol-a", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node-a", PoolID: strings.Repeat("old", 4096), Source: PlacementSourceBlankPool}}} + next := copyPlacementIntent(old) + next.Slots[0].PoolID = strings.Repeat("new", 4096) + return recordCrashFixture{old: old, next: next, + put: func(updated bool) error { + r := old + if updated { + r = next + } + _, err := s.ApplyPlan(PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []PlacementCandidate{{VolumeID: "vol-a", ServerID: "node-a", PoolID: r.Slots[0].PoolID, Source: PlacementSourceBlankPool}}}) + return err + }, get: func() (any, bool) { + r, ok := s.GetPlacementSnapshot("vol-a") + memory, exists := s.GetPlacement("vol-a") + if exists != ok || !reflect.DeepEqual(memory, r) { + t.Fatal("placement records and snapshot diverged") + } + return r, ok + }, + } +} + +func checkStoreCrash(t *testing.T, kind string) { + t.Helper() + for _, phase := range []string{"before-rename", "after-rename"} { + t.Run(phase, func(t *testing.T) { + dir := t.TempDir() + f := openRecordCrashFixture(t, kind, dir, nil) + if err := f.put(false); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordStoreCrashChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "RECORD_STORE_CRASH_DIR="+dir, "RECORD_STORE_CRASH_KIND="+kind, "RECORD_STORE_CRASH_PHASE="+phase) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 73 { + t.Fatalf("crash point not reached: %v context=%v output=%s", err, ctx.Err(), out) + } + raw, err := os.ReadFile(filepath.Join(dir, "vol-a.json")) + if err != nil { + t.Fatalf("crash lost the committed record: %v", err) + } + want := f.old + if phase == "after-rename" { + want = f.next + } + wantRaw, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + var gotJSON, wantJSON any + if err := json.Unmarshal(raw, &gotJSON); err != nil { + t.Fatalf("partial record: %v", err) + } + if err := json.Unmarshal(wantRaw, &wantJSON); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(gotJSON, wantJSON) { + t.Fatalf("wrong or incomplete record at %s", phase) + } + reopened := openRecordCrashFixture(t, kind, dir, nil) + if got, ok := reopened.get(); !ok || !reflect.DeepEqual(got, want) { + t.Fatal("reopened snapshot differs from the complete record") + } + }) + } +} + +func TestRecordStoreCrashChild(t *testing.T) { + dir := os.Getenv("RECORD_STORE_CRASH_DIR") + if dir == "" { + t.Skip("subprocess crash injector") + } + f := openRecordCrashFixture(t, os.Getenv("RECORD_STORE_CRASH_KIND"), dir, func(phase string) { + if phase == os.Getenv("RECORD_STORE_CRASH_PHASE") { + os.Exit(73) + } + }) + if err := f.put(true); err != nil { + t.Fatal(err) + } + t.Fatal("write returned without reaching the crash point") +} + +// The injected operations delegate to real fsync, so omitting either call +// loses its event or fails to surface the injected error. +func TestLifecyclePutSyncOrderAndFailure(t *testing.T) { + for _, kind := range []string{"node", "volume", "placement"} { + for _, failure := range []string{"none", "file", "directory", "nil-hooks"} { + t.Run(kind+"/"+failure, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePutSyncChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "LIFECYCLE_SYNC_KIND="+kind, "LIFECYCLE_SYNC_FAILURE="+failure) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("sync control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func TestLifecyclePutSyncChild(t *testing.T) { + kind := os.Getenv("LIFECYCLE_SYNC_KIND") + if kind == "" { + t.Skip("isolated sync control") + } + failure := os.Getenv("LIFECYCLE_SYNC_FAILURE") + dir := t.TempDir() + f := openRecordCrashFixture(t, kind, dir, nil) + if err := f.put(false); err != nil { + t.Fatal(err) + } + fault := errors.New("injected sync failure") + var events []string + if failure != "nil-hooks" { + durableRecordHooksForTest.Store(&durableRecordHooks{fileSync: func(file *os.File) error { + events = append(events, "file") + if filepath.Ext(file.Name()) != ".tmp" { + t.Fatal("sync must target the candidate file") + } + if failure == "file" { + return fault + } + return file.Sync() + }, dirSync: func(path string) error { + events = append(events, "directory") + if path != dir { + t.Fatal("sync must target the record directory") + } + if failure == "directory" { + return fault + } + return syncBindingParent(path) + }}) + } + err := f.put(true) + want := f.next + if failure == "file" || failure == "directory" { + if !errors.Is(err, fault) { + t.Fatalf("sync failure hidden: %v", err) + } + want = f.old + } else if err != nil { + t.Fatal(err) + } + if got, ok := f.get(); !ok || !reflect.DeepEqual(got, want) { + t.Fatal("memory published before successful sync") + } + wantEvents := []string{"file", "directory"} + if failure == "file" { + wantEvents = []string{"file"} + } + if failure == "nil-hooks" { + wantEvents = nil + } + if !reflect.DeepEqual(events, wantEvents) { + t.Fatalf("sync events %v want %v", events, wantEvents) + } + reopened := openRecordCrashFixture(t, kind, dir, nil) + diskWant := f.next + if failure == "file" { + diskWant = f.old + } + if got, ok := reopened.get(); !ok || !reflect.DeepEqual(got, diskWant) { + t.Fatal("wrong durable record after sync outcome") + } +} diff --git a/seaweed-block/core/lifecycle/store_parent_sync_test.go b/seaweed-block/core/lifecycle/store_parent_sync_test.go new file mode 100644 index 0000000000..9897d3ed98 --- /dev/null +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -0,0 +1,129 @@ +//go:build linux + +package lifecycle + +import ( + "bytes" + "context" + "log" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +// INV-LIFECYCLE-STORE-DURABLE-001: every open syncs the full ancestor chain, +// including a retry after failed creation; a trailing separator changes no target. +func TestLifecycleStoreParentSync(t *testing.T) { + for _, kind := range []string{"node", "volume", "placement"} { + for _, shape := range []string{"nested", "trailing-slash", "failed-parent-sync", "ancestor-permission", "relative-path"} { + t.Run(kind+"/"+shape, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecycleStoreParentSyncChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "LIFECYCLE_PARENT_ROOT="+t.TempDir(), "LIFECYCLE_PARENT_KIND="+kind, "LIFECYCLE_PARENT_SHAPE="+shape) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("parent sync control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func TestLifecycleStoreParentSyncChild(t *testing.T) { + root := os.Getenv("LIFECYCLE_PARENT_ROOT") + if root == "" { + t.Skip("isolated syscall-boundary control") + } + shape := os.Getenv("LIFECYCLE_PARENT_SHAPE") + dir := filepath.Join(root, "new-parent", "deeper", "store") + if shape == "trailing-slash" { + dir = filepath.Join(root, "store") + string(os.PathSeparator) + } + if shape == "relative-path" { + if err := os.Chdir(root); err != nil { + t.Fatal(err) + } + dir = filepath.Join("new-parent", "deeper", "store") + } + abs, err := filepath.Abs(filepath.Clean(dir)) + if err != nil { + t.Fatal(err) + } + // Independently enumerate absolute path prefixes, deepest first, down to /. + parts := strings.Split(strings.TrimPrefix(filepath.Dir(abs), "/"), "/") + var want []string + for n := len(parts); n > 0; n-- { + want = append(want, "/"+strings.Join(parts[:n], "/")) + } + want = append(want, "/") + var calls []string + var warnings bytes.Buffer + log.SetOutput(&warnings) + realSync := syncBindingParent + failFirst := shape == "failed-parent-sync" + fault := &os.PathError{Op: "open", Path: want[0], Err: os.ErrPermission} + syncBindingParent = func(path string) error { + calls = append(calls, path) + if shape == "ancestor-permission" && path == want[len(want)-2] { + return &os.PathError{Op: "open", Path: path, Err: os.ErrPermission} + } + if failFirst { + failFirst = false + return fault + } + return realSync(path) + } + open := func() error { + switch os.Getenv("LIFECYCLE_PARENT_KIND") { + case "node": + _, err := OpenNodeInventoryStore(dir) + return err + case "volume": + _, err := OpenFileStore(dir) + return err + case "placement": + _, err := OpenPlacementIntentStore(dir) + return err + default: + t.Fatal("unknown store kind") + return nil + } + } + if shape == "failed-parent-sync" { + if err := open(); err != nil { + t.Fatalf("best-effort ancestor sync blocked Open: %v", err) + } + if !reflect.DeepEqual(calls, want) { + t.Fatalf("failed-first syncs %v want %v", calls, want) + } + if strings.Count(warnings.String(), "lifecycle: could not sync ") != 1 || !strings.Contains(warnings.String(), "the store directory entry may not survive a crash right after its creation") { + t.Fatalf("missing ancestor durability warning: %s", warnings.String()) + } + calls = nil + warnings.Reset() + } + + if err := open(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(calls, want) { + t.Fatalf("parent syncs %v want %v", calls, want) + } + if shape == "ancestor-permission" { + if strings.Count(warnings.String(), "lifecycle: could not sync ") != 1 || !strings.Contains(warnings.String(), "permission denied") || !strings.Contains(warnings.String(), "the store directory entry may not survive a crash right after its creation") { + t.Fatalf("missing permission warning: %s", warnings.String()) + } + warnings.Reset() + } + calls = nil + if err := open(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(calls, want) { + t.Fatalf("existing-store retry syncs %v want %v", calls, want) + } +} diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index d3fbefd8e9..1d6270d41f 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -36,7 +36,9 @@ func OpenWorkspaceBindingStore(dir string) (*WorkspaceBindingStore, error) { return openWorkspaceBindingStore(dir, syncBindingParent) } -func syncBindingParent(dir string) error { +// Isolated subprocess tests may replace this syscall boundary; production +// always uses the real directory Sync below. +var syncBindingParent = func(dir string) error { f, err := os.Open(dir) if err != nil { return err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9a07e8cd70..7831af1871 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -467,7 +467,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -314 rows: 243 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 299 new. +315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -652,12 +652,14 @@ Notes: | `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | | `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | | `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | Notes: +- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record. - `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failed write's durable outcome may be unknown (the record may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. - `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`. - `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). @@ -711,11 +713,11 @@ Notes: | `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB | | `INV-WS-REOPEN-FENCE-001` | Before I/O, an active reopened holder replaces the observed HEAD generation, including the same epoch/holder and an empty HEAD. A previous incarnation's delayed CAS cannot publish afterward. Local acknowledged WAL is retained. | M4 Claiming -> Holder | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS`, `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites` (`core/storage/chunk_reopen_belt_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `HeadReopenBelt` `OldCASCannotLandAfterReopen` | ACTIVE | | `INV-WS-SEALED-REOPEN-001` | A same-epoch/holder reopen cannot reactivate a detached HEAD. It refuses before preparation, CAS or serving, retaining the exact generation, owner, frontier, image and detachedBy proof for the planned new holder. | M4 Claiming -> Detached | `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestClaimChunkHeadSameOwnerReopenPreservesSeal` (`core/storage/chunk_reopen_belt_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `SealedReopen` `SealedReopenPreservesProof` | ACTIVE | -| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead` | `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE | +| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`; `cmd/blockvolume/workspace_lease.go` `workspaceDetachedGeneration` | `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`); `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn` (a rolled-back copy), is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`); `TestRolledBackCopyBelowHeadLSNIsRefused` (`core/frontend/durable/rolled_back_copy_test.go`); `TestCutPublishesOnlyLocallyDurableLSN` (`core/frontend/durable/cut_durable_before_cas_test.go`) | — | ACTIVE | -| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | +| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry: same holder and epoch only, no move pending or issued, not revoking, store certain, one durable write, and only once max(horizon, deadline) + skew bound has passed; the new process claims HEAD with a new generation before any I/O, so no older incarnation writes or CASes after. | M2 lease: Expired → Granted | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut`, `TestWorkspaceLeaseRegrantCannotUnsealSameEpoch`, `TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD` (`core/authority/workspace_regrant_storage_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | @@ -1070,7 +1072,7 @@ A row that names a function existing only on an open pull request says so ("on # | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | | `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer | | `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn`, is refused before the claim and never served. A rolled-back copy exits 78; a foreign holder below the assignment's epoch stays up without serving. | HEAD `Holder`, `RemoteLSN`; `ProviderConfig.ChunkHolder`; the store's durable LSN (`WALStore.Boundaries`) | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | A copy of the root taken after its last cut has HEAD's LSN and passes: no local check sees it (never restore a root from a copy). | volume host | -| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) reimplements the proof check for the revocation ACK: open. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | +| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | Revocation ACK also delegates to `ReadDetachedChunkHead` through `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`); `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`) checks assigned epoch/holder, fresh proof and read errors without a write. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | | `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | | `TERM-ONE-PROCESS-001` One live process per volume per host | At most one blockvolume process serves a volume on one host: each holds `/run/sw-block/locks/.lock` from before its store opens, whatever its `--durable-root`. Across hosts the assignment and the workspace lease keep holders apart. | The host lock file (`durable.HostVolumeLockDir`, `deploy/systemd/sw-block.tmpfiles.conf`); the store file `<--durable-root>/.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); their exclusive OS file locks; the HEAD `Holder` | Volume: `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (on #439; `ProviderConfig.HostVolumeLock`, set by blockvolume; a missing directory refuses the provider), taken in `ensureHandle` before the store opens and released after it closes. `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the locks' limit: they cover one host. A second process is not refused when it runs on another host with the same server id, in a container without the host's `/run/sw-block/locks` (the Kubernetes renderer does not mount it: open), or on a copied root on another host. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine | diff --git a/seaweed-block/docs/releases/one-process-per-volume.md b/seaweed-block/docs/releases/one-process-per-volume.md index e2604748c5..93ed89b56b 100644 --- a/seaweed-block/docs/releases/one-process-per-volume.md +++ b/seaweed-block/docs/releases/one-process-per-volume.md @@ -7,7 +7,8 @@ the same host is refused before it opens anything, whatever its `--durable-root`. The lock is released when the process exits, including on a crash or kill. -blockvolume creates the directory (`0700`) when it is missing and it may, and +blockvolume creates the directory when it is missing and it may, laid out as +the tmpfiles.d entry does (`/run/sw-block` `0755`, `/run/sw-block/locks` `0700`), and refuses to start when it cannot create or open the directory or a volume's lock file. The shipped units cannot create it (`ProtectSystem=strict`), so install the tmpfiles.d entry shipped in [`deploy/systemd/sw-block.tmpfiles.conf`](../../deploy/systemd/sw-block.tmpfiles.conf): @@ -22,11 +23,12 @@ boot. Both shipped units allow writes to it (`ReadWritePaths=-/run/sw-block/locks`). Without it, or when it is not usable, blockvolume exits at start with `host volume lock directory unavailable ... install the tmpfiles.d entry (deploy/systemd/sw-block.tmpfiles.conf), -or chown the directory and its lock files to this process's user`. A -directory created by a root process (the root ublk unit, or blockvolume run -by hand as root) is root-owned, and an unprivileged unit on that host then -cannot use it: install the tmpfiles.d entry, or chown the directory to the -unit's user. Lock files are opened read-only, so a lock file another user +or make its parent directory traversable (0755) and chown the directory and +its lock files to this process's user`. A directory created by a root +process (the root ublk unit, or blockvolume run by hand as root) is +root-owned, and an unprivileged unit on that host then cannot use it: +install the tmpfiles.d entry, or chown the locks directory to the unit's +user and make sure `/run/sw-block` is `0755`. Lock files are opened read-only, so a lock file another user created stays lockable. ## A rolled-back copy of a root is refused