From d0626bdfcdb737a5fd82073ceb7b0c07c4d4d459 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 10:35:08 -0800 Subject: [PATCH] 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 |