From 34f5c7656c167b9084e9771e7dc89da5a985c2d6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:21:33 -0800 Subject: [PATCH 01/26] test: reproduce node inventory loss at publication rename --- .../core/lifecycle/node_inventory.go | 15 ++- .../lifecycle/node_inventory_crash_test.go | 100 ++++++++++++++++++ 2 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/lifecycle/node_inventory_crash_test.go diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index c241b644da..f5bd801584 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -64,10 +64,11 @@ type NodeRegistration struct { // NodeInventoryStore persists one JSON registration record per server. type NodeInventoryStore struct { - mu sync.Mutex - dir string - records map[string]NodeRegistration - published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + mu sync.Mutex + dir string + records map[string]NodeRegistration + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + persistHookForTest func(string) // nil in production; crash injection at publication boundaries } // OpenNodeInventoryStore opens or creates a node inventory store. @@ -222,9 +223,15 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: replace node %s: %w", rec.ServerID, err) } + if s.persistHookForTest != nil { + s.persistHookForTest("before-rename") + } if err := os.Rename(tmpName, path); err != nil { return fmt.Errorf("lifecycle: rename node %s: %w", rec.ServerID, err) } + if s.persistHookForTest != nil { + s.persistHookForTest("after-rename") + } return nil } 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..4463d1f1be --- /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 (V1-SPEC r2.46). +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) + } + s.persistHookForTest = 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") +} From ba6574c87b3bb1a60b74915273c603d782929c79 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:21:57 -0800 Subject: [PATCH 02/26] fix: atomically sync node inventory replacements --- seaweed-block/core/lifecycle/node_inventory.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index f5bd801584..da5b90d81b 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -217,12 +217,15 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write node temp %s: %w", rec.ServerID, err) } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: sync 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) - } + // V1-SPEC r2.46: replace without an absent-file window; acknowledge only + // after both the complete candidate and its directory entry are synced. if s.persistHookForTest != nil { s.persistHookForTest("before-rename") } @@ -232,6 +235,9 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } + if err := syncBindingParent(s.dir); err != nil { + return fmt.Errorf("lifecycle: sync node directory %s: %w", rec.ServerID, err) + } return nil } From 5ea7c6a006416602a228bb372cd732e9e713ec30 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:26:32 -0800 Subject: [PATCH 03/26] docs: bind node inventory crash safety to durability invariant --- seaweed-block/core/lifecycle/node_inventory.go | 2 +- seaweed-block/core/lifecycle/node_inventory_crash_test.go | 2 +- seaweed-block/docs/design/invariants.md | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index da5b90d81b..b18d6cbd1e 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -224,7 +224,7 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { if err := tmp.Close(); err != nil { return fmt.Errorf("lifecycle: close node temp %s: %w", rec.ServerID, err) } - // V1-SPEC r2.46: replace without an absent-file window; acknowledge only + // INV-LIFECYCLE-STORE-DURABLE-001: replace without an absent-file window; acknowledge only // after both the complete candidate and its directory entry are synced. if s.persistHookForTest != nil { s.persistHookForTest("before-rename") diff --git a/seaweed-block/core/lifecycle/node_inventory_crash_test.go b/seaweed-block/core/lifecycle/node_inventory_crash_test.go index 4463d1f1be..c84c43142a 100644 --- a/seaweed-block/core/lifecycle/node_inventory_crash_test.go +++ b/seaweed-block/core/lifecycle/node_inventory_crash_test.go @@ -28,7 +28,7 @@ func crashNodeRegistration(updated bool) NodeRegistration { } // RegisterNode must leave a complete old or new registration across a process -// crash at either side of the publication rename (V1-SPEC r2.46). +// 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) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 19bb6ca18b..96ea82b964 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -313 rows: 242 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 298 new. +314 rows: 243 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 299 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. @@ -650,6 +650,7 @@ 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` | A lifecycle store write is atomic and durable: after a crash at any point the node file is the complete old or the complete new record, never absent or partial; a put that returned nil has fsynced the file and its directory. | M2 node registration publication | `core/lifecycle/node_inventory.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_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 | From 4bc0d302c6251657e3cb2bce372bf30dfe65421b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:28:04 -0800 Subject: [PATCH 04/26] docs: generalize lifecycle durability row and record open gaps --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 96ea82b964..a1e1dc0686 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,13 +650,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` | A lifecycle store write is atomic and durable: after a crash at any point the node file is the complete old or the complete new record, never absent or partial; a put that returned nil has fsynced the file and its directory. | M2 node registration publication | `core/lifecycle/node_inventory.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-STORE-DURABLE-001` | A lifecycle store write is atomic and durable: after a crash at any point 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 node registration publication | `core/lifecycle/node_inventory.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_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: `FileStore.putLocked` (`core/lifecycle/store.go`) and `PlacementIntentStore.putLocked` (`core/lifecycle/placement_intent.go`) still remove the previous file before rename and do not fsync the replacement or its directory. The current enforcement and crash controls cover node inventory only; the other stores require separate fixes. - `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). From 956a5f86eb49ffe1b9801ac64643f64714fa430d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:29:06 -0800 Subject: [PATCH 05/26] docs: disclose lifecycle failed-put and delete durability gaps --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a1e1dc0686..00695c83b4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -657,7 +657,7 @@ Notes: Notes: -- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: `FileStore.putLocked` (`core/lifecycle/store.go`) and `PlacementIntentStore.putLocked` (`core/lifecycle/placement_intent.go`) still remove the previous file before rename and do not fsync the replacement or its directory. The current enforcement and crash controls cover node inventory only; the other stores require separate fixes. +- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: `FileStore.putLocked` (`core/lifecycle/store.go`) and `PlacementIntentStore.putLocked` (`core/lifecycle/placement_intent.go`) still remove the previous file before rename and do not fsync the replacement or its directory. The current enforcement and crash controls cover node inventory puts only; the other stores require separate fixes. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. - `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). From 16ea488a0bbb825ff376826efd3485306e38a3b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:30:55 -0800 Subject: [PATCH 06/26] test: reproduce volume and placement record loss across rename --- .../core/lifecycle/placement_intent.go | 15 +- seaweed-block/core/lifecycle/store.go | 9 +- .../core/lifecycle/store_crash_test.go | 136 ++++++++++++++++++ 3 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/lifecycle/store_crash_test.go diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index 7d4a58ef8a..d93fc07d19 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -35,10 +35,11 @@ type PlacementIntent struct { // PlacementIntentStore persists one placement intent per volume. type PlacementIntentStore struct { - mu sync.Mutex - dir string - records map[string]PlacementIntent - published sync.Map // committed immutable PlacementIntent values; renewal never takes mu + mu sync.Mutex + dir string + records map[string]PlacementIntent + published sync.Map // committed immutable PlacementIntent values; renewal never takes mu + persistHookForTest func(string) // nil in production; crash injection at publication boundaries } // OpenPlacementIntentStore opens or creates a placement intent store. @@ -200,9 +201,15 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { 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 s.persistHookForTest != nil { + s.persistHookForTest("before-rename") + } if err := os.Rename(tmpName, path); err != nil { return fmt.Errorf("lifecycle: rename placement intent %s: %w", rec.VolumeID, err) } + if s.persistHookForTest != nil { + s.persistHookForTest("after-rename") + } return nil } diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 89b1e6ae66..5c3c130115 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -57,7 +57,8 @@ type FileStore struct { records map[string]VolumeRecord // snap mirrors records as an immutable copy, republished at every change // of records, for lock-free renewal-path reads. - snap atomic.Pointer[map[string]VolumeRecord] + snap atomic.Pointer[map[string]VolumeRecord] + persistHookForTest func(string) // nil in production; crash injection at publication boundaries } // publishLocked republishes the immutable snapshot of records. Caller holds @@ -311,9 +312,15 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: replace %s: %w", rec.Spec.VolumeID, err) } + if s.persistHookForTest != nil { + s.persistHookForTest("before-rename") + } if err := os.Rename(tmpName, path); err != nil { return fmt.Errorf("lifecycle: rename %s: %w", rec.Spec.VolumeID, err) } + if s.persistHookForTest != nil { + s.persistHookForTest("after-rename") + } return nil } 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..0f65092de7 --- /dev/null +++ b/seaweed-block/core/lifecycle/store_crash_test.go @@ -0,0 +1,136 @@ +//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() + if kind == "volume" { + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + s.persistHookForTest = hook + 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"); return r, ok }, + } + } + if kind != "placement" { + t.Fatalf("unknown fixture %q", kind) + } + s, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + s.persistHookForTest = hook + 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"); 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") +} From 33097cb79769b39e51dc0e25150b56b6a9a541be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:31:31 -0800 Subject: [PATCH 07/26] fix: durably replace volume and placement lifecycle records --- seaweed-block/core/lifecycle/placement_intent.go | 12 +++++++++--- seaweed-block/core/lifecycle/store.go | 15 +++++++++------ seaweed-block/docs/design/invariants.md | 4 ++-- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index d93fc07d19..bcd9253cea 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -195,12 +195,15 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write placement intent temp %s: %w", rec.VolumeID, err) } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: sync 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) - } + // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. + if s.persistHookForTest != nil { s.persistHookForTest("before-rename") } @@ -210,6 +213,9 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } + if err := syncBindingParent(s.dir); err != nil { + return fmt.Errorf("lifecycle: sync placement intent directory %s: %w", rec.VolumeID, err) + } return nil } diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 5c3c130115..54cacf328a 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -303,15 +303,15 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write temp %s: %w", rec.Spec.VolumeID, err) } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("lifecycle: sync record 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) - } + // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. + if s.persistHookForTest != nil { s.persistHookForTest("before-rename") } @@ -321,6 +321,9 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } + if err := syncBindingParent(s.dir); err != nil { + return fmt.Errorf("lifecycle: sync record directory %s: %w", rec.Spec.VolumeID, err) + } return nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 00695c83b4..6563b4a00b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,14 +650,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` | A lifecycle store write is atomic and durable: after a crash at any point 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 node registration publication | `core/lifecycle/node_inventory.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-STORE-DURABLE-001` | A lifecycle store write is atomic and durable: after a crash at any point 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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord` (`core/lifecycle/store_crash_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: `FileStore.putLocked` (`core/lifecycle/store.go`) and `PlacementIntentStore.putLocked` (`core/lifecycle/placement_intent.go`) still remove the previous file before rename and do not fsync the replacement or its directory. The current enforcement and crash controls cover node inventory puts only; the other stores require separate fixes. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. +- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: `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). From d0626bdfcdb737a5fd82073ceb7b0c07c4d4d459 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:35:08 -0800 Subject: [PATCH 08/26] fix: sync lifecycle parent entries and pin sync failure publication --- .../core/lifecycle/node_inventory.go | 23 +++- .../core/lifecycle/placement_intent.go | 24 +++- seaweed-block/core/lifecycle/store.go | 22 +++- .../core/lifecycle/store_crash_test.go | 110 +++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 165 insertions(+), 16 deletions(-) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index b18d6cbd1e..ae615a2754 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -67,8 +67,10 @@ type NodeInventoryStore struct { mu sync.Mutex dir string records map[string]NodeRegistration - published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) - persistHookForTest func(string) // nil in production; crash injection at publication boundaries + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + persistHookForTest func(string) // nil in production; crash injection at publication boundaries + fileSyncForTest func(*os.File) error // nil uses the real file Sync + dirSyncForTest func(string) error // nil uses syncBindingParent } // OpenNodeInventoryStore opens or creates a node inventory store. @@ -79,6 +81,11 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { 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: persist a newly created store entry. + if err := syncBindingParent(filepath.Dir(dir)); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + s := &NodeInventoryStore{ dir: dir, records: make(map[string]NodeRegistration), @@ -217,7 +224,11 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write node temp %s: %w", rec.ServerID, err) } - if err := tmp.Sync(); err != nil { + fileSync := tmp.Sync + if s.fileSyncForTest != nil { + fileSync = func() error { return s.fileSyncForTest(tmp) } + } + if err := fileSync(); err != nil { _ = tmp.Close() return fmt.Errorf("lifecycle: sync node temp %s: %w", rec.ServerID, err) } @@ -235,7 +246,11 @@ func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } - if err := syncBindingParent(s.dir); err != nil { + dirSync := syncBindingParent + if s.dirSyncForTest != nil { + dirSync = s.dirSyncForTest + } + if err := dirSync(s.dir); err != nil { return fmt.Errorf("lifecycle: sync node directory %s: %w", rec.ServerID, err) } return nil diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index bcd9253cea..8927a73a9b 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -38,8 +38,10 @@ type PlacementIntentStore struct { mu sync.Mutex dir string records map[string]PlacementIntent - published sync.Map // committed immutable PlacementIntent values; renewal never takes mu - persistHookForTest func(string) // nil in production; crash injection at publication boundaries + published sync.Map // committed immutable PlacementIntent values; renewal never takes mu + persistHookForTest func(string) // nil in production; crash injection at publication boundaries + fileSyncForTest func(*os.File) error // nil uses the real file Sync + dirSyncForTest func(string) error // nil uses syncBindingParent } // OpenPlacementIntentStore opens or creates a placement intent store. @@ -50,6 +52,11 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { 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: persist a newly created store entry. + if err := syncBindingParent(filepath.Dir(dir)); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + s := &PlacementIntentStore{ dir: dir, records: make(map[string]PlacementIntent), @@ -195,7 +202,11 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write placement intent temp %s: %w", rec.VolumeID, err) } - if err := tmp.Sync(); err != nil { + fileSync := tmp.Sync + if s.fileSyncForTest != nil { + fileSync = func() error { return s.fileSyncForTest(tmp) } + } + if err := fileSync(); err != nil { _ = tmp.Close() return fmt.Errorf("lifecycle: sync placement intent temp %s: %w", rec.VolumeID, err) } @@ -203,7 +214,6 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { return fmt.Errorf("lifecycle: close placement intent temp %s: %w", rec.VolumeID, err) } // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. - if s.persistHookForTest != nil { s.persistHookForTest("before-rename") } @@ -213,7 +223,11 @@ func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } - if err := syncBindingParent(s.dir); err != nil { + dirSync := syncBindingParent + if s.dirSyncForTest != nil { + dirSync = s.dirSyncForTest + } + if err := dirSync(s.dir); err != nil { return fmt.Errorf("lifecycle: sync placement intent directory %s: %w", rec.VolumeID, err) } return nil diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 54cacf328a..9a18faa8a2 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -58,7 +58,9 @@ type FileStore struct { // snap mirrors records as an immutable copy, republished at every change // of records, for lock-free renewal-path reads. snap atomic.Pointer[map[string]VolumeRecord] - persistHookForTest func(string) // nil in production; crash injection at publication boundaries + persistHookForTest func(string) // nil in production; crash injection at publication boundaries + fileSyncForTest func(*os.File) error // nil uses the real file Sync + dirSyncForTest func(string) error // nil uses syncBindingParent } // publishLocked republishes the immutable snapshot of records. Caller holds @@ -91,6 +93,11 @@ func OpenFileStore(dir string) (*FileStore, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir %q: %w", dir, err) } + // INV-LIFECYCLE-STORE-DURABLE-001: persist a newly created store entry. + if err := syncBindingParent(filepath.Dir(dir)); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + s := &FileStore{ dir: dir, records: make(map[string]VolumeRecord), @@ -303,7 +310,11 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { _ = tmp.Close() return fmt.Errorf("lifecycle: write temp %s: %w", rec.Spec.VolumeID, err) } - if err := tmp.Sync(); err != nil { + fileSync := tmp.Sync + if s.fileSyncForTest != nil { + fileSync = func() error { return s.fileSyncForTest(tmp) } + } + if err := fileSync(); err != nil { _ = tmp.Close() return fmt.Errorf("lifecycle: sync record temp %s: %w", rec.Spec.VolumeID, err) } @@ -311,7 +322,6 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { return fmt.Errorf("lifecycle: close temp %s: %w", rec.Spec.VolumeID, err) } // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. - if s.persistHookForTest != nil { s.persistHookForTest("before-rename") } @@ -321,7 +331,11 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { if s.persistHookForTest != nil { s.persistHookForTest("after-rename") } - if err := syncBindingParent(s.dir); err != nil { + dirSync := syncBindingParent + if s.dirSyncForTest != nil { + dirSync = s.dirSyncForTest + } + if err := dirSync(s.dir); err != nil { return fmt.Errorf("lifecycle: sync record directory %s: %w", rec.Spec.VolumeID, err) } return nil diff --git a/seaweed-block/core/lifecycle/store_crash_test.go b/seaweed-block/core/lifecycle/store_crash_test.go index 0f65092de7..c0d86a3dcc 100644 --- a/seaweed-block/core/lifecycle/store_crash_test.go +++ b/seaweed-block/core/lifecycle/store_crash_test.go @@ -24,10 +24,30 @@ type recordCrashFixture struct { old, next any put func(bool) error get func() (any, bool) + setSync func(func(*os.File) error, func(string) error) } func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) recordCrashFixture { t.Helper() + if kind == "node" { + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + s.persistHookForTest = hook + 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 + }, + setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, + } + } if kind == "volume" { s, err := OpenFileStore(dir) if err != nil { @@ -45,7 +65,15 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r } _, err := s.CreateVolume(old.Spec) return err - }, get: func() (any, bool) { r, ok := s.GetVolumeSnapshot("vol-a"); return r, ok }, + }, 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 + }, + setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, } } if kind != "placement" { @@ -67,7 +95,15 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r } _, 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"); return r, ok }, + }, 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 + }, + setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, } } @@ -134,3 +170,73 @@ func TestRecordStoreCrashChild(t *testing.T) { } 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) { + 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" { + f.setSync(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() + }, 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/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6563b4a00b..008bb61eae 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,7 +650,7 @@ 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` | A lifecycle store write is atomic and durable: after a crash at any point 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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord` (`core/lifecycle/store_crash_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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_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 | From f865a8e21f475fdf44970e60365a35d08cc65aee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:43:23 -0800 Subject: [PATCH 09/26] test: expose unsynced lifecycle ancestors and trailing separator --- .../core/lifecycle/store_parent_sync_test.go | 82 +++++++++++++++++++ .../core/lifecycle/workspace_bindings.go | 4 +- 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/lifecycle/store_parent_sync_test.go 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..3828af708a --- /dev/null +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -0,0 +1,82 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "reflect" + "testing" + "time" +) + +// INV-LIFECYCLE-STORE-DURABLE-001: creation syncs every new directory's +// parent, including a new ancestor; 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"} { + 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") + } + dir := filepath.Join(root, "store") + want := []string{root} + if os.Getenv("LIFECYCLE_PARENT_SHAPE") == "nested" { + dir = filepath.Join(root, "new-parent", "store") + want = []string{filepath.Dir(dir), root} + } else { + dir += string(os.PathSeparator) + } + var calls []string + realSync := syncBindingParent + syncBindingParent = func(path string) error { + calls = append(calls, path) + 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 err := open(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(calls, want) { + t.Fatalf("parent syncs %v want %v", calls, want) + } + calls = nil + if err := open(); err != nil { + t.Fatal(err) + } + want = []string{filepath.Dir(filepath.Clean(dir))} + 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 From aaedc618551fa203ac4da10a48a719b334d24082 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:44:01 -0800 Subject: [PATCH 10/26] fix: sync every created lifecycle ancestor from cleaned paths --- .../core/lifecycle/node_inventory.go | 28 +++++++++++++++++-- .../core/lifecycle/placement_intent.go | 28 +++++++++++++++++-- seaweed-block/core/lifecycle/store.go | 28 +++++++++++++++++-- .../core/lifecycle/store_parent_sync_test.go | 4 +-- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 78 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index ae615a2754..6e0f959c4a 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -78,12 +78,34 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidNodeRegistration) } + dir = filepath.Clean(dir) + ancestor := dir + for { + if _, err := os.Stat(ancestor); err == nil { + break + } else if !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) + } + parent := filepath.Dir(ancestor) + if parent == ancestor { + return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) + } + ancestor = parent + } 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: persist a newly created store entry. - if err := syncBindingParent(filepath.Dir(dir)); err != nil { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + // INV-LIFECYCLE-STORE-DURABLE-001: sync every new directory's parent, + // deepest first. Existing-store retries still sync the store's parent. + for current := dir; ; { + parent := filepath.Dir(current) + if err := syncBindingParent(parent); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + if current == ancestor || parent == ancestor { + break + } + current = parent } s := &NodeInventoryStore{ diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index 8927a73a9b..a9034b8fa6 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -49,12 +49,34 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } + dir = filepath.Clean(dir) + ancestor := dir + for { + if _, err := os.Stat(ancestor); err == nil { + break + } else if !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) + } + parent := filepath.Dir(ancestor) + if parent == ancestor { + return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) + } + ancestor = parent + } 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: persist a newly created store entry. - if err := syncBindingParent(filepath.Dir(dir)); err != nil { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + // INV-LIFECYCLE-STORE-DURABLE-001: sync every new directory's parent, + // deepest first. Existing-store retries still sync the store's parent. + for current := dir; ; { + parent := filepath.Dir(current) + if err := syncBindingParent(parent); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + if current == ancestor || parent == ancestor { + break + } + current = parent } s := &PlacementIntentStore{ diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 9a18faa8a2..e8cd453504 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -90,12 +90,34 @@ func OpenFileStore(dir string) (*FileStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } + dir = filepath.Clean(dir) + ancestor := dir + for { + if _, err := os.Stat(ancestor); err == nil { + break + } else if !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) + } + parent := filepath.Dir(ancestor) + if parent == ancestor { + return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) + } + ancestor = parent + } if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir %q: %w", dir, err) } - // INV-LIFECYCLE-STORE-DURABLE-001: persist a newly created store entry. - if err := syncBindingParent(filepath.Dir(dir)); err != nil { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + // INV-LIFECYCLE-STORE-DURABLE-001: sync every new directory's parent, + // deepest first. Existing-store retries still sync the store's parent. + for current := dir; ; { + parent := filepath.Dir(current) + if err := syncBindingParent(parent); err != nil { + return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + } + if current == ancestor || parent == ancestor { + break + } + current = parent } s := &FileStore{ diff --git a/seaweed-block/core/lifecycle/store_parent_sync_test.go b/seaweed-block/core/lifecycle/store_parent_sync_test.go index 3828af708a..7290dfe63a 100644 --- a/seaweed-block/core/lifecycle/store_parent_sync_test.go +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -38,8 +38,8 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { dir := filepath.Join(root, "store") want := []string{root} if os.Getenv("LIFECYCLE_PARENT_SHAPE") == "nested" { - dir = filepath.Join(root, "new-parent", "store") - want = []string{filepath.Dir(dir), root} + dir = filepath.Join(root, "new-parent", "deeper", "store") + want = []string{filepath.Dir(dir), filepath.Join(root, "new-parent"), root} } else { dir += string(os.PathSeparator) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 008bb61eae..109348b90c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,7 +650,7 @@ 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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `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 | From b87fea473b09b6c13b78466b877e00b01a3d424c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:50:31 -0800 Subject: [PATCH 11/26] test: reproduce incomplete ancestor sync after failed first open --- .../core/lifecycle/store_parent_sync_test.go | 52 +++++++++++++++---- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/lifecycle/store_parent_sync_test.go b/seaweed-block/core/lifecycle/store_parent_sync_test.go index 7290dfe63a..c1fef0d8e0 100644 --- a/seaweed-block/core/lifecycle/store_parent_sync_test.go +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -4,19 +4,21 @@ package lifecycle import ( "context" + "errors" "os" "os/exec" "path/filepath" "reflect" + "strings" "testing" "time" ) -// INV-LIFECYCLE-STORE-DURABLE-001: creation syncs every new directory's -// parent, including a new ancestor; a trailing separator changes no target. +// 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"} { + for _, shape := range []string{"nested", "trailing-slash", "failed-parent-sync", "relative-path"} { t.Run(kind+"/"+shape, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() @@ -35,18 +37,38 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { if root == "" { t.Skip("isolated syscall-boundary control") } - dir := filepath.Join(root, "store") - want := []string{root} - if os.Getenv("LIFECYCLE_PARENT_SHAPE") == "nested" { - dir = filepath.Join(root, "new-parent", "deeper", "store") - want = []string{filepath.Dir(dir), filepath.Join(root, "new-parent"), root} - } else { - dir += string(os.PathSeparator) + 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 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 failFirst { + failFirst = false + return fault + } return realSync(path) } open := func() error { @@ -65,6 +87,15 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { return nil } } + if shape == "failed-parent-sync" { + if err := open(); !errors.Is(err, os.ErrPermission) { + t.Fatalf("ancestor sync failure hidden: %v", err) + } + if !reflect.DeepEqual(calls, want[:1]) { + t.Fatalf("failed syncs %v want %v", calls, want[:1]) + } + calls = nil + } if err := open(); err != nil { t.Fatal(err) } @@ -75,7 +106,6 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { if err := open(); err != nil { t.Fatal(err) } - want = []string{filepath.Dir(filepath.Clean(dir))} if !reflect.DeepEqual(calls, want) { t.Fatalf("existing-store retry syncs %v want %v", calls, want) } From f9038ca88d1dd54998bf8b13fc2abd85fea54312 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:51:03 -0800 Subject: [PATCH 12/26] fix: sync the full lifecycle ancestor chain on every open --- .../core/lifecycle/node_inventory.go | 28 ++++++------------- .../core/lifecycle/placement_intent.go | 28 ++++++------------- seaweed-block/core/lifecycle/store.go | 28 ++++++------------- 3 files changed, 24 insertions(+), 60 deletions(-) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index 6e0f959c4a..6975c64330 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -78,34 +78,22 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidNodeRegistration) } - dir = filepath.Clean(dir) - ancestor := dir - for { - if _, err := os.Stat(ancestor); err == nil { - break - } else if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) - } - parent := filepath.Dir(ancestor) - if parent == ancestor { - return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) - } - ancestor = parent + 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: sync every new directory's parent, - // deepest first. Existing-store retries still sync the store's parent. - for current := dir; ; { - parent := filepath.Dir(current) + // 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 { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) } - if current == ancestor || parent == ancestor { + if parent == filepath.Dir(parent) { break } - current = parent } s := &NodeInventoryStore{ diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index a9034b8fa6..dcca42190b 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -49,34 +49,22 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } - dir = filepath.Clean(dir) - ancestor := dir - for { - if _, err := os.Stat(ancestor); err == nil { - break - } else if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) - } - parent := filepath.Dir(ancestor) - if parent == ancestor { - return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) - } - ancestor = parent + 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: sync every new directory's parent, - // deepest first. Existing-store retries still sync the store's parent. - for current := dir; ; { - parent := filepath.Dir(current) + // 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 { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) } - if current == ancestor || parent == ancestor { + if parent == filepath.Dir(parent) { break } - current = parent } s := &PlacementIntentStore{ diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index e8cd453504..e7b4eb752c 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -90,34 +90,22 @@ func OpenFileStore(dir string) (*FileStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } - dir = filepath.Clean(dir) - ancestor := dir - for { - if _, err := os.Stat(ancestor); err == nil { - break - } else if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("lifecycle: stat store ancestor: %w", err) - } - parent := filepath.Dir(ancestor) - if parent == ancestor { - return nil, fmt.Errorf("lifecycle: no existing store ancestor for %q", dir) - } - ancestor = parent + 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: sync every new directory's parent, - // deepest first. Existing-store retries still sync the store's parent. - for current := dir; ; { - parent := filepath.Dir(current) + // 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 { - return nil, fmt.Errorf("lifecycle: sync store parent: %w", err) + return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) } - if current == ancestor || parent == ancestor { + if parent == filepath.Dir(parent) { break } - current = parent } s := &FileStore{ From 07bbe359c157de75c8dc42f1dec3b611086f537b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:13:48 -0800 Subject: [PATCH 13/26] test: require registration cure in holder host refusal --- seaweed-block/core/host/master/server_host_identity_test.go | 3 +++ 1 file changed, 3 insertions(+) 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..5a2357a4c4 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -244,6 +244,9 @@ func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1; refused from 127.0.0.2") { t.Fatalf("%s from 127.0.0.2 as node-a: %v, want the host refusal", what, err) } + 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) From 8829b693127d0ba7492ee1ed267531885bc5abf4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:14:17 -0800 Subject: [PATCH 14/26] fix: explain how to correct a workspace holder host mismatch --- seaweed-block/core/host/master/server_host_identity.go | 2 +- seaweed-block/core/host/master/server_host_identity_test.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/host/master/server_host_identity.go b/seaweed-block/core/host/master/server_host_identity.go index 0ed05e436e..e401a085a5 100644 --- a/seaweed-block/core/host/master/server_host_identity.go +++ b/seaweed-block/core/host/master/server_host_identity.go @@ -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 5a2357a4c4..4a343973b2 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -241,7 +241,7 @@ 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") { @@ -257,7 +257,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 @@ -396,7 +396,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) } } From c775b752afde45cf8304f68a138b19b929df77b1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:24:34 -0800 Subject: [PATCH 15/26] test: require heartbeat registration cure and slot detail --- seaweed-block/core/host/master/server_host_identity_test.go | 4 ++++ 1 file changed, 4 insertions(+) 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 4a343973b2..11a6319cb3 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -145,6 +145,10 @@ func TestServerIDRefusedFromAHostOtherThanItsRegisteredOne(t *testing.T) { 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 connects from 127.0.0.2: register the node by the address it connects from (not loopback) in the cluster spec (volume hb-node-a replica r-node-a)" + 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) } From 7928b4d2571207c2b316ee45827bb0a541244604 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:24:50 -0800 Subject: [PATCH 16/26] fix: give heartbeat host mismatch the registration cure --- seaweed-block/core/host/master/server_host_identity.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/server_host_identity.go b/seaweed-block/core/host/master/server_host_identity.go index e401a085a5..99d2f63733 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 connects from %s: register the node by the address it connects from (not loopback) in the cluster spec (volume %s replica %s)", r.ServerId, named, addrHost(a), s.VolumeId, s.ReplicaId) } } From 8f98eb3caabd2c89f5004956b5169c296b6c636e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:27:48 -0800 Subject: [PATCH 17/26] test: keep lifecycle opens available under ancestor sync failures --- .../core/lifecycle/store_parent_sync_test.go | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/lifecycle/store_parent_sync_test.go b/seaweed-block/core/lifecycle/store_parent_sync_test.go index c1fef0d8e0..9897d3ed98 100644 --- a/seaweed-block/core/lifecycle/store_parent_sync_test.go +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -3,8 +3,9 @@ package lifecycle import ( + "bytes" "context" - "errors" + "log" "os" "os/exec" "path/filepath" @@ -18,7 +19,7 @@ import ( // 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", "relative-path"} { + 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() @@ -60,11 +61,16 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { } 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 @@ -88,20 +94,31 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { } } if shape == "failed-parent-sync" { - if err := open(); !errors.Is(err, os.ErrPermission) { - t.Fatalf("ancestor sync failure hidden: %v", err) + if err := open(); err != nil { + t.Fatalf("best-effort ancestor sync blocked Open: %v", err) } - if !reflect.DeepEqual(calls, want[:1]) { - t.Fatalf("failed syncs %v want %v", calls, want[:1]) + 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) From 3c50b14e8d40f8f534d86db2d559bd9add35f23d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:29:31 -0800 Subject: [PATCH 18/26] refactor: share lifecycle record durability and warn on ancestor sync failures --- .../core/lifecycle/node_inventory.go | 56 +------ .../lifecycle/node_inventory_crash_test.go | 4 +- .../core/lifecycle/placement_intent.go | 55 +------ seaweed-block/core/lifecycle/record_file.go | 61 ++++++++ seaweed-block/core/lifecycle/store.go | 49 +----- .../core/lifecycle/store_crash_test.go | 142 ++++++++++-------- seaweed-block/docs/design/invariants.md | 4 +- 7 files changed, 160 insertions(+), 211 deletions(-) create mode 100644 seaweed-block/core/lifecycle/record_file.go diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index 6975c64330..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" @@ -64,13 +65,10 @@ type NodeRegistration struct { // NodeInventoryStore persists one JSON registration record per server. type NodeInventoryStore struct { - mu sync.Mutex - dir string - records map[string]NodeRegistration - published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) - persistHookForTest func(string) // nil in production; crash injection at publication boundaries - fileSyncForTest func(*os.File) error // nil uses the real file Sync - dirSyncForTest func(string) error // nil uses syncBindingParent + mu sync.Mutex + dir string + records map[string]NodeRegistration + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) } // OpenNodeInventoryStore opens or creates a node inventory store. @@ -89,7 +87,7 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { // 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 { - return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) + 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 @@ -223,47 +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) - } - fileSync := tmp.Sync - if s.fileSyncForTest != nil { - fileSync = func() error { return s.fileSyncForTest(tmp) } - } - if err := fileSync(); err != nil { - _ = tmp.Close() - return fmt.Errorf("lifecycle: sync 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) - } - // INV-LIFECYCLE-STORE-DURABLE-001: replace without an absent-file window; acknowledge only - // after both the complete candidate and its directory entry are synced. - if s.persistHookForTest != nil { - s.persistHookForTest("before-rename") - } - if err := os.Rename(tmpName, path); err != nil { - return fmt.Errorf("lifecycle: rename node %s: %w", rec.ServerID, err) - } - if s.persistHookForTest != nil { - s.persistHookForTest("after-rename") - } - dirSync := syncBindingParent - if s.dirSyncForTest != nil { - dirSync = s.dirSyncForTest - } - if err := dirSync(s.dir); err != nil { - return fmt.Errorf("lifecycle: sync node directory %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 index c84c43142a..aba4ef1e86 100644 --- a/seaweed-block/core/lifecycle/node_inventory_crash_test.go +++ b/seaweed-block/core/lifecycle/node_inventory_crash_test.go @@ -88,11 +88,11 @@ func TestNodeInventoryCrashChild(t *testing.T) { if err != nil { t.Fatal(err) } - s.persistHookForTest = func(phase string) { + 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) } diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index dcca42190b..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" @@ -35,13 +36,10 @@ type PlacementIntent struct { // PlacementIntentStore persists one placement intent per volume. type PlacementIntentStore struct { - mu sync.Mutex - dir string - records map[string]PlacementIntent - published sync.Map // committed immutable PlacementIntent values; renewal never takes mu - persistHookForTest func(string) // nil in production; crash injection at publication boundaries - fileSyncForTest func(*os.File) error // nil uses the real file Sync - dirSyncForTest func(string) error // nil uses syncBindingParent + mu sync.Mutex + dir string + records map[string]PlacementIntent + published sync.Map // committed immutable PlacementIntent values; renewal never takes mu } // OpenPlacementIntentStore opens or creates a placement intent store. @@ -60,7 +58,7 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { // 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 { - return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) + 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 @@ -201,46 +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) - } - fileSync := tmp.Sync - if s.fileSyncForTest != nil { - fileSync = func() error { return s.fileSyncForTest(tmp) } - } - if err := fileSync(); err != nil { - _ = tmp.Close() - return fmt.Errorf("lifecycle: sync 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) - } - // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. - if s.persistHookForTest != nil { - s.persistHookForTest("before-rename") - } - if err := os.Rename(tmpName, path); err != nil { - return fmt.Errorf("lifecycle: rename placement intent %s: %w", rec.VolumeID, err) - } - if s.persistHookForTest != nil { - s.persistHookForTest("after-rename") - } - dirSync := syncBindingParent - if s.dirSyncForTest != nil { - dirSync = s.dirSyncForTest - } - if err := dirSync(s.dir); err != nil { - return fmt.Errorf("lifecycle: sync placement intent directory %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 e7b4eb752c..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" @@ -57,10 +58,7 @@ type FileStore struct { records map[string]VolumeRecord // snap mirrors records as an immutable copy, republished at every change // of records, for lock-free renewal-path reads. - snap atomic.Pointer[map[string]VolumeRecord] - persistHookForTest func(string) // nil in production; crash injection at publication boundaries - fileSyncForTest func(*os.File) error // nil uses the real file Sync - dirSyncForTest func(string) error // nil uses syncBindingParent + snap atomic.Pointer[map[string]VolumeRecord] } // publishLocked republishes the immutable snapshot of records. Caller holds @@ -101,7 +99,7 @@ func OpenFileStore(dir string) (*FileStore, error) { // 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 { - return nil, fmt.Errorf("lifecycle: sync store ancestor %q: %w", parent, err) + 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 @@ -309,46 +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) - } - fileSync := tmp.Sync - if s.fileSyncForTest != nil { - fileSync = func() error { return s.fileSyncForTest(tmp) } - } - if err := fileSync(); err != nil { - _ = tmp.Close() - return fmt.Errorf("lifecycle: sync record 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) - } - // INV-LIFECYCLE-STORE-DURABLE-001: retain the old file until atomic replacement. - if s.persistHookForTest != nil { - s.persistHookForTest("before-rename") - } - if err := os.Rename(tmpName, path); err != nil { - return fmt.Errorf("lifecycle: rename %s: %w", rec.Spec.VolumeID, err) - } - if s.persistHookForTest != nil { - s.persistHookForTest("after-rename") - } - dirSync := syncBindingParent - if s.dirSyncForTest != nil { - dirSync = s.dirSyncForTest - } - if err := dirSync(s.dir); err != nil { - return fmt.Errorf("lifecycle: sync record directory %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 index c0d86a3dcc..c28e073981 100644 --- a/seaweed-block/core/lifecycle/store_crash_test.go +++ b/seaweed-block/core/lifecycle/store_crash_test.go @@ -24,17 +24,19 @@ type recordCrashFixture struct { old, next any put func(bool) error get func() (any, bool) - setSync func(func(*os.File) error, func(string) error) } 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) } - s.persistHookForTest = hook return recordCrashFixture{old: crashNodeRegistration(false), next: crashNodeRegistration(true), put: func(updated bool) error { _, err := s.RegisterNode(crashNodeRegistration(updated)); return err }, get: func() (any, bool) { @@ -45,7 +47,6 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r } return r, ok }, - setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, } } if kind == "volume" { @@ -53,7 +54,6 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r if err != nil { t.Fatal(err) } - s.persistHookForTest = hook 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" @@ -73,7 +73,6 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r } return r, ok }, - setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, } } if kind != "placement" { @@ -83,7 +82,6 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r if err != nil { t.Fatal(err) } - s.persistHookForTest = hook 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) @@ -103,7 +101,6 @@ func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) r } return r, ok }, - setSync: func(f func(*os.File) error, d func(string) error) { s.fileSyncForTest, s.dirSyncForTest = f, d }, } } @@ -177,66 +174,81 @@ 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) { - 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" { - f.setSync(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() - }, 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") + 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/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 109348b90c..572e39b719 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,14 +650,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/node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` (temp + Sync, rename over the old file, `syncBindingParent`) | `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-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: `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-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). From 286f5ebeb8f4df7465fde5eeca356c4391ddd893 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:46:10 -0800 Subject: [PATCH 19/26] durable: red test, a created lock directory's parent must be 0755 V1-SPEC r2.45 (1): MkdirAll(locks, 0700) also makes a missing parent /run/sw-block 0700; created by root, it keeps the unit's user out even after the locks directory is chowned. The tmpfiles.d layout is parent 0755, locks 0700. Co-Authored-By: Claude Opus 5.5 --- .../durable/volume_lock_parent_mode_test.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go 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..3890219402 --- /dev/null +++ b/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go @@ -0,0 +1,40 @@ +//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) + } + } +} From 4c36f1f8614b80bcea97e47569ae38d370b11c9b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:46:38 -0800 Subject: [PATCH 20/26] durable: lay out a created lock directory as tmpfiles.d does A missing /run/sw-block is created 0755 and the locks directory 0700, with the modes set explicitly (the umask cannot narrow them); existing directories are left alone. The cure line also names the parent. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 27 +++++++++++++++++-- .../docs/releases/one-process-per-volume.md | 14 +++++----- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index eb391db3d8..00ac1bb722 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,30 @@ 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. Existing directories are left +// as they are. Modes are set explicitly, so the umask cannot narrow them. +func makeVolumeLockDir(dir string) error { + parent := filepath.Dir(dir) + if _, err := os.Stat(parent); errors.Is(err, os.ErrNotExist) { + if err := os.MkdirAll(parent, 0o755); err != nil { + return err + } + if err := os.Chmod(parent, 0o755); err != nil { + return err + } + } + if err := os.Mkdir(dir, 0o700); err != nil { + if errors.Is(err, os.ErrExist) { + return nil + } + return err + } + return os.Chmod(dir, 0o700) +} // 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/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 From 8edb6b128e52560f104badbd09e371a653956ad9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 12:15:41 -0800 Subject: [PATCH 21/26] test: distinguish heartbeat advertised address from RPC peer --- .../core/host/master/server_host_identity_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 11a6319cb3..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,11 +141,14 @@ 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 connects from 127.0.0.2: register the node by the address it connects from (not loopback) in the cluster spec (volume hb-node-a replica r-node-a)" + 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) } From a777189b7f69b5b34f7abd9c3b8333529cb6e5a3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 12:15:53 -0800 Subject: [PATCH 22/26] fix: diagnose advertised heartbeat addresses accurately --- seaweed-block/core/host/master/server_host_identity.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/server_host_identity.go b/seaweed-block/core/host/master/server_host_identity.go index 99d2f63733..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 but connects from %s: register the node by the address it connects from (not loopback) in the cluster spec (volume %s replica %s)", + 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) } } From 5c84520d48f1fedc3fac3d8e3c79b5d45f74e7d6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 12:22:36 -0800 Subject: [PATCH 23/26] durable: red test, a regular file as the lock directory is accepted The new helper treats any existing lock path as the directory; the old constructor refused a non-directory. Controls: an existing parent and an existing lock directory keep their modes. Co-Authored-By: Claude Opus 5.5 --- .../durable/one_process_per_volume_test.go | 19 ++++++++ .../durable/volume_lock_parent_mode_test.go | 48 +++++++++++++++++++ 2 files changed, 67 insertions(+) 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/volume_lock_parent_mode_test.go b/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go index 3890219402..ba85f454d9 100644 --- a/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go +++ b/seaweed-block/core/frontend/durable/volume_lock_parent_mode_test.go @@ -38,3 +38,51 @@ func TestHostVolumeLockCreatesParent0755AndLocks0700(t *testing.T) { } } } + +// 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) +} + From dc393ba380532f21052a865df2f76087629518dc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 12:22:51 -0800 Subject: [PATCH 24/26] durable: refuse a non-directory lock path; chmod only what this call created The lock directory and its parent are chmod'ed only when this call's own Mkdir created them, so an existing or concurrently created directory keeps its mode; an existing lock path that is not a directory refuses (Lstat), as the constructor did before. The invariant row links the mode tests. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 34 ++++++++++++------- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 00ac1bb722..e99ada32b2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -564,25 +564,35 @@ const volumeLockCure = "install the tmpfiles.d entry (deploy/systemd/sw-block.tm // 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. Existing directories are left -// as they are. Modes are set explicitly, so the umask cannot narrow them. +// 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.Stat(parent); errors.Is(err, os.ErrNotExist) { - if err := os.MkdirAll(parent, 0o755); err != nil { - return err - } + 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 } - } - if err := os.Mkdir(dir, 0o700); err != nil { - if errors.Is(err, os.ErrExist) { - return nil - } + } else if !errors.Is(err, os.ErrExist) { return err } - return os.Chmod(dir, 0o700) + 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 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9a07e8cd70..8d2d96542f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -715,7 +715,7 @@ Notes: | `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 | From bdbe601e4c75d8b52904055628e29e16362c6ca9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:23:42 -0800 Subject: [PATCH 25/26] test(workspace): refuse unassigned stored seal proofs --- .../cmd/blockvolume/workspace_proof_test.go | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/workspace_proof_test.go 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) + } + }) + } +} From b4daad80d1554d9107dc98b67003c6fd56b0b92b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 11:24:07 -0800 Subject: [PATCH 26/26] fix(workspace): delegate revocation ACK to stored seal proof --- seaweed-block/cmd/blockvolume/workspace_lease.go | 6 +----- seaweed-block/docs/design/invariants.md | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) 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/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9a07e8cd70..c92859ef2e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -711,7 +711,7 @@ 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 | @@ -1070,7 +1070,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 |