Merge pull request #470 from seaweedfs/train/20261123-29

release: OSS train 29 (heartbeat order per slot #453; permanent recovery cause at the guest gate #464; delete refusal names its cure #448; fork deadline before metadata writes #454)
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-22 21:51:25 -08:00
commit 329ded8fae
15 files changed
+527 -49

No files matched your search

@@ -2,6 +2,7 @@ package authority
import (
"errors"
"log"
"sort"
"sync"
"time"
@@ -10,7 +11,7 @@ import (
// ============================================================
// P14 S4 — Observation Store
//
// Push-ingested latest-wins observation store per ServerID. The
// Push-ingested latest-wins observation store per replica slot. The
// store computes derived freshness on read, based on wall-clock
// time vs ObservedAt + FreshnessWindow. Expired observations stay
// visible; they are just semantically ineligible for supported
@@ -35,18 +36,19 @@ type ObservationStore struct {
revision uint64
onMutation func()
// supersededCount counts heartbeat ingests that were dropped
// because a newer ObservedAt was already stored for the same
// ServerID. Diagnostic only — PCDD-DELAYED-HB-001 evidence
// supersededCount counts slot reports that were dropped because a
// newer ObservedAt was stored for that server/volume/replica slot.
// Diagnostic only — PCDD-DELAYED-HB-001 evidence
// surface. Not an authority input; publisher / controller /
// evidence minting paths MUST NOT read it. Exposed via
// SupersededCount().
supersededCount uint64
supersededSlots map[[3]string]uint64
}
// SupersededCount returns the total number of ingests that were
// dropped because a newer observation from the same server was
// already stored. Diagnostic surface for PCDD-DELAYED-HB-001.
// SupersededCount returns the total number of slot reports dropped
// because a newer report of that same server/volume/replica was stored.
// Diagnostic surface for PCDD-DELAYED-HB-001.
// NOT authority input. Monotonic across the lifetime of the store.
func (s *ObservationStore) SupersededCount() uint64 {
s.mu.Lock()
@@ -54,6 +56,14 @@ func (s *ObservationStore) SupersededCount() uint64 {
return s.supersededCount
}
// SupersededSlotCount is the diagnostic count for one reporting slot.
// Like SupersededCount, it is not an authority input.
func (s *ObservationStore) SupersededSlotCount(serverID, volumeID, replicaID string) uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.supersededSlots[[3]string{serverID, volumeID, replicaID}]
}
// SlotFact returns the most-recently-observed SlotFact for a
// (volumeID, replicaID) pair across all reporting servers, or
// (zero, false) if no server has reported that slot.
@@ -201,10 +211,11 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat
}
cfg := config.withDefaults()
return &ObservationStore{
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
supersededSlots: make(map[[3]string]uint64),
}
}
@@ -231,11 +242,10 @@ var ErrInvalidObservation = errors.New("observation_store: invalid observation")
// ExpiresAt, and fires the registered mutation callback if
// anything changed.
//
// Latest-wins per ServerID. If an incoming observation has an
// ObservedAt strictly older than the currently-stored one from
// the same server, the store keeps the newer one (ignores the
// stale ingest). No error is returned for that case; it's a
// routine ordering event, not a bug.
// Latest-wins per (ServerID, volume, replica). A slot report strictly
// older than that slot's stored fact is ignored; other slots in the
// observation are accepted independently. No error is returned for
// superseded reports.
func (s *ObservationStore) Ingest(obs Observation) error {
_, err := s.ingest(obs)
return err
@@ -290,44 +300,65 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro
var fn func()
var transitions []SlotHealthTransition
type supersededReport struct {
volume, replica string
sentAt, newest time.Time
total uint64
}
var dropped []supersededReport
// Both the all-superseded and mixed-report paths release mu before
// returning. Logging never runs under the store lock.
defer func() {
for _, d := range dropped {
log.Printf("heartbeat superseded server=%s volume=%s replica=%s sent_at=%s newest=%s total=%d",
obs.ServerID, d.volume, d.replica, d.sentAt.UTC().Format(time.RFC3339Nano), d.newest.UTC().Format(time.RFC3339Nano), d.total)
}
}()
s.mu.Lock()
prev, hadPrev := s.observations[obs.ServerID]
if hadPrev {
if prev.ObservedAt.After(obs.ObservedAt) {
// Out-of-order ingest: keep the newer one already
// stored. No mutation fired.
//
// Diagnostic counter for PCDD-DELAYED-HB-001. Not an
// authority input. Must never be read by publisher /
// controller / evidence minting path — it exists so
// tests and operators can see that a superseded
// heartbeat was observed and recorded-as-superseded,
// distinct from "silently dropped".
s.supersededCount++
s.mu.Unlock()
return nil, nil
}
}
// Health transitions, from this accepted report against the same
// server's previously stored fact for each slot it carries.
// slot's stored fact. INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53:
// timestamps order one sender's
// slot only; a later report from another slot cannot supersede it.
accepted := make([]SlotFact, 0, len(obs.Slots))
for _, slot := range obs.Slots {
old := ""
var newest time.Time
if hadPrev {
for _, p := range prev.Slots {
if slotKey(p) == slotKey(slot) {
old = p.UnhealthyReason
newest = slotObservedAt(p, prev)
break
}
}
}
if newest.After(slot.ObservedAt) {
s.supersededCount++
key := [3]string{obs.ServerID, slot.VolumeID, slot.ReplicaID}
s.supersededSlots[key]++
dropped = append(dropped, supersededReport{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]})
continue
}
accepted = append(accepted, slot)
if old != slot.UnhealthyReason {
transitions = append(transitions, SlotHealthTransition{
VolumeID: slot.VolumeID, ReplicaID: slot.ReplicaID, Old: old, New: slot.UnhealthyReason,
})
}
}
if len(obs.Slots) > 0 && len(accepted) == 0 {
s.mu.Unlock()
return nil, nil
}
obs.Slots = accepted
if hadPrev {
obs.Slots = mergeServerSlots(prev.Slots, obs.Slots)
if prev.ObservedAt.After(obs.ObservedAt) {
// Preserve the newest server metadata without lending its
// timestamp or freshness to another process's slot.
obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server
}
}
s.observations[obs.ServerID] = obs
s.revision++
@@ -0,0 +1,153 @@
package authority
import (
"bytes"
"fmt"
"log"
"strings"
"testing"
"time"
)
type unlockedHeartbeatLog struct {
bytes.Buffer
store *ObservationStore
locked bool
}
func (w *unlockedHeartbeatLog) Write(p []byte) (int, error) {
if w.store.mu.TryLock() {
w.store.mu.Unlock()
} else {
w.locked = true
}
return w.Buffer.Write(p)
}
func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) {
base := time.Unix(1000, 0)
s := NewObservationStore(FreshnessConfig{}, func() time.Time { return base })
w := &unlockedHeartbeatLog{store: s}
old := log.Writer()
log.SetOutput(w)
t.Cleanup(func() { log.SetOutput(old) })
for _, server := range []string{"one-host", "other-host"} {
for _, volume := range []string{"a", "b"} {
slot := healthySlot(volume, "r1")
if err := s.Ingest(Observation{ServerID: server, ObservedAt: base, Slots: []SlotFact{slot}}); err != nil {
t.Fatal(err)
}
}
}
for _, tc := range []struct{ server, volume string }{{"one-host", "a"}, {"one-host", "a"}, {"one-host", "b"}, {"other-host", "a"}} {
if err := s.Ingest(Observation{ServerID: tc.server, ObservedAt: base.Add(-time.Second), Slots: []SlotFact{healthySlot(tc.volume, "r1")}}); err != nil {
t.Fatal(err)
}
}
if w.locked {
t.Fatal("superseded diagnostic was emitted while the store lock was held")
}
lines := strings.Split(strings.TrimSpace(w.String()), "\n")
if len(lines) != 4 {
t.Fatalf("diagnostics=%q; want one line per dropped slot", w.String())
}
for i, want := range []string{
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=2",
"server=one-host volume=b replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=other-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
} {
if !strings.Contains(lines[i], "heartbeat superseded "+want) {
t.Errorf("diagnostic %d=%q; want %q", i, lines[i], want)
}
}
if s.SupersededSlotCount("one-host", "a", "r1") != 2 ||
s.SupersededSlotCount("one-host", "b", "r1") != 1 ||
s.SupersededSlotCount("other-host", "a", "r1") != 1 ||
s.SupersededSlotCount("other-host", "b", "r1") != 0 || s.SupersededCount() != 4 {
t.Fatal("per-slot diagnostics disagree with emitted totals or aggregate count")
}
}
// INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53: processes on one server order only their
// own (volume, replica) reports; another slot's later timestamp is irrelevant.
func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) {
for _, n := range []int{10, 100} {
t.Run(fmt.Sprintf("%d slots", n), func(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(3 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
for round := 0; round < 2; round++ {
for i := n - 1; i >= 0; i-- {
slot := healthySlot(fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
slot.DataAddr = fmt.Sprintf("round-%d-slot-%d", round, i)
at := base.Add(time.Duration(round)*time.Second + time.Duration(i)*time.Millisecond)
obs, err := HeartbeatToObservation(serverObs("one-host", at, slot))
if err != nil {
t.Fatal(err)
}
if err := s.Ingest(obs); err != nil {
t.Fatal(err)
}
}
}
for i := 0; i < n; i++ {
got, ok := s.SlotFactOnServer("one-host", fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
if !ok || got.DataAddr != fmt.Sprintf("round-1-slot-%d", i) {
t.Errorf("slot %d lost an independent sender's heartbeat: fact=%+v present=%v", i, got, ok)
}
}
if got := s.SupersededCount(); got != 0 {
t.Fatalf("other senders superseded %d slot reports", got)
}
})
}
}
func TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(4 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
report := func(at time.Duration, slots ...SlotFact) []SlotHealthTransition {
t.Helper()
tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "one-host", ObservedAt: base.Add(at), Slots: slots})
if err != nil {
t.Fatal(err)
}
return tr
}
a, b, c := healthySlot("a", "r1"), healthySlot("b", "r1"), healthySlot("c", "r1")
report(3*time.Second, a)
report(time.Second, b)
a.UnhealthyReason, b.UnhealthyReason, c.UnhealthyReason = "stale", "new-b", "new-c"
mutations := 0
s.SetOnMutation(func() { mutations++ })
tr := report(2*time.Second, a, b, c)
if len(tr) != 2 || tr[0].VolumeID != "b" || tr[0].New != "new-b" || tr[1].VolumeID != "c" || tr[1].New != "new-c" {
t.Fatalf("mixed report transitions=%+v; want only b and c", tr)
}
if got, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok || got.UnhealthyReason != "" {
t.Fatalf("stale a replaced its newer fact: %+v, %v", got, ok)
}
if s.SupersededCount() != 1 || mutations != 1 {
t.Fatalf("mixed report: superseded=%d mutations=%d; want 1/1", s.SupersededCount(), mutations)
}
rev := s.Snapshot().revision
if tr := report(time.Second, a, b, c); len(tr) != 0 {
t.Fatalf("all-stale report emitted transitions: %+v", tr)
}
if s.SupersededCount() != 4 || mutations != 1 || s.Snapshot().revision != rev {
t.Fatalf("all-stale report: superseded=%d mutations=%d revision=%d; want 4/1/%d", s.SupersededCount(), mutations, s.Snapshot().revision, rev)
}
// The server's timestamp stays at its newest report; each accepted slot
// keeps its own expiry, including after a delayed mixed report.
now = base.Add(12500 * time.Millisecond)
if _, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok {
t.Fatal("a lost its later expiry to another slot's older report")
}
for _, volume := range []string{"b", "c"} {
if _, ok := s.SlotFactOnServer("one-host", volume, "r1"); ok {
t.Fatalf("%s inherited a's later freshness", volume)
}
}
}
+1 -1
View File
@@ -144,7 +144,7 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
}
if _, line, ok := p.workspaceLineLocked(volume); ok {
if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID {
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK")
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete")
}
} else if pendingPlacement {
return fmt.Errorf("workspace delete: placement may have queued authority")
@@ -1285,6 +1285,7 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
// readAt + deadline, the last moment this fork can publish
// (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed.
readAt := c.now()
deadline := readAt.Add(c.deadline())
var shareToken string
if c.guard != nil { // the shared HEAD is the snapshot's, read below
if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil {
@@ -1334,6 +1335,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen)
}
} else {
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; VOLUME not written", req.Target)
}
vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(),
Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record}
ve, err := volumeEntry(vol, req.RequestID)
@@ -1355,6 +1359,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
existing = vol
}
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; manifest preparation not started", req.Target)
}
head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo)
defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs)
if err != nil {
@@ -1365,7 +1372,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
return ForkResult{}, err
}
he.Extended[extReq] = []byte(req.RequestID)
deadline := readAt.Add(c.deadline())
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; copy intent not written", req.Target)
}
id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes,
DeadlineNs: deadline.UnixNano()})
if err != nil {
@@ -2,6 +2,7 @@ package chunkstore
import (
"context"
"fmt"
"strings"
"testing"
"time"
@@ -75,3 +76,118 @@ func TestCatalog_PublishIsBoundedByTheDeadline(t *testing.T) {
f.stallCreate = nil
}
}
// A delayed source read must not create a target, and an expired attempt
// after VOLUME must not create a copy intent, even one it later deletes.
func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) {
for _, origin := range []string{OriginFork, OriginRestore} {
for _, stage := range []string{"source_read", "volume_written", "live"} {
t.Run(origin+"/"+stage, func(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
now := time.Unix(1800000000, 0)
c.SetClock(func() time.Time { return now })
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil {
t.Fatal(err)
}
start := now
volumeWrites, intentWrites := 0, 0
f.afterLookup = func(p string) {
if stage == "source_read" && isSnapPath(p, "v1", "s1") {
now = start.Add(DefaultOpDeadline)
}
}
f.beforeCreate = func(p string) {
if p == catBase+"/v2/VOLUME" {
volumeWrites++
if stage == "volume_written" {
now = start.Add(DefaultOpDeadline)
}
}
if strings.HasPrefix(p, catBase+"/v2/intents/") {
intentWrites++
}
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
var err error
if origin == OriginFork {
_, err = c.Fork(ctx, req)
} else {
_, err = c.Restore(ctx, req)
}
f.afterLookup, f.beforeCreate = nil, nil
if stage == "live" {
if err != nil || volumeWrites != 1 || intentWrites != 1 {
t.Fatalf("live attempt: err=%v VOLUME=%d intents=%d", err, volumeWrites, intentWrites)
}
return
}
if CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("expired attempt: %v", err)
}
wantVolume := 0
if stage == "volume_written" {
wantVolume = 1
}
if volumeWrites != wantVolume || intentWrites != 0 {
t.Fatalf("expired attempt wrote VOLUME=%d intents=%d; want %d and 0", volumeWrites, intentWrites, wantVolume)
}
if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil {
t.Fatal("expired attempt published HEAD")
}
if intents := intentsOf(t, f, "v2"); len(intents) != 0 {
t.Fatalf("expired attempt left intents: %+v", intents)
}
})
}
}
}
// The frozen flat snapshot forces the manifest-upgrade path to create an
// intent before uploading its segment; count creates, even if later removed.
func TestFork_ExpiredLegacyPreparationWritesNoIntent(t *testing.T) {
for _, origin := range []string{OriginFork, OriginRestore} {
for _, expired := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/expired=%t", origin, expired), func(t *testing.T) {
f, c, r := preF4ForkFixture(t, false)
now := time.Unix(1800000000, 0)
start := now
c.SetClock(func() time.Time { return now })
intents := 0
f.beforeCreate = func(p string) {
if p == catBase+"/v3/VOLUME" && expired {
now = start.Add(DefaultOpDeadline)
}
if strings.HasPrefix(p, catBase+"/v3/intents/") {
intents++
}
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "legacy-deadline"}
var err error
if origin == OriginFork {
_, err = c.Fork(context.Background(), req)
} else {
_, err = c.Restore(context.Background(), req)
}
f.beforeCreate = nil
if expired {
if CodeOf(err) != CodeDeadlineExceeded || intents != 0 {
t.Fatalf("expired legacy attempt: err=%v intent creates=%d; want deadline and zero", err, intents)
}
if _, err := f.LookupEntry(context.Background(), catBase+"/v3", headName); err == nil {
t.Fatal("expired legacy attempt published HEAD")
}
} else {
if err != nil || intents != 2 {
t.Fatalf("live legacy attempt: err=%v intent creates=%d; want success and upgrade+copy intents", err, intents)
}
dst, err := NewChunkRemote(f, r.b, catBase+"/v3")
if err != nil {
t.Fatal(err)
}
assertLegacyImage(t, dst)
}
})
}
}
}
@@ -370,7 +370,7 @@ func TestFork_RefusalsAndDeadline(t *testing.T) {
t.Fatal("a fork past its deadline wrote a HEAD")
}
c.SetClock(time.Now)
// The VOLUME from the late attempt is reused by its own retry.
// A retry of the expired attempt succeeds under a fresh deadline.
if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed {
t.Fatalf("retry after the late attempt: %+v %v", res, err)
}
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -178,9 +179,13 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) {
var pinnedAttempt string
stoppedFork := func(snap, target string) {
t.Helper()
cat.OpDeadline = time.Nanosecond
start := clock
cat.SetClock(func() time.Time { return clock })
original := cat.f
cat.f = expireForkVolumeFiler{Filer: original, target: path.Join(base, target, volumeName), expire: func() { clock = start.Add(DefaultOpDeadline) }}
_, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"})
cat.OpDeadline = 0
cat.f = original
cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock })
if CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err)
}
@@ -231,3 +236,19 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) {
}
}
}
// expireForkVolumeFiler advances only after the target identity was stored;
// the retention test therefore exercises an incomplete fork, not an absent one.
type expireForkVolumeFiler struct {
Filer
target string
expire func()
}
func (f expireForkVolumeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error {
err := f.Filer.CreateEntry(ctx, dir, e, exclusive)
if err == nil && path.Join(dir, e.Name) == f.target {
f.expire()
}
return err
}
@@ -25,12 +25,16 @@ func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) {
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
clock := time.Now()
c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances
c.OpDeadline = time.Nanosecond
c.SetClock(func() time.Time { return clock })
f.beforeCreate = func(p string) {
if p == catBase+"/v2/VOLUME" {
clock = clock.Add(DefaultOpDeadline)
}
}
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err)
}
c.OpDeadline = 0
f.beforeCreate = nil
if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil {
t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err)
}
@@ -1084,7 +1084,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R
}
report := Recover(h.storage, volumeID)
if report.Err != nil {
h.backend.SetOperational(false, report.Evidence)
h.backend.setRecoveryFailure(report.Evidence, report.Err)
return report, report.Err
}
if chunked {
@@ -0,0 +1,89 @@
package durable_test
import (
"bytes"
"context"
"errors"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// INV-FE-ERROR-RETRY-CLASS-001 / V1-SPEC r2.55 side (d), coverage A9.1.
// A real strict-W WAL integrity failure must survive recovery readiness gating
// as a permanent cause. Ordinary awaiting-recovery readiness stays retryable.
func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) {
root := t.TempDir()
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
WALRecoveryTestDisableFlusher: true,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
s, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
b := p.Backend("v1")
if _, err := b.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) ||
frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady {
t.Fatalf("ordinary pre-recovery gate is not retryable not-ready: %v", err)
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if _, err := s.Write(5, block(0xA7)); err != nil {
t.Fatal(err)
}
ws, ok := s.(*storage.WALStore)
if !ok {
t.Fatalf("unexpected store %T", s)
}
if err := ws.SetWMode(storage.WModeStrict); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
restore := corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7)
t.Cleanup(restore)
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) {
t.Fatalf("expected real WAL integrity recovery failure: %v", err)
}
n, err := b.Read(ctx, 5*4096, make([]byte, 4096))
if n != 0 || !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("failed recovery guest read: n=%d, want 0 and not-ready: %v", n, err)
}
if got := frontend.ClassifyBackendError(ctx, err); got != frontend.BackendErrorPermanent {
t.Errorf("store-fault recovery became guest retry class %v, want permanent: %v", got, err)
}
if !errors.Is(err, storage.ErrWALIntegrityFault) {
t.Errorf("guest error lost permanent WAL-integrity cause: %v", err)
}
// A later successful recovery clears the old cause. A subsequent ordinary
// readiness pause must not inherit a repaired fault's permanent class.
restore()
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatalf("recovery after repair: %v", err)
}
want := block(0xA7)
got := make([]byte, len(want))
n, err = b.Read(ctx, 5*4096, got)
if err != nil || n != len(want) || !bytes.Equal(got, want) {
t.Fatalf("repaired acknowledged record through backend: n=%d, want %d; matching bytes=%t: %v", n, len(want), bytes.Equal(got, want), err)
}
b.SetOperational(false, "maintenance pause")
_, err = b.Read(ctx, 5*4096, make([]byte, 4096))
if !errors.Is(err, frontend.ErrNotReady) || errors.Is(err, storage.ErrWALIntegrityFault) ||
frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady {
t.Fatalf("ordinary pause retained the repaired recovery fault: %v", err)
}
}
@@ -206,6 +206,9 @@ type StorageBackend struct {
// could not follow the store's next LSN). While set, every I/O is
// refused, so a volume never serves without its observer. Under mu.
observerErr error
// recoveryErr retains the typed cause while the operational gate is shut.
// INV-FE-ERROR-RETRY-CLASS-001: permanent leaves survive readiness markers.
recoveryErr error // protected by mu; cleared only by successful readiness
// observerMu serializes moving the store's next LSN (the frontier
// seed) together with rebasing the observer, against installing an
// observer together with its rebase: whichever runs second sees the
@@ -494,6 +497,13 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
b.mu.Unlock()
}
func (b *StorageBackend) setRecoveryFailure(evidence string, cause error) {
b.mu.Lock()
b.setOperationalLocked(false, evidence)
b.recoveryErr = cause
b.mu.Unlock()
}
// FirstServing is closed the first time the backend admits I/O (for a chunk
// volume: after its storage claim succeeded) and never reopens. A later loss
// of readiness does not reopen it: the process exit of
@@ -503,6 +513,9 @@ func (b *StorageBackend) FirstServing() <-chan struct{} { return b.firstServing
// The caller owns mu; publication never calls the store or waits for I/O.
func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) {
flipped := !ok && b.operational.Load()
if ok {
b.recoveryErr = nil
}
b.opEvidence.Store(evidence)
b.operational.Store(ok)
if ok && !b.served {
@@ -914,6 +927,9 @@ func (b *StorageBackend) readyCheck() error {
closed := b.closed
chunkFenced := b.chunkFenced
observerErr := b.observerErr
recoveryErr := b.recoveryErr
operational := b.operational.Load()
ev, _ := b.opEvidence.Load().(string)
precopyPending := b.precopy != nil && b.precopy.active
b.mu.Unlock()
if closed {
@@ -928,9 +944,8 @@ func (b *StorageBackend) readyCheck() error {
if precopyPending {
return errPrecopyPaused
}
if !b.operational.Load() {
ev, _ := b.opEvidence.Load().(string)
return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev)
if !operational {
return fmt.Errorf("%w: %s", errors.Join(frontend.ErrNotReady, recoveryErr), ev)
}
return nil
}
@@ -2,6 +2,7 @@ package master
import (
"context"
"strings"
"testing"
"time"
@@ -55,6 +56,10 @@ func TestMarkVolumeDeleting_RefusedWhileAssigned(t *testing.T) {
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("mark of an assigned volume: %v; want FailedPrecondition", err)
}
want := "revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete"
if !strings.Contains(status.Convert(err).Message(), want) {
t.Fatalf("delete refusal lacks the clean-revocation cure: %v", err)
}
if h.Lifecycle().Deletions.Reserved("live") {
t.Fatal("a refused mark reserved the id")
}
@@ -230,6 +230,8 @@ stateDiagram-v2
NameHeld --> Published: exclusive create snaps/name/attempt
NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path
Published --> Deleting: DeleteSnapshot or retention (forks do not hold it)
Published --> ForkTarget: deadline live before VOLUME, legacy preparation, copy intent and HEAD
ForkTarget --> ActiveTarget: exclusive HEAD create before deadline (fork or restore)
Deleting --> NameFreed: name record removed
Aborted --> NameFreed: name record removed
NameFreed --> [*]
+32 -4
View File
@@ -81,6 +81,32 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c
blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves).
**Heartbeat observations, per server/volume/replica slot.**
`ObservationStore.ingest` compares each reported slot only with that slot's
stored timestamp (`slotObservedAt`). An older slot is dropped and counted;
an equal or newer slot is accepted. A mixed report merges accepted slots and
retains every other stored slot. An all-superseded nonempty report changes no
observation or health transition. Accepted slots keep their own freshness;
server metadata keeps its newest timestamp without lending it to another slot.
```mermaid
flowchart LR
Report[Receive heartbeat report] --> Compare{Each slot: stored timestamp newer?}
Compare -->|yes| Drop[Drop and count only that slot]
Compare -->|no| Accept[Accept that slot and its health transition]
Drop --> Mixed{Any accepted slots or an empty report?}
Accept --> Mixed
Mixed -->|yes| Merge[Merge accepted slots; retain other slots and newest server metadata]
Mixed -->|no| Keep[Keep stored observations unchanged]
```
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| Stored observations | Stored observations (slot refused) | stored timestamp for this server/volume/replica is strictly newer than the report; drop and count only this slot | `core/authority/observation_store.go` `ingest`, `slotObservedAt` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (mixed report merged) | accept equal/newer slots against their own stored timestamp; merge only accepted slots, preserving other slots and independent freshness | `core/authority/observation_store.go` `ingest`, `mergeServerSlots` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (no mutation) | a nonempty report has no accepted slot; publish no observation mutation or health transition | `core/authority/observation_store.go` `ingest` | `INV-OBS-SLOT-ORDER-001` |
**Assignment line, per volume.**
| From | To | Event and guard | Enforced in | Protects |
@@ -349,7 +375,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` |
| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` |
| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, check start + deadline before the target `VOLUME`, legacy manifest preparation, copy intent and HEAD writes; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` |
| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` |
@@ -467,7 +493,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new.
317 rows: 246 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 302 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -724,6 +750,7 @@ Notes:
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE |
| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK. | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | ACTIVE |
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
@@ -874,7 +901,7 @@ Notes:
| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE |
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE |
| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE |
| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestFork_ExpiredAttemptWritesNoNewMetadata`, `TestFork_ExpiredLegacyPreparationWritesNoIntent` (`core/frontend/chunkstore/catalog_deadline_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE |
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE |
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE |
@@ -911,7 +938,7 @@ Notes:
- `INV-GC-GRACE-RESTART-001`: "past the grace" means past the grace plus the clock-skew bound of `INV-GC-CLOCK-SKEW-001`. The restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test.
- `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code.
- `INV-FORK-FROM-SEALED-001`: the case of a name whose attempt is still in flight (name record present, attempt entry absent) is enforced by reading; no test forks during a held snapshot create.
- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved.
- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. The same deadline is checked before creating target VOLUME, its copy intent and its HEAD; an expired source read creates no target, and expiry after VOLUME leaves it retryable without a new copy intent. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved.
- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists.
- `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing.
- `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it.
@@ -930,6 +957,7 @@ Notes:
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE |
| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | M2 heartbeat observations: per-slot refusal / mixed merge / all-superseded no mutation (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE |
| `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE |
| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE |
| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE |
+5
View File
@@ -66,6 +66,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p
- **SeaweedFS space:** every cut and snapshot stores the chunks that changed since the previous one. Space comes
back only by GC and then a SeaweedFS vacuum (below).
Each volume process reports its own heartbeat slot (server, volume and replica).
The master orders each slot against that slot's previous report. In version 1.0,
a backward host-clock step longer than the freshness window (30 seconds by
default) can expire the host's slots; keep host clocks synchronized.
## Recovery point and sync policy
- **A stopped volume** keeps everything it acknowledged, on its host.