format gate: per-process read levels, the publication boundary checks them, the clamped grant stays monotonic

A server's per-volume processes may run different binaries: the read
level is kept per process (its heartbeat slot's incarnation) and a server
reads the lowest any of its processes reported within the freshness
window. A heartbeat is judged on its own process's level.

The final publication boundary and the promotion gate check the target
server's current level, so an ask decided before an old process reported
is not published.

A level-0 grant clamped to the horizon is now + the time left to it, so
the deadline (read by the level-1 barrier after a finalize) keeps the
monotonic reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 20:01:10 -08:00
1 parent 349fc1ba5a
commit fadc4f0345
8 files changed
+226 -24

No files matched your search

@@ -5,6 +5,8 @@ import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
@@ -124,7 +126,7 @@ func TestTheForcedBarrierFollowsTheFormatLevel(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
p.CloseWorkspaceExtenders() // horizon stays t=45
p.CloseWorkspaceExtenders() // horizon stays t=45
bindAndGrant(t, p, "v", "r") // deadline t=30, horizon t=45, skew 4
c.at(40)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
@@ -165,3 +167,34 @@ func TestTheForcedBarrierFollowsTheFormatLevel(t *testing.T) {
t.Fatalf("after the finalize at t=54 (level 0 would wait for the horizon t=65 plus skew): %v", err)
}
}
// A clamped level-0 grant raises the deadline with this process's monotonic
// reading, so the level-1 barrier after a finalize (with no renewal after
// it) cannot be moved by a wall-clock step (codex01's AMEND P1 1).
func TestAClampedLevel0GrantKeepsTheMonotonicReading(t *testing.T) {
disk, _ := newTempStore(t)
base := time.Now() // monotonic
var offset atomic.Int64
clock := func() time.Time { return base.Add(time.Duration(offset.Load())) }
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, clock), WithWorkspaceMaxClockSkew(4*time.Second), WithFormatLevel(0))
p.CloseWorkspaceExtenders() // no extension: the horizon stays first grant + 45 s
bindAndGrant(t, p, "v", "r")
offset.Store(int64(20 * time.Second))
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil {
t.Fatal(err)
}
if want := base.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
t.Fatalf("renewal at +20 s: grant %d, want the horizon %d (clamped)", l.ExpiresAtNS, want)
}
p.FinalizeFormatLevel()
p.mu.Lock()
d := p.leaseDeadlineLocked("v")
p.mu.Unlock()
if !strings.Contains(d.String(), "m=") {
t.Fatalf("the clamped deadline %s has no monotonic reading: a wall-clock step after the finalize would move the barrier", d)
}
if !d.Equal(base.Add(45 * time.Second)) {
t.Fatalf("the clamped deadline %s, want base + 45 s", d)
}
}
@@ -104,7 +104,11 @@ func (p *Publisher) forcedMoveBarrierV100Locked(lease *WorkspaceLease, deadline
func (p *Publisher) renewV100Locked(volume, holder string, epoch uint64, lv *leaseView, now time.Time) (WorkspaceLease, error) {
grant := now.Add(p.workspaceTTL)
if h := time.Unix(0, lv.d.horizon); grant.After(h) {
grant = h
// Clamped to the horizon, as the time left to it from now: the grant
// (and the deadline it raises, which the level-1 barrier reads after
// a finalize) keeps now's monotonic reading, so a wall-clock step
// cannot move it.
grant = now.Add(h.Sub(now))
}
// A grant without positive host validity would make the host fence on an
// invalid reply; refuse with an error instead.
+75 -14
View File
@@ -8,6 +8,7 @@ import (
"strings"
"sync"
"sync/atomic"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
@@ -15,29 +16,89 @@ import (
"google.golang.org/grpc/status"
)
// readsLevels holds each server's reported format read level (its latest
// heartbeat's reads_level), in memory only. A registered server with no
// report since this master started reads level 0: unknown counts as old, so
// a silent host never lets the format be finalized past it.
// readsLevels holds the format read level each reporting process of a
// server sent (its latest heartbeat's reads_level), in memory only. One
// server id is shared by its per-volume processes, which may run different
// binaries, so a server reads the lowest level any of its processes reported
// within the freshness window (a process silent longer has gone). A
// registered server with no such report reads level 0: unknown counts as
// old, so a silent host never lets the format be finalized past it.
type readsLevels struct {
mu sync.Mutex
level map[string]uint32
mu sync.Mutex
window time.Duration
now func() time.Time
procs map[string]map[string]procLevel // server -> process -> report
}
func newReadsLevels() *readsLevels { return &readsLevels{level: map[string]uint32{}} }
type procLevel struct {
level uint32
seen time.Time
}
func (r *readsLevels) note(server string, level uint32) {
func newReadsLevels(window time.Duration) *readsLevels {
return &readsLevels{window: window, now: time.Now, procs: map[string]map[string]procLevel{}}
}
// note records the level process (of server) reported now.
func (r *readsLevels) note(server, process string, level uint32) {
r.mu.Lock()
defer r.mu.Unlock()
r.level[server] = level
if r.procs[server] == nil {
r.procs[server] = map[string]procLevel{}
}
r.procs[server][process] = procLevel{level: level, seen: r.now()}
}
// of is server's reported read level and whether it has reported.
// of is the lowest level server's processes reported within the window,
// and whether any did.
func (r *readsLevels) of(server string) (uint32, bool) {
r.mu.Lock()
defer r.mu.Unlock()
l, ok := r.level[server]
return l, ok
cutoff := r.now().Add(-r.window)
var low uint32
found := false
for p, e := range r.procs[server] {
if e.seen.Before(cutoff) {
delete(r.procs[server], p)
continue
}
if !found || e.level < low {
low, found = e.level, true
}
}
return low, found
}
// below names server's processes that reported a level below level within
// the window, sorted, each as "process (reads level N)".
func (r *readsLevels) below(server string, level uint32) []string {
r.mu.Lock()
defer r.mu.Unlock()
cutoff := r.now().Add(-r.window)
var out []string
for p, e := range r.procs[server] {
if !e.seen.Before(cutoff) && e.level < level {
out = append(out, fmt.Sprintf("%s (reads level %d)", p, e.level))
}
}
sort.Strings(out)
return out
}
// heartbeatProcess names the reporting process of a heartbeat: its slot's
// incarnation (new on every process start), else its slot's data address.
func heartbeatProcess(slots []*control.HeartbeatSlot) string {
for _, s := range slots {
if s.GetIncarnation() != "" {
return s.GetIncarnation()
}
}
for _, s := range slots {
if s.GetDataAddr() != "" {
return s.GetDataAddr()
}
}
return ""
}
// formatLevelState is the cluster's format level in memory: 0 until the
@@ -69,7 +130,7 @@ func (h *Host) formatTooOld(server string) string {
if !ok {
return fmt.Sprintf("node %q has not reported its format read level; the cluster's format level is %d", server, h.formatLevel())
}
return fmt.Sprintf("node %q reads format level %d; the cluster's format level is %d (binary_too_old)", server, reads, h.formatLevel())
return fmt.Sprintf("node %q reads format level %d (the lowest of its processes); the cluster's format level is %d (binary_too_old)", server, reads, h.formatLevel())
}
// belowLevel lists the given servers whose reported read level is below
@@ -82,7 +143,7 @@ func (h *Host) belowLevel(servers []string, level uint32) []string {
case !ok:
out = append(out, fmt.Sprintf("%s (no report)", s))
case reads < level:
out = append(out, fmt.Sprintf("%s (reads level %d)", s, reads))
out = append(out, fmt.Sprintf("%s (process %s)", s, strings.Join(h.reads.below(s, level), ", ")))
}
}
sort.Strings(out)
@@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
@@ -175,7 +176,7 @@ func TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable(t *testing.T) {
for _, step := range []struct {
reads *uint32
want string
}{{nil, "node-b (no report)"}, {ptr(uint32(0)), "node-b (reads level 0)"}} {
}{{nil, "node-b (no report)"}, {ptr(uint32(0)), "node-b (process 127.0.0.1:19311 (reads level 0))"}} {
if step.reads != nil {
if err := r.fgHeartbeat("node-b", *step.reads); err != nil {
t.Fatal(err)
@@ -280,3 +281,99 @@ func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
}
}
// fgProcessHeartbeat sends a heartbeat of one of server's processes (its
// incarnation) for vol, reporting reads.
func (r *isolationRig) fgProcessHeartbeat(server, incarnation, vol string, reads uint32) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: reads,
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r-" + incarnation, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1], Incarnation: incarnation}}})
return err
}
// One server id is shared by its per-volume processes, which may run
// different binaries: an old process's level 0 is not hidden by a new
// process's later level 1. The finalize is refused naming the old process;
// at level 1 the server takes no new work while the old process is live,
// and the new process's own heartbeat is taken (FormatGate: a host is a
// process; codex01's AMEND P1 3).
func TestAServerReadsTheLowestLevelOfItsProcesses(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc (reads level 0)") {
t.Fatalf("finalize with an old process beside a new one on node-b: %v", err)
}
r.m.format.v.Store(1)
if r.m.formatEligible("node-b") {
t.Fatal("level 1: node-b is eligible while its old process is live")
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatalf("level 1: the new process's own heartbeat was refused: %v", err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); !binaryTooOld(err) {
t.Fatalf("level 1: the old process's heartbeat: %v", err)
}
}
// A process silent longer than the freshness window has gone: it no longer
// holds its server's level down.
func TestAGoneProcessNoLongerHoldsItsServersLevel(t *testing.T) {
rl := newReadsLevels(time.Minute)
now := time.Unix(1000, 0)
rl.now = func() time.Time { return now }
rl.note("s", "old", 0)
rl.note("s", "new", 1)
if l, ok := rl.of("s"); !ok || l != 0 {
t.Fatalf("both live: level %d %v, want 0", l, ok)
}
now = now.Add(2 * time.Minute)
rl.note("s", "new", 1)
if l, ok := rl.of("s"); !ok || l != 1 {
t.Fatalf("the old process silent past the window: level %d %v, want 1", l, ok)
}
}
// A bind decided on a server's observations is not published once another
// of that server's processes reports a lower read level: the publication
// boundary judges the server's current capability (codex01's AMEND P1 2).
// The control, with no old process, binds.
func TestAPublicationToAServerThatTurnedOutOldIsRefused(t *testing.T) {
for _, old := range []bool{true, false} {
t.Run(map[bool]string{true: "old-process", false: "control"}[old], func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if old {
if err := r.fgProcessHeartbeat("node-b", "old-proc", "other", 0); err != nil {
t.Fatal(err)
}
}
r.m.format.v.Store(1)
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 1,
Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302", Incarnation: "new-proc", Reachable: true, Eligible: true}}}); err != nil {
t.Fatal(err)
}
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
bound := false
for end := time.Now().Add(3 * time.Second); time.Now().Before(end) && !bound; time.Sleep(50 * time.Millisecond) {
_, bound = r.m.Publisher().VolumeAuthorityLine("v")
}
if old && bound {
t.Fatal("v was bound on node-b while an old process of node-b is live at level 1")
}
if !old && !bound {
t.Fatal("control: v was not bound on node-b, whose only process reads level 1")
}
})
}
}
+1 -1
View File
@@ -270,7 +270,7 @@ func New(cfg Config) (*Host, error) {
topo: cfg.Topology,
events: newEventRing(1024),
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
reads: newReadsLevels(),
reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()),
}
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
@@ -304,7 +304,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
h.holdCreating(vol, why)
continue
}
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex)
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) && h.formatEligible(vol.Slots[currentIdx].ServerID)
// A fencing round fenced survivors above this line and nothing was
// published: they refuse the primary at its epoch (and may no longer
// look ready), so heal before anything else while it is acceptable.
@@ -319,7 +319,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
for _, slot := range vol.Slots {
if slot.ReplicaID != vol.Authority.ReplicaID {
candidates = append(candidates, slot)
if candidateAcceptableForPromotionGate(slot, serverIndex) {
if candidateAcceptableForPromotionGate(slot, serverIndex) && h.formatEligible(slot.ServerID) {
readyCandidate = true
}
}
+6 -4
View File
@@ -537,11 +537,13 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.refuseServerIDFromOtherHost(r); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
// The format gate: the server's read level, recorded before it is
// judged; a binary that cannot read the cluster's format level is
// The format gate: the reporting process's read level, recorded before
// it is judged (its server then reads at most that level for new work);
// a process whose binary cannot read the cluster's format level is
// refused, so it is never observed as a candidate.
s.host.reads.note(r.GetServerId(), r.GetReadsLevel())
if why := s.host.formatTooOld(r.GetServerId()); why != "" {
s.host.reads.note(r.GetServerId(), heartbeatProcess(r.GetSlots()), r.GetReadsLevel())
if level := s.host.formatLevel(); r.GetReadsLevel() < level {
why := fmt.Sprintf("node %q process reads format level %d; the cluster's format level is %d (binary_too_old)", r.GetServerId(), r.GetReadsLevel(), level)
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "heartbeat refused: "+why), lifecycleclient.ReasonBinaryTooOld).Err()
}
msg := heartbeatFromWire(r)
@@ -277,6 +277,11 @@ func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish fu
epoch = line.Epoch
}
server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch)
// The format gate at the last boundary: an ask decided on observations
// taken before its server reported a lower read level is not published.
if why := h.formatTooOld(server); why != "" {
return fmt.Errorf("workspace publication: %s", why)
}
b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}
if bound {
matched := false