master, volume, replication: a promotion survivor is the store its primary attested

The primary attests, in its heartbeat, the store id (superblock UUID) of
each replica counted toward its write ACKs. A probe round answer carries
the replica's store id; a candidate is ready only when that id is the one
its primary attested (a replaced or never-attested store is not a
survivor). The promotion line carries the probed store id, and the target
refuses a promotion whose store id is missing or is not its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-25 03:23:18 -08:00
1 parent 5fb4fccd85
commit 121a4ec5ed
32 files changed
+1994 -962

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ type PrimaryEvidence struct {
DurableLSN uint64
DataEpoch uint64 // the target's epoch-table row at DurableLSN
DataFirstLSN uint64
StoreID [16]byte // the probed store's id (its superblock UUID)
}
// ProbeResult is the outcome of a transport probe.
@@ -348,6 +348,7 @@ type VolumeStatus struct {
Path string // its store path under --durable-root
Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...)
ReplicaID string // the replica this store holds
StoreID string `json:",omitempty"` // the store's superblock UUID (hex); empty when it carries none
Epoch uint64 // the epoch the store is latched to; 0 before an assignment
EndpointVersion uint64 // the endpoint version it is latched to
Latched bool // an assignment latched the store (epoch and endpoint version set)
@@ -39,6 +39,7 @@ package durable
import (
"context"
"encoding/hex"
"errors"
"fmt"
"log"
@@ -356,7 +357,12 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
writeProfile.DirtyMapUpdateOps = storageProfile.DirtyMapUpdateOps
writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos
}
var storeID string
if id := storage.StoreIDOf(b.storage); !id.IsZero() {
storeID = hex.EncodeToString(id[:])
}
return VolumeStatus{
StoreID: storeID,
Warnings: warnings,
HolesSuspected: holes,
VolumeID: volumeID,
+4
View File
@@ -125,6 +125,7 @@ type Host struct {
probeHub *probeHub // the promotion probe round (probe_round.go)
probeSlots slotServers // replica -> server, for the round
cfg Config
attest *storeAttestations // primaries' attested write-ACK stores
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
log *log.Logger
boot *bootstrap.DurableAuthorityBootstrap
@@ -259,6 +260,9 @@ func New(cfg Config) (*Host, error) {
// now, or a first start would compare against an unknown device forever.
// An unknown identity (stat error, unsupported platform) never matches.
h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir))
if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil {
return nil, fmt.Errorf("master.New: %w", err)
}
var sink authority.ControllerSink = ctrl
if len(cfg.Topology.Volumes) == 0 {
@@ -54,7 +54,7 @@ func (f *fakeStatus) serve(t *testing.T) int {
_ = json.NewEncoder(w).Encode(body)
case "/status/durable":
_ = json.NewEncoder(w).Encode(map[string]any{"Volumes": []map[string]any{{
"VolumeID": "vol-rf3", "ReplicaID": f.replicaID, "FrontierKnown": true, "DurableLSN": 70,
"VolumeID": "vol-rf3", "ReplicaID": f.replicaID, "StoreID": testStoreHex, "FrontierKnown": true, "DurableLSN": 70,
}}})
default:
http.NotFound(w, r)
@@ -97,6 +97,7 @@ func useProductionProbe(t *testing.T, h *Host) (r1, r2 *fakeStatus) {
// it covers (#181): r2 reports durable 70.
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{
AckProfile: "sync-quorum",
Attested: attestEvery(testStoreID),
RequiredLSNByVolume: map[string]uint64{"vol-rf3": 70},
}))
return r1, r2
+18 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// The promotion probe round. When the master decides a promotion it mints a
@@ -113,6 +114,10 @@ type roundEvidenceProvider struct {
ackProfile string
required map[string]uint64
wait time.Duration
// attested is the store the volume's primary last attested for a
// replica (Host.AttestedStore); a candidate answering another store, or
// one never attested, is not Ready.
attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
func newRoundID() uint64 {
@@ -182,15 +187,26 @@ done:
continue
}
invalid := a.GetTablePresent() && !a.GetTableValid()
var store storage.StoreID
if len(a.GetStoreId()) == len(store) {
copy(store[:], a.GetStoreId())
}
attested := false
if p.attested != nil && !store.IsZero() {
want, ok := p.attested(volumeID, c.ReplicaID)
attested = ok && want == store
}
result.Candidates = append(result.Candidates, PromotionCandidateEvidence{
ReplicaID: c.ReplicaID,
DurableLSN: a.GetDurableEnd(),
LastDataEpoch: a.GetLastDataEpoch(),
LastDataFirstLSN: a.GetLastDataFirstLsn(),
TableInvalid: invalid,
StoreID: store,
// A promotion target answers as a ready replica, from a store
// whose epoch table is present and valid.
Ready: a.GetReplicaReady() && a.GetTablePresent() && a.GetTableValid(),
// whose epoch table is present and valid, and whose id is the
// store its primary attested (counted toward its write ACKs).
Ready: a.GetReplicaReady() && a.GetTablePresent() && a.GetTableValid() && attested,
})
}
return result, nil
@@ -47,7 +47,7 @@ func (h *Host) slotServer(volumeID, replicaID string) string {
// round: the ack profile and the required frontier from the workload plans'
// configuration, every candidate's evidence from this round's answers.
func (h *Host) NewRoundPromotionEvidenceProvider(ackProfile string, requiredLSNByVolume map[string]uint64) PromotionEvidenceProvider {
return &roundEvidenceProvider{hub: h.probeHub, serverOf: h.slotServer, ackProfile: ackProfile, required: cloneRequiredLSNMap(requiredLSNByVolume), wait: probeRoundWait}
return &roundEvidenceProvider{hub: h.probeHub, serverOf: h.slotServer, ackProfile: ackProfile, required: cloneRequiredLSNMap(requiredLSNByVolume), wait: probeRoundWait, attested: h.AttestedStore}
}
// SubscribeProbeRounds streams the probe rounds for the caller's node.
@@ -6,6 +6,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// roundNode is a node on the hub that answers its rounds with answer(round).
@@ -28,9 +29,18 @@ func roundNode(t *testing.T, hub *probeHub, serverID string, answer func(*contro
}()
}
// storeOf is the store id a replica's node answers with in these tests.
func storeOf(replicaID string) storage.StoreID {
return storage.StoreID{'s', byte(len(replicaID)), replicaID[len(replicaID)-1]}
}
// attestedAs is the primary's attestation: each replica on storeOf(replica).
func attestedAs(_, replicaID string) (storage.StoreID, bool) { return storeOf(replicaID), true }
func readyAnswer(server string) func(*control.ProbeRound) *control.ProbeAnswer {
return func(r *control.ProbeRound) *control.ProbeAnswer {
return &control.ProbeAnswer{ServerId: server, VolumeId: r.VolumeId, ReplicaId: r.ReplicaId, RoundId: r.RoundId,
id := storeOf(r.ReplicaId)
return &control.ProbeAnswer{ServerId: server, VolumeId: r.VolumeId, ReplicaId: r.ReplicaId, RoundId: r.RoundId, StoreId: id[:],
DurableEnd: 9, LastDataEpoch: 2, LastDataFirstLsn: 5, TablePresent: true, TableValid: true, ReplicaReady: true}
}
}
@@ -38,7 +48,7 @@ func readyAnswer(server string) func(*control.ProbeRound) *control.ProbeAnswer {
func TestProbeRound_CountsOnlyThisRoundsAnswersFromTheAskedNode(t *testing.T) {
hub := newProbeHub()
servers := map[string]string{"r2": "s2", "r3": "s3"}
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return servers[r] }, ackProfile: "sync-quorum", wait: 300 * time.Millisecond}
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return servers[r] }, ackProfile: "sync-quorum", wait: 300 * time.Millisecond, attested: attestedAs}
roundNode(t, hub, "s2", readyAnswer("s2"))
// s3 answers with an OLD round id (a report from before this decision),
@@ -46,7 +56,8 @@ func TestProbeRound_CountsOnlyThisRoundsAnswersFromTheAskedNode(t *testing.T) {
roundNode(t, hub, "s3", func(r *control.ProbeRound) *control.ProbeAnswer {
old := readyAnswer("s3")(r)
old.RoundId = r.RoundId + 1
hub.deliver(&control.ProbeAnswer{ServerId: "s3", VolumeId: r.VolumeId, ReplicaId: "r2", RoundId: r.RoundId, DurableEnd: 99, TablePresent: true, TableValid: true, ReplicaReady: true})
r2store := storeOf("r2")
hub.deliver(&control.ProbeAnswer{ServerId: "s3", VolumeId: r.VolumeId, ReplicaId: "r2", RoundId: r.RoundId, StoreId: r2store[:], DurableEnd: 99, TablePresent: true, TableValid: true, ReplicaReady: true})
return old
})
@@ -58,7 +69,7 @@ func TestProbeRound_CountsOnlyThisRoundsAnswersFromTheAskedNode(t *testing.T) {
for _, c := range res.Candidates {
got[c.ReplicaID] = c
}
if c := got["r2"]; !c.Ready || c.DurableLSN != 9 || c.LastDataEpoch != 2 || c.LastDataFirstLSN != 5 {
if c := got["r2"]; !c.Ready || c.DurableLSN != 9 || c.LastDataEpoch != 2 || c.LastDataFirstLSN != 5 || c.StoreID != storeOf("r2") {
t.Fatalf("r2 answered this round from its node: %+v", c)
}
if c := got["r3"]; c.Ready || c.DurableLSN != 0 {
@@ -68,7 +79,7 @@ func TestProbeRound_CountsOnlyThisRoundsAnswersFromTheAskedNode(t *testing.T) {
func TestProbeRound_InvalidTableOrNoAnswerIsNotReady(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return map[string]string{"r2": "s2", "r3": "s3"}[r] }, wait: 200 * time.Millisecond}
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return map[string]string{"r2": "s2", "r3": "s3"}[r] }, wait: 200 * time.Millisecond, attested: attestedAs}
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
a := readyAnswer("s2")(r)
a.TableValid = false // a recovery left its table invalid
@@ -86,6 +97,41 @@ func TestProbeRound_InvalidTableOrNoAnswerIsNotReady(t *testing.T) {
}
}
// A candidate is ready only on the store its primary attested (the store
// counted toward its write ACKs): another store (a replaced disk), no store id,
// or a replica never attested is not.
func TestProbeRound_OnlyTheAttestedStoreIsReady(t *testing.T) {
servers := map[string]string{"r2": "s2", "r3": "s3", "r4": "s4"}
for name, c := range map[string]struct {
attested func(string, string) (storage.StoreID, bool)
answer func(*control.ProbeAnswer)
ready bool
}{
"the attested store": {attestedAs, func(*control.ProbeAnswer) {}, true},
"another store": {attestedAs, func(a *control.ProbeAnswer) { a.StoreId = []byte("another-store-16") }, false},
"no store id": {attestedAs, func(a *control.ProbeAnswer) { a.StoreId = nil }, false},
"never attested": {func(string, string) (storage.StoreID, bool) { return storage.StoreID{}, false }, func(*control.ProbeAnswer) {}, false},
"no attestation source": {nil, func(*control.ProbeAnswer) {}, false},
} {
t.Run(name, func(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return servers[r] }, wait: 300 * time.Millisecond, attested: c.attested}
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
a := readyAnswer("s2")(r)
c.answer(a)
return a
})
res, err := p.ProbePromotionCandidates("v1", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2", ServerID: "s2"}})
if err != nil {
t.Fatal(err)
}
if len(res.Candidates) != 1 || res.Candidates[0].Ready != c.ready {
t.Fatalf("candidates=%+v; want ready=%t", res.Candidates, c.ready)
}
})
}
}
func TestProbeRound_ALateAnswerAfterTheRoundClosedIsDropped(t *testing.T) {
hub := newProbeHub()
r := hub.open(7, "v1")
@@ -2,6 +2,7 @@ package master
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/storage"
"reflect"
"strings"
@@ -35,6 +36,11 @@ type PromotionCandidateEvidence struct {
// TableInvalid: a recovery left the candidate's table without a known
// history; such a candidate is never Ready (never a promotion survivor).
TableInvalid bool
// StoreID is the candidate's probed store (its superblock UUID). A
// candidate is Ready only when it equals the store the volume's primary
// last attested for it (Host.AttestedStore): a replaced store, or one
// never attested, is not a survivor.
StoreID storage.StoreID
}
type PromotionProbeResult struct {
@@ -688,7 +694,7 @@ func promotionAllowedReplicas(result PromotionProbeResult, ok bool, peerCount in
func promotionEvidenceFor(result PromotionProbeResult, replicaID string) adapter.PrimaryEvidence {
for _, c := range result.Candidates {
if c.ReplicaID == replicaID {
return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: c.DurableLSN, DataEpoch: c.LastDataEpoch, DataFirstLSN: c.LastDataFirstLSN}
return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: c.DurableLSN, DataEpoch: c.LastDataEpoch, DataFirstLSN: c.LastDataFirstLSN, StoreID: c.StoreID}
}
}
return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion}
@@ -3,6 +3,8 @@ package master
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -59,6 +61,22 @@ func TestPromotionRefusesReplicaMissingAcknowledgedWrite(t *testing.T) {
if initial.ReplicaID != "r1" {
t.Fatalf("initial line=%+v", initial)
}
// The primary attests its write-ACK set: each replica with the store
// its barriers reported (the live ship above ran them).
// (the component cluster names its peers replica-0 and replica-1;
// the master's placement names them r2 and r3)
peers := cluster.Primary().RepVol.AttestedStores()
attested := map[string]storage.StoreID{"r1": cluster.Primary().RepVol.LocalStoreID()}
for i, id := range []string{"r2", "r3"} {
got := peers[fmt.Sprintf("replica-%d", i)]
if want := storage.StoreIDOf(cluster.Replica(i).Store); want.IsZero() || got != want {
t.Fatalf("primary attests replica-%d as %x, its store is %x", i, got, want)
}
attested[id] = got
}
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", initial.Epoch, attested)); err != nil {
t.Fatal(err)
}
if err := cluster.Primary().RepVol.Close(); err != nil {
t.Fatal(err)
}
@@ -75,7 +93,8 @@ func TestPromotionRefusesReplicaMissingAcknowledgedWrite(t *testing.T) {
// As the volume's /status/durable reports it: DurableLSN is
// R, the store's synced LSN (storage_adapter.go Boundaries).
r, _, _ := store.Boundaries()
_ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: r}}})
sid := storage.StoreIDOf(store)
_ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: r, StoreID: hex.EncodeToString(sid[:])}}})
default:
http.NotFound(w, r)
}
@@ -89,7 +108,7 @@ func TestPromotionRefusesReplicaMissingAcknowledgedWrite(t *testing.T) {
}
routes[host] = servers[i].URL
}
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", HTTPClient: &http.Client{Transport: promotionTraceRoutes(routes), Timeout: time.Second}}))
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", Attested: h.AttestedStore, HTTPClient: &http.Client{Transport: promotionTraceRoutes(routes), Timeout: time.Second}}))
ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", false, false, true, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
@@ -2,8 +2,10 @@ package master
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/storage"
"net"
"net/http"
"net/url"
@@ -22,6 +24,11 @@ type WorkloadPlanPromotionProbeConfig struct {
RequiredLSNByVolume map[string]uint64
ExternalStatus bool
HTTPClient *http.Client
// Attested is the store the volume's primary last attested for a
// replica (Host.AttestedStore). A candidate whose probed store differs,
// or that was never attested, is not Ready; nil attests nothing, so no
// candidate is Ready.
Attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
func NewWorkloadPlanPromotionEvidenceProvider(plans []lifecycle.BlockVolumeWorkloadPlan, cfg WorkloadPlanPromotionProbeConfig) PromotionEvidenceProvider {
@@ -58,6 +65,7 @@ func NewWorkloadPlanPromotionEvidenceProvider(plans []lifecycle.BlockVolumeWorkl
required: cloneRequiredLSNMap(cfg.RequiredLSNByVolume),
status: statusAddrs,
client: httpClient,
attested: cfg.Attested,
}
}
@@ -66,6 +74,7 @@ type workloadPlanPromotionEvidenceProvider struct {
required map[string]uint64
status map[string]map[string]string
client *http.Client
attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
func (p *workloadPlanPromotionEvidenceProvider) ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) {
@@ -132,6 +141,9 @@ func (p *workloadPlanPromotionEvidenceProvider) probeCandidate(volumeID, replica
ProbeAddr: statusAddr,
DurableLSN: best.DurableLSN,
}
if b, err := hex.DecodeString(best.StoreID); err == nil && len(b) == len(ev.StoreID) {
copy(ev.StoreID[:], b)
}
// The candidate's epoch-table row and table validity come from the
// authenticated probe round, not from /status (loopback-only under
// mutual TLS); until then the evidence carries none.
@@ -139,10 +151,23 @@ func (p *workloadPlanPromotionEvidenceProvider) probeCandidate(volumeID, replica
local.ReplicaID == replicaID &&
strings.EqualFold(local.ReplicationRole, "replica_ready") &&
best.FrontierKnown &&
!ev.TableInvalid
!ev.TableInvalid &&
p.storeAttested(volumeID, replicaID, ev.StoreID)
return ev, nil
}
// storeAttested reports whether probed is the store the volume's primary
// last attested for replicaID: a store the primary never counted toward its
// write ACKs (never attested, dropped, or a replacement with a new
// superblock) is not a survivor, whatever its own report says.
func (p *workloadPlanPromotionEvidenceProvider) storeAttested(volumeID, replicaID string, probed storage.StoreID) bool {
if p.attested == nil || probed.IsZero() {
return false
}
want, ok := p.attested(volumeID, replicaID)
return ok && want == probed
}
func (p *workloadPlanPromotionEvidenceProvider) probeCurrent(volumeID, replicaID, statusAddr string) (PromotionCandidateEvidence, error) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -32,7 +32,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_ProbesDurableFrontiers(t *testing
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -47,6 +47,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_ProbesDurableFrontiers(t *testing
ReplicaID: "r2", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
RequiredLSNByVolume: map[string]uint64{"vol-rf3": 52},
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
@@ -83,7 +84,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 90,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 90,
}}})
default:
http.NotFound(w, r)
@@ -98,6 +99,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
ReplicaID: "r2", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
})
@@ -114,6 +116,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
func TestWorkloadPlanPromotionEvidenceProvider_CurrentUnknownWithoutProbeAddress(t *testing.T) {
provider := NewWorkloadPlanPromotionEvidenceProvider(nil, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
})
result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{ReplicaID: "r1"}, nil)
@@ -141,7 +144,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_CurrentKnownAfterSuccessfulProbe(
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r1", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r1", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -156,6 +159,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_CurrentKnownAfterSuccessfulProbe(
ReplicaID: "r1", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
})
@@ -180,7 +184,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusUsesNodeAd
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -195,6 +199,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusUsesNodeAd
ReplicaID: "r2", DataAddr: "10.0.0.2:19103", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
ExternalStatus: true,
HTTPClient: rewriteHTTPClient(server.URL, "10.0.0.2:23260"),
@@ -220,6 +225,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusRejectsLoo
ReplicaID: "r2", DataAddr: "127.0.0.1:19103", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
ExternalStatus: true,
})
@@ -330,6 +330,12 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
}
// A primary's attestation of its write-ACK stores. Only the holder of
// the volume's current line is taken; a failed write fails the report,
// so the primary sends it again with its next heartbeat.
if err := s.host.ingestStoreAttestation(r.GetServerId(), r.GetStoreAttestation()); err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
return &control.HeartbeatAck{
AcceptedAt: timestamppb.Now(),
Sequence: s.seq.Add(1),
@@ -1007,6 +1013,10 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme
EvidenceEpoch: info.Primary.DataEpoch,
EvidenceFirstLsn: info.Primary.DataFirstLSN,
}
if info.Primary.StoreID != ([16]byte{}) {
id := info.Primary.StoreID
fact.EvidenceStoreId = id[:]
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
// topology. peer_set_generation is derived
@@ -0,0 +1,196 @@
package master
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// storeAttestationFile holds every volume's last primary attestation, in
// the authority store directory; it is replaced as a whole by one atomic
// write (temp file, fsync, rename, directory fsync).
const storeAttestationFile = "store-attestations.json"
// attestedStores is one volume's last attestation: the primary line that
// made it and, per replica, the store that counted toward its write ACKs.
type attestedStores struct {
Primary string `json:"primary"`
Epoch uint64 `json:"epoch"`
Stores map[string]string `json:"stores"` // replica id -> store id (hex)
}
// storeAttestations is the master's record of which store each replica
// counted toward write ACKs with, as the volume's primary attested it. It
// is the reference a promotion's probed store must equal: a replica's own
// report of its store never sets it, so a replaced store (an empty disk
// with a new superblock) is not taken for the store that acknowledged.
type storeAttestations struct {
mu sync.Mutex
path string // "" = memory only
vols map[string]attestedStores
}
func loadStoreAttestations(dir string) (*storeAttestations, error) {
s := &storeAttestations{vols: map[string]attestedStores{}}
if dir == "" {
return s, nil
}
s.path = filepath.Join(dir, storeAttestationFile)
b, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
return s, nil
}
if err != nil {
return nil, fmt.Errorf("store attestations: %w", err)
}
if err := json.Unmarshal(b, &s.vols); err != nil {
return nil, fmt.Errorf("store attestations %s: %w", s.path, err)
}
if s.vols == nil {
s.vols = map[string]attestedStores{}
}
return s, nil
}
// lookup returns the store the volume's primary last attested for replica;
// false when that replica is not in the attestation (never attested, or
// dropped from the write-ACK set since).
func (s *storeAttestations) lookup(volumeID, replicaID string) (storage.StoreID, bool) {
s.mu.Lock()
defer s.mu.Unlock()
h, ok := s.vols[volumeID].Stores[replicaID]
if !ok {
return storage.StoreID{}, false
}
var id storage.StoreID
b, err := hex.DecodeString(h)
if err != nil || len(b) != len(id) {
return storage.StoreID{}, false
}
copy(id[:], b)
return id, !id.IsZero()
}
// record replaces the volume's attestation with att, in one write. An
// attestation from a lower epoch than the recorded one is ignored (a
// deposed primary's late report); an unchanged one writes nothing.
func (s *storeAttestations) record(att *control.StoreAttestation) error {
next := attestedStores{Primary: att.GetReplicaId(), Epoch: att.GetEpoch(), Stores: map[string]string{}}
for _, st := range att.GetStores() {
var id storage.StoreID
if st.GetReplicaId() == "" || len(st.GetStoreId()) != len(id) {
return fmt.Errorf("store attestation for %s: malformed entry %q (%d bytes)", att.GetVolumeId(), st.GetReplicaId(), len(st.GetStoreId()))
}
copy(id[:], st.GetStoreId())
if id.IsZero() {
continue
}
next.Stores[st.GetReplicaId()] = hex.EncodeToString(id[:])
}
s.mu.Lock()
defer s.mu.Unlock()
cur, had := s.vols[att.GetVolumeId()]
if had && next.Epoch < cur.Epoch {
return nil
}
if had && sameAttestation(cur, next) {
return nil
}
vols := make(map[string]attestedStores, len(s.vols)+1)
for k, v := range s.vols {
vols[k] = v
}
vols[att.GetVolumeId()] = next
if err := s.persist(vols); err != nil {
return err
}
s.vols = vols
return nil
}
func sameAttestation(a, b attestedStores) bool {
if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) {
return false
}
for k, v := range a.Stores {
if b.Stores[k] != v {
return false
}
}
return true
}
func (s *storeAttestations) persist(vols map[string]attestedStores) error {
if s.path == "" {
return nil
}
payload, err := json.Marshal(vols)
if err != nil {
return err
}
temp := s.path + ".tmp"
f, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return fmt.Errorf("store attestations: %w", err)
}
_, werr := f.Write(payload)
if werr == nil {
werr = f.Sync()
}
if cerr := f.Close(); werr == nil {
werr = cerr
}
if werr == nil {
werr = os.Rename(temp, s.path)
}
if werr != nil {
_ = os.Remove(temp)
return fmt.Errorf("store attestations: %w", werr)
}
if runtime.GOOS == "windows" {
return nil // a directory cannot be fsynced there; the rename is the commit
}
d, err := os.Open(filepath.Dir(s.path))
if err != nil {
return fmt.Errorf("store attestations: directory: %w", err)
}
defer d.Close()
if err := d.Sync(); err != nil {
return fmt.Errorf("store attestations: directory fsync: %w", err)
}
return nil
}
// ingestStoreAttestation records a heartbeat's attestation when the
// reporting server holds the volume's published primary line at the
// attested epoch (the line's replica and owner). Anything else is not a
// primary's word and is dropped.
func (h *Host) ingestStoreAttestation(server string, att *control.StoreAttestation) error {
if att == nil || h.attest == nil {
return nil
}
vol := att.GetVolumeId()
line, published := h.Publisher().PublishedAuthorityLine(vol)
if !published || line.ReplicaID != att.GetReplicaId() || line.Epoch != att.GetEpoch() ||
h.workspaceLineOwner(line, vol, line.ReplicaID, line.Epoch) != server {
return nil
}
return h.attest.record(att)
}
// AttestedStore is the store the primary of volumeID last attested for
// replicaID (see storeAttestations).
func (h *Host) AttestedStore(volumeID, replicaID string) (storage.StoreID, bool) {
if h == nil || h.attest == nil {
return storage.StoreID{}, false
}
return h.attest.lookup(volumeID, replicaID)
}
@@ -0,0 +1,215 @@
package master
import (
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func attestation(vol, primary string, epoch uint64, stores map[string]storage.StoreID) *control.StoreAttestation {
att := &control.StoreAttestation{VolumeId: vol, ReplicaId: primary, Epoch: epoch}
for id, sid := range stores {
att.Stores = append(att.Stores, &control.AttestedStore{ReplicaId: id, StoreId: append([]byte(nil), sid[:]...)})
}
return att
}
func storeID(b byte) storage.StoreID {
var id storage.StoreID
for i := range id {
id[i] = b
}
return id
}
// rf3Primary publishes vol-rf3's first line (r1 on node-a) and returns it.
func rf3Primary(t *testing.T, h *Host) authority.AuthorityBasis {
t.Helper()
seedRF3Placement(t, h)
ingestRF3Observation(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-rf3")
if line.ReplicaID != "r1" {
t.Fatalf("initial line=%+v", line)
}
return line
}
// The reference store of a replica is set only by the volume's primary
// line holder at that line's epoch; a replica's own claim, a stale epoch or
// another server is dropped; a later attestation without a replica drops
// it; the record survives a master restart.
func TestStoreAttestationOnlyFromThePrimaryLine(t *testing.T) {
dir := t.TempDir()
h, err := New(Config{AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0",
ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() { closeTestMaster(t, h) })
line := rf3Primary(t, h)
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
for _, c := range []struct {
name, server, primary string
epoch uint64
}{
{"a replica's own claim", "node-b", "r2", line.Epoch},
{"the primary's replica id from another server", "node-b", "r1", line.Epoch},
{"another epoch", "node-a", "r1", line.Epoch + 1},
} {
if err := h.ingestStoreAttestation(c.server, attestation("vol-rf3", c.primary, c.epoch, map[string]storage.StoreID{"r2": s2})); err != nil {
t.Fatal(err)
}
if _, ok := h.AttestedStore("vol-rf3", "r2"); ok {
t.Fatalf("%s set the reference", c.name)
}
}
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil {
t.Fatal(err)
}
if got, ok := h.AttestedStore("vol-rf3", "r2"); !ok || got != s1 {
t.Fatalf("primary's attestation: r2 -> %x %t, want %x", got, ok, s1)
}
// r2 left the write-ACK set (its store was replaced, it is catching up).
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r3": t1})); err != nil {
t.Fatal(err)
}
if _, ok := h.AttestedStore("vol-rf3", "r2"); ok {
t.Fatal("a replica dropped from the primary's attestation is still attested")
}
reloaded, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if got, ok := reloaded.lookup("vol-rf3", "r3"); !ok || got != t1 {
t.Fatalf("after restart: r3 -> %x %t, want %x", got, ok, t1)
}
if _, ok := reloaded.lookup("vol-rf3", "r2"); ok {
t.Fatal("after restart: the dropped r2 is attested again")
}
}
// The loss schedule: r2 counted toward write ACKs with store S1; its disk
// is replaced (S2, empty) and its own reports say S2; the primary dies. The
// probe of r2 shows S2 with a durable LSN as good as r3's, so only the
// store check tells them apart: r2 is not a survivor, r3 (attested T1,
// probed T1) is promoted. With the required frontier unknown, the RF3
// quorum rule needs two survivors, so nothing is promoted.
func TestPromotionRefusesAReplacedStoreThePrimaryNeverAttested(t *testing.T) {
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
for _, c := range []struct {
name string
requiredKnown bool
r2Probed storage.StoreID
want string // "" = no promotion
wantNot string
}{
{"replaced store, frontier known", true, s2, "r3", "r2"},
{"replaced store, frontier unknown", false, s2, "", "r2"},
{"control: the attested store", true, s1, "", ""},
} {
t.Run(c.name, func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
t.Cleanup(func() { closeTestMaster(t, h) })
line := rf3Primary(t, h)
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil {
t.Fatal(err)
}
// r2's node reports its new store: never the reference.
if err := h.ingestStoreAttestation("node-b", attestation("vol-rf3", "r2", line.Epoch, map[string]storage.StoreID{"r2": s2})); err != nil {
t.Fatal(err)
}
probed := map[string]storage.StoreID{"r2": c.r2Probed, "r3": t1}
plans := []lifecycle.BlockVolumeWorkloadPlan{{VolumeID: "vol-rf3", Protocol: "iscsi"}}
routes := map[string]string{}
for i, id := range []string{"r2", "r3"} {
id, sid := id, probed[id]
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/status":
_ = json.NewEncoder(w).Encode(volume.StatusProjection{Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: id}, ReplicationRole: "replica_ready"})
case "/status/durable":
_ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: 100, StoreID: hex.EncodeToString(sid[:])}}})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
plans[0].Replicas = append(plans[0].Replicas, lifecycle.BlockVolumeReplicaWorkload{ReplicaID: id, ISCSIListenPort: 3260 + i})
routes[[]string{"127.0.0.1:23260", "127.0.0.1:23261"}[i]] = srv.URL
}
cfg := WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", Attested: h.AttestedStore,
HTTPClient: &http.Client{Transport: promotionTraceRoutes(routes), Timeout: time.Second}}
if c.requiredKnown {
cfg.RequiredLSNByVolume = map[string]uint64{"vol-rf3": 50}
}
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, cfg))
ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", false, false, true, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
issued := line
deadline := time.Now().Add(2 * time.Second)
for issued.Epoch <= line.Epoch && time.Now().Before(deadline) {
issued, _ = h.Publisher().VolumeAuthorityLine("vol-rf3")
time.Sleep(10 * time.Millisecond)
}
promoted := ""
if issued.Epoch > line.Epoch {
promoted = issued.ReplicaID
}
if c.wantNot != "" && promoted == c.wantNot {
t.Fatalf("promoted %s, whose probed store %x is not the attested %x", promoted, c.r2Probed, s1)
}
if c.want != "" && promoted != c.want {
t.Fatalf("promoted %q, want %s", promoted, c.want)
}
if c.name == "control: the attested store" && promoted != "r2" && promoted != "r3" {
t.Fatalf("control: promoted %q, want a survivor", promoted)
}
if c.want == "" && c.wantNot != "" && promoted != "" {
t.Fatalf("promoted %s with one attested survivor and an unknown frontier", promoted)
}
})
}
}
// A provider without the attestation lookup refuses every candidate.
func TestPromotionProbeWithoutAttestationIsNeverReady(t *testing.T) {
p := &workloadPlanPromotionEvidenceProvider{}
if p.storeAttested("v", "r2", storeID(1)) {
t.Fatal("no attestation lookup: a candidate was taken as attested")
}
p.attested = func(string, string) (storage.StoreID, bool) { return storageZero(), true }
if p.storeAttested("v", "r2", storage.StoreID{}) {
t.Fatal("an unknown probed store was taken as attested")
}
}
func storageZero() storage.StoreID { return storage.StoreID{} }
// testStoreID is the store every probe fixture reports, and attestEvery
// attests it for every replica: fixtures about other rules hold the store
// check true.
var testStoreID = storeID(0x5a)
var testStoreHex = hex.EncodeToString(testStoreID[:])
func attestEvery(id storage.StoreID) func(string, string) (storage.StoreID, bool) {
return func(string, string) (storage.StoreID, bool) { return id, true }
}
+56 -5
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
"sort"
"sync"
"sync/atomic"
"time"
@@ -16,6 +17,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/replication"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
@@ -173,7 +175,7 @@ type Host struct {
obsCli control.ObservationServiceClient
// probeRoles answers the promotion probe round's role fields (probe_round.go).
probeRoles probeRoles
asnCli control.AssignmentServiceClient
asnCli control.AssignmentServiceClient
cancel context.CancelFunc
wg sync.WaitGroup
@@ -662,9 +664,10 @@ func (h *Host) buildReport() *control.HeartbeatReport {
Reachable: true,
Eligible: true,
// Raw identity facts; the master compares them with its own store.
MachineId: h.cfg.StorageIdentity.MachineID,
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
MachineId: h.cfg.StorageIdentity.MachineID,
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
StoreAttestation: h.storeAttestation(),
Slots: []*control.HeartbeatSlot{
{
VolumeId: h.cfg.VolumeID,
@@ -682,6 +685,50 @@ func (h *Host) buildReport() *control.HeartbeatReport {
}
}
// storeAttester is the replication slot's view of its write-ACK set
// (replication.ReplicationVolume).
type storeAttester interface {
LocalStoreID() storage.StoreID
AttestedStores() map[string]storage.StoreID
}
// storeAttestation is this node's attestation of its write-ACK set while it
// holds the primary role (admitted, at its current epoch): its own store and
// every Healthy peer's last barrier store. nil on a replica, before the
// role is admitted, or while the local store carries no id.
func (h *Host) storeAttestation() *control.StoreAttestation {
h.selfFenceMu.Lock()
role, epoch := h.selfRole, h.selfEpoch
h.selfFenceMu.Unlock()
if role != selfRolePrimary || epoch == 0 {
return nil
}
if reason, _ := h.roleAdmissionFailed.Load().(string); reason != "" {
return nil
}
rv, ok := h.getReplication().(storeAttester)
if !ok || rv == nil {
return nil
}
own := rv.LocalStoreID()
if own.IsZero() {
return nil
}
att := &control.StoreAttestation{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, Epoch: epoch,
Stores: []*control.AttestedStore{{ReplicaId: h.cfg.ReplicaID, StoreId: append([]byte(nil), own[:]...)}}}
peers := rv.AttestedStores()
ids := make([]string, 0, len(peers))
for id := range peers {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
sid := peers[id]
att.Stores = append(att.Stores, &control.AttestedStore{ReplicaId: id, StoreId: append([]byte(nil), sid[:]...)})
}
return att
}
// newIncarnation returns a random process incarnation id.
func newIncarnation() string {
var b [8]byte
@@ -922,7 +969,11 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
if fr, ok := h.selfFenceFloor(); ok {
floor, floorErr = fr.EpochFloor()
}
if reason := checkPrimaryEvidence(fact, st, end, floor, floorErr == nil && floor > 0); reason != "" {
var store storage.StoreID
if sid, ok := rv.(interface{ LocalStoreID() storage.StoreID }); ok {
store = sid.LocalStoreID()
}
if reason := checkPrimaryEvidence(fact, st, end, floor, floorErr == nil && floor > 0, store); reason != "" {
h.refusePrimary(reason)
return
}
@@ -5,6 +5,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// primaryEvidenceSource is the local store's epoch table and durable end, as
@@ -31,7 +32,7 @@ type primaryEvidenceSource interface {
// single-replica workspace move starts from the published image and is
// governed by the layout's own start check and claim id instead. A store
// without an epoch table has no rows: a probed row cannot match it.
func checkPrimaryEvidence(fact *control.AssignmentFact, st replication.EpochTableStatus, end uint64, floor uint64, floorKnown bool) string {
func checkPrimaryEvidence(fact *control.AssignmentFact, st replication.EpochTableStatus, end uint64, floor uint64, floorKnown bool, store storage.StoreID) string {
if len(fact.Peers) == 0 {
return ""
}
@@ -62,6 +63,9 @@ func checkPrimaryEvidence(fact *control.AssignmentFact, st replication.EpochTabl
row.epoch, row.first = r.Epoch, r.FirstLSN
}
}
if len(fact.EvidenceStoreId) != len(store) || string(fact.EvidenceStoreId) != string(store[:]) {
return fmt.Sprintf("promoted at epoch %d on a probed store %x, this node's store is %x", fact.Epoch, fact.EvidenceStoreId, store[:])
}
if row.epoch != fact.EvidenceEpoch || row.first != fact.EvidenceFirstLsn {
return fmt.Sprintf("promoted at epoch %d on the probed row (epoch %d from %d) at LSN %d, the store's row there is (epoch %d from %d)",
fact.Epoch, fact.EvidenceEpoch, fact.EvidenceFirstLsn, fact.EvidenceDurableLsn, row.epoch, row.first)
@@ -6,6 +6,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
@@ -15,9 +16,11 @@ func TestCheckPrimaryEvidence(t *testing.T) {
rows := func(r ...transport.EpochRow) replication.EpochTableStatus {
return replication.EpochTableStatus{Rows: r, Present: true}
}
local := storage.StoreID{1, 2, 3}
promo := func(lsn, ep, first uint64) *control.AssignmentFact {
return &control.AssignmentFact{Epoch: 3, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_PROMOTION, EvidenceDurableLsn: lsn, EvidenceEpoch: ep, EvidenceFirstLsn: first}
return &control.AssignmentFact{Epoch: 3, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_PROMOTION, EvidenceDurableLsn: lsn, EvidenceEpoch: ep, EvidenceFirstLsn: first, EvidenceStoreId: local[:]}
}
onStore := func(f *control.AssignmentFact, id []byte) *control.AssignmentFact { f.EvidenceStoreId = id; return f }
for _, c := range []struct {
name string
fact *control.AssignmentFact
@@ -35,6 +38,8 @@ func TestCheckPrimaryEvidence(t *testing.T) {
{"promotion, store lower than probed", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 6, 2, "durable end"},
{"promotion, another row at the probed LSN", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 7}), 8, 2, "row"},
{"promotion over an invalid table", promo(8, 2, 5), replication.EpochTableStatus{Present: true, Invalid: true}, 8, 2, "invalid"},
{"promotion without the probed store id", onStore(promo(8, 2, 5), nil), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 8, 2, "store"},
{"promotion probed on another store", onStore(promo(8, 2, 5), []byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 8, 2, "store"},
{"promotion to a store replaced empty", promo(8, 2, 5), rows(), 0, 0, "durable end"},
{"forced", &control.AssignmentFact{Epoch: 3, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_FORCED}, rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}), 5, 2, ""},
{"no kind to a node with data", &control.AssignmentFact{Epoch: 3, Peers: peers}, rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}), 5, 2, "without a primary kind"},
@@ -43,7 +48,7 @@ func TestCheckPrimaryEvidence(t *testing.T) {
{"a single-replica line (no peers)", &control.AssignmentFact{Epoch: 3}, rows(), 5, 0, ""},
} {
t.Run(c.name, func(t *testing.T) {
got := checkPrimaryEvidence(c.fact, c.st, c.end, c.floor, c.floor > 0)
got := checkPrimaryEvidence(c.fact, c.st, c.end, c.floor, c.floor > 0, local)
switch {
case c.refused == "" && got != "":
t.Fatalf("refused: %s", got)
@@ -7,6 +7,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// The replica's side of the promotion probe round: it subscribes to the
@@ -87,6 +88,11 @@ func (h *Host) probeAnswer(round uint64) *control.ProbeAnswer {
}
}
}
if sid, ok := h.getReplication().(interface{ LocalStoreID() storage.StoreID }); ok && sid != nil {
if id := sid.LocalStoreID(); !id.IsZero() {
a.StoreId = id[:]
}
}
if roles, ok := h.probeRoles.Load().(probeRoleSource); ok && roles != nil {
a.ReplicaReady, a.PrimaryReady = roles()
}
@@ -347,8 +347,8 @@ func TestT4b6_BarrierWire_FullLineageEcho_StillEnforced(t *testing.T) {
}
sample.LastDataEpoch, sample.LastDataFirstLSN = 7, 31
encoded := transport.EncodeBarrierResp(sample)
if len(encoded) != 56 {
t.Fatalf("BarrierResp encoded length = %d; wire shape (56B = 32B lineage + 8B achievedLSN + 8B lastDataEpoch + 8B lastDataFirstLSN) regressed",
if len(encoded) != 72 {
t.Fatalf("BarrierResp encoded length = %d; wire shape (72B = 32B lineage + 8B achievedLSN + 8B lastDataEpoch + 8B lastDataFirstLSN + 16B storeID) regressed",
len(encoded))
}
+26
View File
@@ -16,6 +16,7 @@ import (
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
@@ -161,6 +162,10 @@ type ReplicaPeer struct {
mu sync.Mutex
state ReplicaState
closed bool
// storeID is the store the peer's last successful barrier reported,
// cleared whenever the peer leaves Healthy: a store is attested only
// by a barrier it answered while counting toward write ACKs.
storeID storage.StoreID
// onHealthy lets the owning ReplicationVolume reopen a terminal work
// queue only after recovery has returned this peer to Healthy.
onHealthy func()
@@ -689,6 +694,9 @@ func (p *ReplicaPeer) Barrier(ctx context.Context, targetLSN uint64) (transport.
}
log.Printf("replication: barrier ack peer=%s targetLSN=%d achievedLSN=%d",
p.target.ReplicaID, targetLSN, ack.AchievedLSN)
p.mu.Lock()
p.storeID = ack.StoreID
p.mu.Unlock()
return ack, nil
}
@@ -762,6 +770,9 @@ func (p *ReplicaPeer) SetState(next ReplicaState) {
return
}
p.state = next
if next != ReplicaHealthy {
p.storeID = storage.StoreID{}
}
onHealthy := p.onHealthy
p.mu.Unlock()
log.Printf("replication: peer %s state %s → %s", p.target.ReplicaID, prev, next)
@@ -770,6 +781,20 @@ func (p *ReplicaPeer) SetState(next ReplicaState) {
}
}
// AttestedStore is the store this peer counts toward write ACKs with: its
// last successful barrier's store id while the peer is Healthy. false while
// the peer is not Healthy, or no barrier has reported a store since it
// became Healthy (a peer healed without a barrier is attested by its next
// one).
func (p *ReplicaPeer) AttestedStore() (storage.StoreID, bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed || p.state != ReplicaHealthy || p.storeID.IsZero() {
return storage.StoreID{}, false
}
return p.storeID, true
}
func (p *ReplicaPeer) setOnHealthy(fn func()) {
p.mu.Lock()
p.onHealthy = fn
@@ -866,6 +891,7 @@ func (p *ReplicaPeer) Invalidate(reason string) {
return
}
p.state = ReplicaDegraded
p.storeID = storage.StoreID{}
p.mu.Unlock()
log.Printf("replication: peer %s invalidated (prev=%s, reason=%s)",
p.target.ReplicaID, prev, reason)
@@ -0,0 +1,64 @@
package replication
import (
"context"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// A peer attests the store its barrier reported, only while Healthy: a
// peer that leaves Healthy loses it, and one healed without a barrier is
// not attested until its next barrier answers.
func TestPeerAttestsTheStoreItsBarrierReported(t *testing.T) {
replicaStore, err := storage.CreateWALStore(filepath.Join(t.TempDir(), "r.wal"), 64, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = replicaStore.Close() })
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
exec := transport.NewBlockExecutor(storage.NewBlockStore(64, 4096), listener.Addr())
peer, err := NewReplicaPeer(ReplicaTarget{ReplicaID: "r2", DataAddr: listener.Addr(), ControlAddr: listener.Addr(), Epoch: 1, EndpointVersion: 1}, exec)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = peer.Close() })
want := storage.StoreIDOf(replicaStore)
if want.IsZero() {
t.Fatal("a WAL store carries no id")
}
if _, ok := peer.AttestedStore(); ok {
t.Fatal("attested before any barrier")
}
if _, err := peer.Barrier(context.Background(), 0); err != nil {
t.Fatal(err)
}
if got, ok := peer.AttestedStore(); !ok || got != want {
t.Fatalf("after a barrier: %x %t, want %x", got, ok, want)
}
peer.Invalidate("test: shipping failed")
if _, ok := peer.AttestedStore(); ok {
t.Fatal("a Degraded peer is still attested")
}
peer.SetState(ReplicaHealthy)
if peer.State() != ReplicaHealthy {
t.Fatalf("state %s, want Healthy", peer.State())
}
if _, ok := peer.AttestedStore(); ok {
t.Fatal("healed without a barrier, yet attested with the old store")
}
if _, err := peer.Barrier(context.Background(), 0); err != nil {
t.Fatal(err)
}
if got, ok := peer.AttestedStore(); !ok || got != want {
t.Fatalf("after the next barrier: %x %t, want %x", got, ok, want)
}
}
+21
View File
@@ -1106,6 +1106,27 @@ func replicationDurationNanos(d time.Duration) uint64 {
return uint64(d.Nanoseconds())
}
// LocalStoreID is the id of the store this volume replicates from (zero
// when the store carries none).
func (v *ReplicationVolume) LocalStoreID() storage.StoreID { return storage.StoreIDOf(v.store) }
// AttestedStores is the primary's attestation of its write-ACK set: each
// Healthy peer with the store its last barrier reported (replica id ->
// store id). A peer that is not Healthy, or has not answered a barrier
// since it became Healthy, is absent: the master never takes it as a
// survivor on this primary's word.
func (v *ReplicationVolume) AttestedStores() map[string]storage.StoreID {
v.mu.Lock()
defer v.mu.Unlock()
out := map[string]storage.StoreID{}
for id, peer := range v.peers {
if sid, ok := peer.AttestedStore(); ok {
out[id] = sid
}
}
return out
}
// PeerStatuses returns a stable, sorted diagnostic snapshot of all
// currently tracked peers. This is intentionally a status surface, not
// a control surface: callers cannot mutate the returned peer state.
File diff suppressed because it is too large. Load diff
@@ -139,6 +139,29 @@ message HeartbeatReport {
// first). 0 means unknown (older reporters, platforms without statfs):
// the master then compares machine_id and durable_root_dev only.
uint64 durable_root_fsid = 8;
// store_attestation is sent by a volume's primary only: the stores of
// the replicas that count toward its write ACKs. The master takes it as
// the reference a promotion's probed store must match, and only from
// the server that holds the volume's current primary line at that
// epoch. A replica's own report of its store never sets it.
StoreAttestation store_attestation = 9;
}
// StoreAttestation is a primary's attestation of its write-ACK set at one
// epoch: every replica in it with the store id (the store's superblock
// UUID) of the store that answered its barriers, the primary's own store
// included. A replica absent from it is not a survivor on this primary's
// word.
message StoreAttestation {
string volume_id = 1;
string replica_id = 2; // the primary's own replica id
uint64 epoch = 3; // the primary line's epoch
repeated AttestedStore stores = 4;
}
message AttestedStore {
string replica_id = 1;
bytes store_id = 2; // 16 bytes
}
// HeartbeatSlot — per-replica slot fact. local_role_claim is the
@@ -270,6 +293,9 @@ message AssignmentFact {
uint64 evidence_durable_lsn = 11;
uint64 evidence_epoch = 12;
uint64 evidence_first_lsn = 13;
// The probed store's id (its superblock UUID, 16 bytes): the target
// adopts a promotion only on that same store.
bytes evidence_store_id = 14;
}
// PrimaryKind is how a line made its primary the primary.
@@ -563,3 +563,6 @@ func (s *Store) SyncCount() uint64 { return s.syncs.Load() }
// Compile-time assertion: Store satisfies the LogicalStorage contract.
var _ storage.LogicalStorage = (*Store)(nil)
// StoreID returns the header UUID written when the store was created.
func (s *Store) StoreID() storage.StoreID { return storage.StoreID(s.hdr.UUID) }
+27
View File
@@ -0,0 +1,27 @@
package storage
// StoreID is a local store's identity: the 16 random bytes its superblock
// was given when the store was created. A store re-created at the same path
// has a new one, so equal ids mean the same store, never a copy or a
// replacement. The zero value means unknown.
type StoreID [16]byte
// IsZero reports whether the id is unknown.
func (id StoreID) IsZero() bool { return id == StoreID{} }
// storeIdentified is implemented by stores that carry a superblock UUID.
type storeIdentified interface {
StoreID() StoreID
}
// StoreIDOf returns s's store id, or the zero id when s does not carry one.
func StoreIDOf(s LogicalStorage) StoreID {
if si, ok := s.(storeIdentified); ok {
return si.StoreID()
}
return StoreID{}
}
// StoreID returns the superblock UUID written when the store was created
// (both on-disk formats carry it).
func (s *WALStore) StoreID() StoreID { return StoreID(s.sb.UUID) }
+30 -12
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"net"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// BarrierAck is the validated per-peer barrier outcome surfaced to
@@ -17,12 +19,15 @@ import (
// Reason is populated by higher-layer aggregation (DurabilityCoordinator)
// and is empty on successful Barrier returns.
type BarrierAck struct {
Lineage RecoveryLineage
AchievedLSN uint64
Lineage RecoveryLineage
AchievedLSN uint64
LastDataEpoch uint64 // the replica's last data row's epoch; 0 = no table (see BarrierResponse)
LastDataFirstLSN uint64 // that row's first LSN
Success bool
Reason string
// StoreID is the replica's store identity (its superblock UUID); zero
// from a replica that does not report one.
StoreID storage.StoreID
Success bool
Reason string
}
// ErrBarrierLineageMismatch is returned by BlockExecutor.Barrier when
@@ -43,8 +48,10 @@ var ErrBarrierLineageMismatch = errors.New("transport: barrier: response lineage
// rule, INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK).
//
// Wire: [32B lineage][8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN]
// — 56 bytes. A 40-byte response (a replica from before the epoch table)
// decodes with LastDataEpoch 0, which the primary reads as "no table".
// [16B storeID] — 72 bytes. A 40-byte response (a replica from before the
// epoch table) decodes with LastDataEpoch 0, which the primary reads as "no
// table"; a 56-byte one (before the store id) with a zero StoreID, which the
// primary reads as "unknown store" and never attests.
// Lineage field order inside the 32B slab is strictly
// SessionID, Epoch, EndpointVersion, frontierHint (matches
// EncodeLineage). Any deviation MUST be rejected at decode.
@@ -58,27 +65,35 @@ type BarrierResponse struct {
// LastDataFirstLSN is that row's first LSN: the primary requires it to
// equal its own first LSN for the epoch (the receiver check).
LastDataFirstLSN uint64
// StoreID is the replica's store identity: the superblock UUID of the
// store that synced AchievedLSN. The primary reports it to the master
// when this replica counts toward write ACKs; zero = unknown.
StoreID storage.StoreID
}
// barrierRespSize is the exact byte length of a valid encoded
// BarrierResponse. Short, over-long, or field-misordered payloads
// are rejected by DecodeBarrierResp and MUST NOT contribute to
// correctness decisions (round-21 rule).
const barrierRespSize = 56
const barrierRespSize = 72
// barrierRespV0Size is the response of a replica from before the epoch table.
const barrierRespV0Size = 40
// barrierRespV1Size is the response of a replica from before the store id.
const barrierRespV1Size = 56
// EncodeBarrierResp serializes a barrier response.
// Wire: [32B lineage (SessionID, Epoch, EndpointVersion, frontierHint)]
//
// [8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN]
// [8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN][16B storeID]
func EncodeBarrierResp(r BarrierResponse) []byte {
buf := make([]byte, barrierRespSize)
copy(buf[0:32], EncodeLineage(r.Lineage))
binary.BigEndian.PutUint64(buf[32:40], r.AchievedLSN)
binary.BigEndian.PutUint64(buf[40:48], r.LastDataEpoch)
binary.BigEndian.PutUint64(buf[48:56], r.LastDataFirstLSN)
copy(buf[56:72], r.StoreID[:])
return buf
}
@@ -93,9 +108,9 @@ func EncodeBarrierResp(r BarrierResponse) []byte {
// Callers MUST treat any error return as "no valid ack" and MUST NOT
// fabricate a frontier or count the ack toward durability.
func DecodeBarrierResp(buf []byte) (BarrierResponse, error) {
if len(buf) < barrierRespV0Size || (len(buf) > barrierRespV0Size && len(buf) < barrierRespSize) {
return BarrierResponse{}, fmt.Errorf("transport: short barrier response: %d bytes, want %d (or %d from a replica without the epoch table)",
len(buf), barrierRespSize, barrierRespV0Size)
if len(buf) != barrierRespV0Size && len(buf) != barrierRespV1Size && len(buf) < barrierRespSize {
return BarrierResponse{}, fmt.Errorf("transport: short barrier response: %d bytes, want %d (or %d without the store id, %d without the epoch table)",
len(buf), barrierRespSize, barrierRespV1Size, barrierRespV0Size)
}
lineage, err := DecodeLineage(buf[0:32])
if err != nil {
@@ -114,10 +129,13 @@ func DecodeBarrierResp(buf []byte) (BarrierResponse, error) {
Lineage: lineage,
AchievedLSN: binary.BigEndian.Uint64(buf[32:40]),
}
if len(buf) >= barrierRespSize {
if len(buf) >= barrierRespV1Size {
resp.LastDataEpoch = binary.BigEndian.Uint64(buf[40:48])
resp.LastDataFirstLSN = binary.BigEndian.Uint64(buf[48:56])
}
if len(buf) >= barrierRespSize {
copy(resp.StoreID[:], buf[56:72])
}
return resp, nil
}
+21 -1
View File
@@ -5,6 +5,7 @@ package transport
import (
"encoding/binary"
"github.com/seaweedfs/seaweed-block/core/storage"
"strings"
"testing"
)
@@ -83,11 +84,30 @@ func TestBarrierResp_FullLineageEcho_RoundTrip(t *testing.T) {
// callers could count toward durability.
//
// Required test per mini-plan §2 T4b-1.
// The barrier reply carries the replica's store id; a 56-byte reply (a
// replica from before the store id) decodes with the zero id, "unknown".
func TestBarrierResp_StoreID(t *testing.T) {
lin := RecoveryLineage{SessionID: 7, Epoch: 3, EndpointVersion: 2, TargetLSN: 40}
id := storage.StoreID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
buf := EncodeBarrierResp(BarrierResponse{Lineage: lin, AchievedLSN: 40, LastDataEpoch: 3, LastDataFirstLSN: 9, StoreID: id})
if len(buf) != barrierRespSize {
t.Fatalf("encoded %d bytes, want %d", len(buf), barrierRespSize)
}
got, err := DecodeBarrierResp(buf)
if err != nil || got.StoreID != id || got.AchievedLSN != 40 || got.LastDataFirstLSN != 9 {
t.Fatalf("round trip: %+v %v", got, err)
}
old, err := DecodeBarrierResp(buf[:barrierRespV1Size])
if err != nil || !old.StoreID.IsZero() || old.LastDataEpoch != 3 {
t.Fatalf("56-byte reply: %+v %v; want the rows and a zero store id", old, err)
}
}
func TestBarrierResp_ShortPayload_Rejected(t *testing.T) {
// Every length below the full response except the 40-byte response of
// a replica from before the epoch table (TestT4b6 decodes that one).
for n := 0; n < barrierRespSize; n++ {
if n == barrierRespV0Size {
if n == barrierRespV0Size || n == barrierRespV1Size {
continue
}
t.Run("", func(t *testing.T) {
+4 -3
View File
@@ -571,11 +571,12 @@ func (e *BlockExecutor) Barrier(replicaID string, lineage RecoveryLineage, front
}
return BarrierAck{
Lineage: resp.Lineage,
AchievedLSN: resp.AchievedLSN,
Lineage: resp.Lineage,
AchievedLSN: resp.AchievedLSN,
LastDataEpoch: resp.LastDataEpoch,
LastDataFirstLSN: resp.LastDataFirstLSN,
Success: true,
StoreID: resp.StoreID,
Success: true,
}, nil
}
+2
View File
@@ -637,6 +637,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
AchievedLSN: frontier,
LastDataEpoch: r.epochs.LastDataRowAt(frontier).Epoch,
LastDataFirstLSN: r.epochs.LastDataRowAt(frontier).FirstLSN,
StoreID: storage.StoreIDOf(r.store),
})
replyType, reply = MsgBarrierResp, resp
return true
@@ -690,6 +691,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
AchievedLSN: frontier,
LastDataEpoch: r.epochs.LastDataRowAt(frontier).Epoch,
LastDataFirstLSN: r.epochs.LastDataRowAt(frontier).FirstLSN,
StoreID: storage.StoreIDOf(r.store),
})
replyType, reply = MsgBarrierResp, resp
+1
View File
@@ -77,6 +77,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Path` | string | its store path under --durable-root |
| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) |
| `Volumes[].ReplicaID` | string | the replica this store holds |
| `Volumes[].StoreID` | string | the store's superblock UUID (hex); empty when it carries none (omitted when empty) |
| `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment |
| `Volumes[].EndpointVersion` | uint64 | the endpoint version it is latched to |
| `Volumes[].Latched` | bool | an assignment latched the store (epoch and endpoint version set) |