diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 56f3965639..2d7f4be8c3 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -399,6 +399,9 @@ func (h *Host) finalizeBelow(servers []string, level uint32) []hostBelow { failed = append(failed, fmt.Sprintf("last reported level %d", last)) } } + if h.readsLevelUnkept(s) { + failed = append(failed, "read level not kept durably") + } if len(failed) > 0 { out = append(out, hostBelow{s, strings.Join(failed, "; ")}) } @@ -469,16 +472,34 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, err error) { // recordReadsLevel keeps server's last reported level after a heartbeat: in // memory, and on its node record when it changed, so an idle host is judged -// by it across restarts. A failed write is logged; the finalize then reads -// the level kept in memory. -func (h *Host) recordReadsLevel(server string) { +// by it across restarts. Settling and writing happen under readsKeepMu, so +// two heartbeats cannot leave the older level on disk. A failed write fails +// closed: the host is marked unkept (the finalize refuses it) until a later +// write succeeds, and the error is returned so the heartbeat is refused and +// sent again. +func (h *Host) recordReadsLevel(server string) error { + h.readsKeepMu.Lock() + defer h.readsKeepMu.Unlock() level, ok := h.reads.settle(server, h.servedBy(server)) if !ok || h.lifecycle == nil { - return + return nil } if _, err := h.lifecycle.Nodes.RecordReadsLevel(server, level); err != nil { - h.log.Printf("blockmaster: node %s: keeping its read level %d: %v", server, level, err) + if h.readsUnkept == nil { + h.readsUnkept = map[string]bool{} + } + h.readsUnkept[server] = true + return fmt.Errorf("node %s: keeping its read level %d: %w", server, level, err) } + delete(h.readsUnkept, server) + return nil +} + +// readsLevelUnkept says server's last read level failed to be kept durably. +func (h *Host) readsLevelUnkept(server string) bool { + h.readsKeepMu.Lock() + defer h.readsKeepMu.Unlock() + return h.readsUnkept[server] } // lastReadsLevel is server's last reported level: from this master's @@ -527,7 +548,7 @@ func (h *Host) finalizeHosts() []string { } var out []string for s := range candidates { - if _, known := h.lastReadsLevel(s); known || len(h.volumesServedBy(s)) > 0 { + if _, known := h.lastReadsLevel(s); known || h.readsLevelUnkept(s) || len(h.volumesServedBy(s)) > 0 { out = append(out, s) } } diff --git a/seaweed-block/core/host/master/format_gate_test.go b/seaweed-block/core/host/master/format_gate_test.go index a6bdd5b272..0f37398666 100644 --- a/seaweed-block/core/host/master/format_gate_test.go +++ b/seaweed-block/core/host/master/format_gate_test.go @@ -293,9 +293,9 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) { if _, ok := r.m.Lifecycle().Nodes.GetNode("node-a"); ok { t.Fatal("the retired host is still registered") } - // node-b (holding "held") reports level 1; node-a, retired, never - // reported: the finalize goes through. - if err := r.fgHeartbeat("node-b", 1); err != nil { + // node-b reports level 1 for "held", the volume it holds; node-a, + // retired, never reported: the finalize goes through. + if err := r.fgProcessHeartbeat("node-b", "proc-held", "held", 1); err != nil { t.Fatal(err) } if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil { @@ -741,32 +741,26 @@ func TestFinalizeFormatJudgesEveryServedVolume(t *testing.T) { t.Fatalf("finalize with both of node-b's volumes at level 1: %v", err) } - // Work held only as an issued line: vol is granted to node-a, then its - // placement is deleted. node-a reports level 1 only for another volume, - // so the line's volume has no report of its own: refused. + // Work held only as an issued line: a workspace move issues "leased" to + // node-b, then its placement is deleted. node-b reports level 1 only for + // another volume, so the line's volume has no report of its own: refused. lease := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) - lease.createVolume(t, "leased") - lease.place(t, "leased", "node-a") - if err := ingestV11(lease.m, authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(), - Slots: []authority.SlotFact{{VolumeID: "leased", ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil { - t.Fatal(err) - } - if _, err := lease.m.RunLifecycleProductTick(); err != nil { - t.Fatal(err) - } - waitAuthorityLine(t, lease.m.Publisher(), "leased") - if line := lease.m.Publisher().PublishedAuthorityLines()["leased"]; line.IssuedHost != "node-a" { - t.Fatalf("fixture line: %+v, want issued to node-a", line) + lease.issueMove(t, "leased", "m-leased") + if line := lease.m.Publisher().PublishedAuthorityLines()["leased"]; line.IssuedHost != "node-b" { + t.Fatalf("fixture line: %+v, want issued to node-b", line) } if err := lease.m.Lifecycle().Placements.DeletePlacement("leased"); err != nil { t.Fatal(err) } - lease.m.reads.forget("node-a") - if err := lease.fgProcessHeartbeat("node-a", "proc-other", "other", 1); err != nil { + lease.m.reads.forget("node-b") + if err := lease.fgProcessHeartbeat("node-b", "proc-other", "other", 1); err != nil { t.Fatal(err) } - if err := finalize(lease); reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "node-a (volume leased: no report)") { - t.Fatalf("finalize with node-a holding only the leased line, unreported for it: %v", err) + if err := lease.fgHeartbeat("node-a", 1); err != nil { + t.Fatal(err) + } + if err := finalize(lease); reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "node-b (volume leased: no report)") { + t.Fatalf("finalize with node-b holding only the leased line, unreported for it: %v", err) } } @@ -786,20 +780,25 @@ func TestFinalizeFormatJudgesAnIdleHostByItsLastLevel(t *testing.T) { r.m.reads.mu.Unlock() } for _, tc := range []struct { - name string - level uint32 - want string // "" passes + name string + before []uint32 // earlier reports, oldest first + level uint32 // the last report + want string // "" passes }{ - {"last-1-passes", 1, ""}, - {"last-0-blocks", 0, "node-b (last reported level 0)"}, + {"last-1-passes", nil, 1, ""}, + {"last-0-blocks", nil, 0, "node-b (last reported level 0)"}, + {"1-then-0-blocks", []uint32{1}, 0, "node-b (last reported level 0)"}, + {"0-then-1-passes", []uint32{0}, 1, ""}, } { t.Run(tc.name, func(t *testing.T) { authDir, lcDir := upgradedStoreDir(t), t.TempDir() r := newIsolationRig(t, false, authDir, lcDir) r.createVolume(t, "held") r.place(t, "held", "node-b") - if err := r.fgProcessHeartbeat("node-b", "proc-held", "held", tc.level); err != nil { - t.Fatal(err) + for _, l := range append(append([]uint32(nil), tc.before...), tc.level) { + if err := r.fgProcessHeartbeat("node-b", "proc-held", "held", l); err != nil { + t.Fatal(err) + } } if err := r.m.Lifecycle().Placements.DeletePlacement("held"); err != nil { // emptied t.Fatal(err) @@ -835,3 +834,72 @@ func TestFinalizeFormatJudgesAnIdleHostByItsLastLevel(t *testing.T) { }) } } + +// Keeping a host's last read level is ordered and fails closed: of two +// heartbeats, the later one's level is the one left on the node record even +// when the earlier one's write is still in progress; a failed write refuses +// the heartbeat (the host sends it again) and the finalize refuses the host +// until a later write succeeds. +func TestTheLastReadLevelIsKeptInOrderAndFailsClosed(t *testing.T) { + r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) + nodes := r.m.Lifecycle().Nodes + level := func() (uint32, bool) { + rec, ok := nodes.GetNode("node-b") + if !ok || rec.ReadsLevel == nil { + return 0, false + } + return *rec.ReadsLevel, true + } + + // Ordering: the level-1 write is held; a level-0 report comes meanwhile. + release := nodes.HoldWritesForTest() + r.m.reads.note("node-b", "", "p1", 1) + first := make(chan error, 1) + go func() { first <- r.m.recordReadsLevel("node-b") }() + time.Sleep(50 * time.Millisecond) // the first keeper is inside its held write + r.m.reads.note("node-b", "", "p1", 0) + second := make(chan error, 1) + go func() { second <- r.m.recordReadsLevel("node-b") }() + release() + for _, ch := range []chan error{first, second} { + select { + case err := <-ch: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("a keeper did not return") + } + } + if l, ok := level(); !ok || l != 0 { + t.Fatalf("node record level %d (%v) after reports 1 then 0, want 0", l, ok) + } + + // Fail closed: a failed write refuses the heartbeat and marks the host. + failed := errors.New("injected node record write failure") + nodes.SetPersistHookForTest(func() error { return failed }) + if err := r.fgHeartbeat("node-b", 1); status.Code(err) != codes.Unavailable { + t.Fatalf("heartbeat whose level could not be kept: %v, want Unavailable", err) + } + if err := r.fgHeartbeat("node-a", 1); err != nil { + nodes.SetPersistHookForTest(nil) + if err := r.fgHeartbeat("node-a", 1); err != nil { + t.Fatal(err) + } + nodes.SetPersistHookForTest(func() error { return failed }) + } + _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}) + if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "read level not kept durably") { + t.Fatalf("finalize with node-b's level unkept: %v", err) + } + nodes.SetPersistHookForTest(nil) + if err := r.fgHeartbeat("node-b", 1); err != nil { + t.Fatalf("heartbeat after the write recovers: %v", err) + } + if l, ok := level(); !ok || l != 1 { + t.Fatalf("node record level %d (%v) after the recovered write, want 1", l, ok) + } + if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil { + t.Fatalf("finalize once node-b's level is kept: %v", err) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index a3db16fa6f..fa485ddf71 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -157,6 +157,12 @@ type Host struct { grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits) format formatLevelState // the cluster's format level (format_gate.go) finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) + // readsKeepMu orders keeping a host's last read level: the level is + // settled and written under it, so a later report's level is always the + // one left on disk. readsUnkept marks hosts whose last level failed to be + // kept; the finalize refuses them until a later write succeeds. + readsKeepMu sync.Mutex + readsUnkept map[string]bool // testGrantWaitsRead, when a test sets it, runs after a status snapshot // has read its placements, still holding grantWaitMu. testGrantWaitsRead func() diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index aa68733535..6644f09cf8 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -543,7 +543,11 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo // lower level, and the grant (publication) refuses a holder process // whose own report is below the cluster's level, typed binary_too_old. s.host.reads.noteHeartbeat(r.GetServerId(), r.GetSlots(), r.GetReadsLevel()) - s.host.recordReadsLevel(r.GetServerId()) + // The host's last read level is kept durably before the report is + // accepted; a failed write refuses it, so the host sends it again. + if err := s.host.recordReadsLevel(r.GetServerId()); err != nil { + return nil, status.Error(codes.Unavailable, err.Error()) + } msg := heartbeatFromWire(r) if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil { return nil, fmt.Errorf("ingest: %w", err) diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index 5294ce4d47..c325aa2801 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -71,7 +71,17 @@ 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) + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + failWrite func() error // tests: a non-nil error fails the next record write +} + +// SetPersistHookForTest installs (nil clears) a callback that each later +// record write of this store runs under the store mutex before the write. A +// non-nil error fails that write with nothing replaced. Tests only. +func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) { + s.mu.Lock() + defer s.mu.Unlock() + s.failWrite = hook } // OpenNodeInventoryStore opens or creates a node inventory store. @@ -247,6 +257,11 @@ func (s *NodeInventoryStore) load() error { } func (s *NodeInventoryStore) putLocked(rec NodeRegistration) error { + if s.failWrite != nil { + if err := s.failWrite(); err != nil { + return fmt.Errorf("lifecycle: write node %s: %w", rec.ServerID, err) + } + } raw, err := json.MarshalIndent(rec, "", " ") if err != nil { return fmt.Errorf("lifecycle: marshal node %s: %w", rec.ServerID, err) @@ -329,6 +344,10 @@ func copyNodeRegistration(reg NodeRegistration) NodeRegistration { out.Pools[i].Labels = copyStringMap(out.Pools[i].Labels) } out.Replicas = append([]ReplicaInventory(nil), reg.Replicas...) + if reg.ReadsLevel != nil { + l := *reg.ReadsLevel + out.ReadsLevel = &l + } return out } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8cddb1cb28..5131dfb61b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -838,7 +838,7 @@ Notes: | `INV-WS-RESTART-GRACE-001` | At format level 1, a renewal writes nothing durable. A forced move, an expired re-grant and a no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | | `INV-WS-AUTH-RECORD-V2-001` | The format finalize writes the store's attestation file as format 2 (`INV-FMT-LEVEL-001`), on which a v1.0.x master refuses its whole start; from then on its authority records are envelope version 2 (a v1.0.x master would skip them); before it, both are v1.0's. It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | | `INV-FMT-LEVEL-001` | The cluster's format level is the attestation file's form: v1.0.x's bare map is level 0, the envelope (format 2, format_level 1) level 1. It only rises: the finalize is its only writer, and an envelope below level 1 is refused at start. | FormatGate Finalize (level 0 → 1) | `core/host/master/store_attestation.go` `decodeStoreAttestations`, `finalize`, `persist`, `level`; `core/host/master/host.go` `New` | `TestFinalizeFormatNeedsEveryHostWithWorkOrAReportAndIsDurable`, `TestAnAttestationEnvelopeBelowLevel1IsRefused` (`core/host/master/format_gate_test.go`); `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAV100MasterRefusesTheAttestationEnvelope` (`core/host/master/golden_v100_test.go`) | `FormatGate` `OneWay` (mutation `level_lowered`) | ACTIVE | -| `INV-FMT-FINALIZE-001` | Finalize is refused, naming them, while a host with work lacks a live level-1 report per served volume, or a reported process or an idle host's last kept level is below 1 (never reported: no block). Else: envelope write, publisher switch under both locks, answer; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeHosts`, `finalizeBelow`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatNeedsEveryHostWithWorkOrAReportAndIsDurable`, `TestFinalizeFormatIgnoresAnIdleUnreportedHost`, `TestFinalizeFormatJudgesEveryServedVolume`, `TestFinalizeFormatJudgesAnIdleHostByItsLastLevel`, `TestAFailedFinalizeWriteLeavesLevel0` (`core/host/master/format_gate_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE | +| `INV-FMT-FINALIZE-001` | Finalize is refused, naming them, while a host with work lacks a live level-1 report per served volume, or a reported process or an idle host's last kept level is below 1 (never reported: no block). Else: envelope write, publisher switch under both locks, answer; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeHosts`, `finalizeBelow`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatNeedsEveryHostWithWorkOrAReportAndIsDurable`, `TestFinalizeFormatIgnoresAnIdleUnreportedHost`, `TestFinalizeFormatJudgesEveryServedVolume`, `TestFinalizeFormatJudgesAnIdleHostByItsLastLevel`, `TestTheLastReadLevelIsKeptInOrderAndFailsClosed`, `TestAFailedFinalizeWriteLeavesLevel0` (`core/host/master/format_gate_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE | | `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported server is placeable; no line is granted to a holder process before its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`, `grantTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE | | `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE | | `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |