Merge pull request #958 from seaweedfs/fix/957-c3-progress-window

fix: observe C3 recovery progress and graceful stop separately
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-02 14:05:35 -08:00
commit af07f8be92
14 files changed
+668 -16

No files matched your search

@@ -0,0 +1,41 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"syscall"
"testing"
"time"
)
// The graceful-stop procedure: the driver applies the same pre-create disk cap
// and measured neighbour as C3. No SIGKILL is sent until this cell has ended.
func TestC3GracefulStopWithReclaimPressure(t *testing.T) {
env := startHandoffEnvWith(t, 1, nil)
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
d := env.start(t, "blockvolume-graceful", "s1")
env.adopt(t, d, "s1")
var chunks []uint64
for c := uint64(0); c < 32; c++ {
chunks = append(chunks, c)
}
env.writeImage(t, "s1", denseImage("graceful-pressure", chunks))
began := time.Now()
t.Logf("GRACEFUL_BEGIN time=%s", began.UTC().Format(time.RFC3339Nano))
if err := d.proc.Signal(syscall.SIGTERM); err != nil {
t.Fatal(err)
}
select {
case <-d.done:
keepFullLog(t, d)
t.Logf("GRACEFUL_PHASES log tail:\n%s", d.tail(80))
t.Logf("GRACEFUL_END elapsed=%s err=%v", time.Since(began), d.err)
if d.err != nil {
t.Fatalf("graceful exit: %v", d.err)
}
case <-time.After(5 * time.Minute):
keepFullLog(t, d)
logTaskState(t, d, "graceful driver ceiling")
t.Skip("UNKNOWN: graceful driver ceiling expired; classify from phase/progress and kernel evidence, not elapsed time alone")
}
}
@@ -0,0 +1,60 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/host/volume"
"net/http"
"testing"
"time"
)
func waitC3RecoveryPrimary(t *testing.T, d *daemon, addr, target string) {
t.Helper()
w := newRecoveryPrimaryWait(time.Now())
client := &http.Client{Timeout: time.Second}
needle := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target)
for {
var s volume.RecoveryProgressStatus
resp, err := client.Get("http://" + addr + "/status/recovery-progress?volume=" + target)
if err == nil {
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("recovery observer HTTP %d", resp.StatusCode)
} else {
err = json.NewDecoder(resp.Body).Decode(&s)
}
resp.Body.Close()
if err == nil && s.ProcessID == "" {
err = fmt.Errorf("recovery observer lacks process identity")
}
}
now := time.Now()
if err == nil {
t.Logf("C3_RECOVERY volume=%s status=%+v", target, s)
} else {
t.Logf("C3_RECOVERY volume=%s unavailable=%v", target, err)
}
state, waitErr := w.observe(now, s, d.line(needle) != "" && err == nil, err == nil)
if state == "unknown" {
if now.Sub(w.began) >= 15*time.Minute {
t.Skip("UNKNOWN: C3 recovery exceeded15min experiment ceiling")
}
t.Skipf("UNKNOWN: recovery observation lacks timely counter/exit evidence or was unavailable for30s: %v", err)
}
if waitErr != nil {
t.Fatalf("%s: %v; log tail:\n%s", d.name, waitErr, d.tail(40))
}
if state == "primary" {
return
}
select {
case <-d.done:
t.Fatalf("%s exited before PRIMARY: %v", d.name, d.err)
default:
}
time.Sleep(time.Second)
}
}
@@ -566,11 +566,13 @@ func (d *daemon) term(t *testing.T, timeout time.Duration) {
// kill kills the child (no ACK is sent on a signal) and waits for it.
func (d *daemon) kill(t *testing.T) {
t.Helper()
began := time.Now()
defer func() { t.Logf("%s SIGKILL-to-reap=%s", d.name, time.Since(began)) }()
d.cancel()
select {
case <-d.done:
case <-time.After(10 * time.Second):
t.Fatalf("%s did not exit after kill", d.name)
d.waitForKilledReap(t)
}
}
@@ -591,14 +593,16 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args ..
d := &daemon{name: name, log: log.Name(), done: make(chan struct{}), cancel: cancel}
started := false
t.Cleanup(func() {
stopAt := time.Now()
cancel()
if started {
select {
case <-d.done:
case <-time.After(10 * time.Second):
t.Errorf("%s did not exit after cancellation", name)
d.waitForKilledReap(t)
}
}
t.Logf("%s cancellation-to-reap=%s", name, time.Since(stopAt))
_ = log.Close()
if t.Failed() {
keepFullLog(t, d)
@@ -912,3 +916,43 @@ func (c *nvmeInitiator) close() {
}
}
}
// A killed task can remain in uninterruptible filesystem I/O. The containing
// procedure owns its outer ceiling;10s alone is never a product-stop failure.
func (d *daemon) waitForKilledReap(t *testing.T) {
t.Helper()
began := time.Now()
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
ceiling := began.Add(15 * time.Minute)
if deadline, ok := t.Deadline(); ok && deadline.Add(-5*time.Second).Before(ceiling) {
ceiling = deadline.Add(-5 * time.Second)
}
timer := time.NewTimer(time.Until(ceiling))
defer timer.Stop()
for {
logTaskState(t, d, "SIGKILL reap pending")
select {
case <-d.done:
t.Logf("environment: %s reaped after additional %s (SIGKILL; not graceful stop)", d.name, time.Since(began))
return
case <-timer.C:
t.Skipf("UNKNOWN: environment reap observation ceiling reached; outstanding name=%s pid=%d, driver retains cleanup ownership", d.name, d.proc.Pid)
case <-ticker.C:
}
}
}
func logTaskState(t *testing.T, d *daemon, reason string) {
t.Helper()
if d.proc == nil {
return
}
dirs, err := filepath.Glob(fmt.Sprintf("/proc/%d/task/*", d.proc.Pid))
t.Logf("environment: %s name=%s pid=%d at=%s tasks_error=%v", reason, d.name, d.proc.Pid, time.Now().UTC().Format(time.RFC3339Nano), err)
for _, dir := range dirs {
for _, field := range []string{"stat", "wchan", "stack", "io"} {
data, err := os.ReadFile(filepath.Join(dir, field))
t.Logf("environment: task=%s %s=%q error=%v", filepath.Base(dir), field, data, err)
}
}
}
@@ -0,0 +1,90 @@
package main_test
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/storage"
"time"
)
// The ceiling bounds the experiment, not product recovery. Reaching it is
// UNKNOWN even if a PRIMARY line arrives in the same observation.
type recoveryPrimaryWait struct {
began, last time.Time
lastAvailable time.Time
process string
phase storage.RecoveryPhase
completed uint64
awaiting bool
fenceBytes, replayRecords uint64
windowStarted bool
workActive bool
}
func newRecoveryPrimaryWait(now time.Time) *recoveryPrimaryWait {
return &recoveryPrimaryWait{began: now, last: now, lastAvailable: now}
}
func (w *recoveryPrimaryWait) observe(now time.Time, s volume.RecoveryProgressStatus, adopted bool, available bool) (string, error) {
if now.Sub(w.began) >= 15*time.Minute {
return "unknown", nil
}
if !available {
if now.Sub(w.lastAvailable) >= 30*time.Second {
return "unknown", nil
}
return "waiting", nil
}
w.lastAvailable = now
if s.Stalled {
return "", fmt.Errorf("recovery_stalled at phase %d completed %d", s.Phase, s.Completed)
}
if s.ProcessID != "" {
if w.process != "" && w.process != s.ProcessID {
return "", fmt.Errorf("holder incarnation changed: %s -> %s", w.process, s.ProcessID)
}
w.process = s.ProcessID
}
if s.FenceBytes > w.fenceBytes || s.ReplayRecords > w.replayRecords {
completedAt := s.CounterProgressAt
if completedAt.IsZero() {
return "unknown", nil
}
if w.windowStarted && !w.awaiting && completedAt.Sub(w.last) >= 30*time.Second {
return "", fmt.Errorf("completed recovery gap reached30s before late work")
}
w.fenceBytes, w.replayRecords, w.last = s.FenceBytes, s.ReplayRecords, completedAt
w.windowStarted = true
w.workActive = true
}
if !w.windowStarted && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) {
w.windowStarted = true
w.workActive = true
w.last = now
}
w.phase, w.completed = s.Phase, s.Completed
if w.windowStarted && s.AwaitingAuthority && !w.awaiting && !s.AuthorityWaitSince.IsZero() && s.AuthorityWaitSince.Sub(w.last) >= 30*time.Second {
return "", fmt.Errorf("silence reached30s before authority pause")
}
if s.AwaitingAuthority || w.awaiting {
w.last = now
}
w.awaiting = s.AwaitingAuthority
if !s.AwaitingAuthority && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) && now.Sub(w.last) >= 30*time.Second {
return "", fmt.Errorf("no completed recovery work for30s (phase %d completed %d)", w.phase, w.completed)
}
// Phase-only completion is not a counter. Once replay/fence was seen,
// its exit must itself be observed inside the last completed-work window.
// A late attach sample cannot prove when that exit occurred, even when
// PRIMARY is already logged or a general LastProgress timestamp moved.
if w.workActive && s.Phase != storage.RecoveryReplay && s.Phase != storage.RecoveryFence {
if now.Sub(w.last) >= 30*time.Second {
return "unknown", nil
}
w.workActive = false
}
if adopted && s.ProcessID != "" {
return "primary", nil
}
return "waiting", nil
}
@@ -0,0 +1,165 @@
package main_test
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/storage"
"testing"
"time"
)
func TestRecoveryPrimaryWaitUsesProgressNotTotalTime(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
for i := 1; i <= 6; i++ {
now := start.Add(time.Duration(i) * 20 * time.Second)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: uint64(i) * 4 << 20, FenceBytes: uint64(i) * 4 << 20, CounterProgressAt: now}
if got, err := w.observe(now, s, false, true); got != "waiting" || err != nil {
t.Fatalf("progress %d: %s %v", i, got, err)
}
}
if got, err := w.observe(start.Add(121*time.Second), volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 24 << 20}, true, true); got != "primary" || err != nil {
t.Fatalf("%s %v", got, err)
}
}
func TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 4 << 20, FenceBytes: 4 << 20, CounterProgressAt: start}
w.observe(start, s, false, true)
if _, err := w.observe(start.Add(30*time.Second), s, false, true); err == nil {
t.Fatal("identical counter renewed")
}
w = newRecoveryPrimaryWait(start)
s.Stalled = true
if _, err := w.observe(start, s, true, true); err == nil {
t.Fatal("stalled sample passed as primary")
}
}
func TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true}
if got, err := w.observe(start.Add(time.Minute), s, false, true); got != "waiting" || err != nil {
t.Fatalf("pause: %s %v", got, err)
}
s.AwaitingAuthority = false
if got, err := w.observe(start.Add(2*time.Minute), s, false, true); got != "waiting" || err != nil {
t.Fatalf("grant: %s %v", got, err)
}
if got, err := w.observe(start.Add(15*time.Minute), s, true, true); got != "unknown" || err != nil {
t.Fatalf("ceiling became pass: %s %v", got, err)
}
}
func TestRecoveryPrimaryWaitLateProgressCannotHideSilence(t *testing.T) {
start := time.Unix(1000, 0)
for _, pause := range []bool{false, true} {
w := newRecoveryPrimaryWait(start)
first := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 1, FenceBytes: 1, CounterProgressAt: start}
w.observe(start, first, false, true)
late := first
late.Completed = 2
late.FenceBytes = 2
late.CounterProgressAt = start.Add(31 * time.Second)
if pause {
late = first
late.AwaitingAuthority = true
late.AuthorityWaitSince = start.Add(31 * time.Second)
}
if _, err := w.observe(start.Add(31*time.Second), late, true, true); err == nil {
t.Fatalf("late pause=%t hid silence", pause)
}
}
}
func TestRecoveryPrimaryWaitUnavailableSamplePreservesPause(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true, AuthorityWaitSince: start}
w.observe(start, s, false, true)
if state, err := w.observe(start.Add(29*time.Second), volume.RecoveryProgressStatus{}, false, false); state != "waiting" || err != nil {
t.Fatalf("missing: %s %v", state, err)
}
if !w.awaiting || w.process != "p1" {
t.Fatal("missing sample changed known state")
}
if state, err := w.observe(start.Add(30*time.Second), volume.RecoveryProgressStatus{}, true, false); state != "unknown" || err != nil {
t.Fatalf("missing observation passed: %s %v", state, err)
}
}
func TestRecoveryPrimaryWaitPhaseChangeIsNotProgress(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 7, Completed: 7, CounterProgressAt: start}
w.observe(start, s, false, true)
s.Phase = storage.RecoveryFence
s.Completed = 1
s.CounterProgressAt = start.Add(29 * time.Second)
if _, err := w.observe(start.Add(30*time.Second), s, true, true); err == nil {
t.Fatal("phase-only change hid no-progress window")
}
}
func TestRecoveryPrimaryWaitDoesNotCountPreReplayWork(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
w.observe(start, volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryCreate}, false, true)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 1, CounterProgressAt: start.Add(40 * time.Second)}
if got, err := w.observe(start.Add(40*time.Second), s, false, true); got != "waiting" || err != nil {
t.Fatalf("pre-replay time counted: %s %v", got, err)
}
s.Phase = storage.RecoveryFence
s.LastProgress = start.Add(69 * time.Second)
if _, err := w.observe(start.Add(70*time.Second), s, true, true); err == nil {
t.Fatal("phase-only timestamp hid counter silence")
}
}
func TestRecoveryPrimaryWaitExitNeedsTimelyWitness(t *testing.T) {
for _, phase := range []storage.RecoveryPhase{storage.RecoveryReplay, storage.RecoveryFence} {
for _, adopted := range []bool{false, true} {
t.Run(fmt.Sprintf("phase%d/primary%t", phase, adopted), func(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: phase, ReplayRecords: 1, CounterProgressAt: start}
if got, err := w.observe(start, s, false, true); got != "waiting" || err != nil {
t.Fatalf("setup: %s %v", got, err)
}
s.Phase = storage.RecoveryAttach
s.LastProgress = start.Add(31 * time.Second)
if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil {
t.Fatalf("unproved exit became %s %v", got, err)
}
})
}
}
// A witnessed timely exit ends only the replay/fence window; a later
// PRIMARY may follow other bounded work without inventing more counters.
t.Run("timely-exit", func(t *testing.T) {
start := time.Unix(1000, 0)
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1, CounterProgressAt: start}
w.observe(start, s, false, true)
s.Phase = storage.RecoveryAttach
if got, err := w.observe(start.Add(29*time.Second), s, false, true); got != "waiting" || err != nil {
t.Fatalf("timely exit: %s %v", got, err)
}
if got, err := w.observe(start.Add(time.Minute), s, true, true); got != "primary" || err != nil {
t.Fatalf("witnessed exit: %s %v", got, err)
}
})
}
func TestRecoveryPrimaryWaitMissingCounterTimeIsUnknown(t *testing.T) {
start := time.Unix(1000, 0)
for _, adopted := range []bool{false, true} {
w := newRecoveryPrimaryWait(start)
s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1}
if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil {
t.Fatalf("adopted=%t: missing timestamp became %s %v", adopted, got, err)
}
}
}
@@ -89,7 +89,7 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon {
t.Helper()
b := env.hosts["n-"+target]
d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target))
waitC3RecoveryPrimary(t, d, b.status, target)
poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool {
return volumeFrontendReady(b.status, target)
})
@@ -22,6 +22,16 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// recoveryProgressStatus holds only w.mu while copying scalar fields and
// time.Time values. Its only calls are Lock/Unlock: no storage, helper,
// channel, I/O or wait is introduced by the read-only snapshot.
reviewed := map[string]bool{
"ReportRecoveryProgress": true, "recoveryProgressStatus": true,
"authorityWaitEnds": true, "authorityWaitStarts": true,
"AwaitingAuthority": true, "primaryAssigned": true, "notPrimary": true,
"supportingAdmitted": true, "reason": true, "catchUpSince": true,
"epoch": true,
}
locked := 0
for _, decl := range f.Decls {
fn, ok := decl.(*ast.FuncDecl)
@@ -34,12 +44,16 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) {
continue
}
locked++
if !reviewed[fn.Name.Name] {
t.Errorf("unreviewed watchdog-locked method %s", fn.Name.Name)
}
delete(reviewed, fn.Name.Name)
for _, violation := range watchdogBodyViolations(fset, fn.Body) {
t.Errorf("watchdog-locked %s: %s", fn.Name.Name, violation)
}
}
if locked != 10 {
t.Fatalf("watchdog lock sites=%d, want 10 reviewed methods", locked)
if locked != 11 || len(reviewed) != 0 {
t.Fatalf("watchdog lock sites=%d, want 11 reviewed methods; missing=%v", locked, reviewed)
}
}
@@ -0,0 +1,68 @@
package volume
import (
"context"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestRecoveryStatusReportsOnlyCompletedFrontiers(t *testing.T) {
h, clk := watchdogHost(t, 30*time.Second)
h.applyFixtureFact(selfPrimaryFact(1))
h.ReportRecoveryProgress(storage.RecoveryReplay, 7)
clk.advance(time.Second)
h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20)
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", h))
addr, err := s.Start("127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer s.Close(context.Background())
read := func() map[string]any {
t.Helper()
res, err := http.Get("http://" + addr + "/status/recovery-progress?volume=v1")
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
t.Fatalf("status %d", res.StatusCode)
}
var got map[string]any
if err := json.NewDecoder(res.Body).Decode(&got); err != nil {
t.Fatal(err)
}
return got
}
first := read()
if first["FenceBytes"] != float64(4<<20) || first["ReplayRecords"] != float64(7) || first["ProcessID"] == "" {
t.Fatalf("frontiers: %v", first)
}
clk.advance(10 * time.Second)
h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20)
again := read()
if again["LastProgress"] != first["LastProgress"] {
t.Fatalf("repeat renewed: %v -> %v", first, again)
}
clk.advance(time.Second)
h.ReportRecoveryProgress(storage.RecoveryAttach, 1)
if read()["CounterProgressAt"] != first["CounterProgressAt"] {
t.Fatal("phase-only report changed counter timestamp")
}
h.ReportAuthorityWait(true)
if read()["AwaitingAuthority"] != true {
t.Fatal("missing authority pause")
}
h.ReportAuthorityWait(false)
clk.advance(31 * time.Second)
if h.UnhealthyReason() != UnhealthyRecoveryStalled {
t.Fatal("control did not stall")
}
if read()["Stalled"] != true {
t.Fatal("missing stalled latch")
}
}
@@ -82,16 +82,20 @@ type recoveryWatchdog struct {
timeout time.Duration
now func() time.Time
primarySince time.Time // zero unless this replica holds the primary assignment
primaryEpoch uint64
supportingSince time.Time // zero unless admitted as a supporting replica
supportingEpoch uint64
timedOut bool // recovery_stalled latched until a ready fact
awaiting int // authority waits in progress: the window is paused while > 0
readySeen bool // promotion-ready once in this primary assignment: disarmed
progressPhase storage.RecoveryPhase
progressDone uint64
lastProgress time.Time
primarySince time.Time // zero unless this replica holds the primary assignment
primaryEpoch uint64
supportingSince time.Time // zero unless admitted as a supporting replica
supportingEpoch uint64
timedOut bool // recovery_stalled latched until a ready fact
awaiting int // authority waits in progress: the window is paused while > 0
authorityWaitSince time.Time
readySeen bool // promotion-ready once in this primary assignment: disarmed
progressPhase storage.RecoveryPhase
progressDone uint64
fenceBytes uint64
replayRecords uint64
counterProgressAt time.Time
lastProgress time.Time
}
func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog {
@@ -123,6 +127,40 @@ func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64)
w.timedOut = true
}
w.progressPhase, w.progressDone, w.lastProgress = phase, done, now
switch phase {
case storage.RecoveryFence:
w.fenceBytes = done
w.counterProgressAt = now
case storage.RecoveryReplay:
w.replayRecords = done
w.counterProgressAt = now
}
}
// RecoveryProgressStatus is an observation of completed startup work in one
// process incarnation. Reading it does not renew the window or grant readiness.
type RecoveryProgressStatus struct {
ProcessID string // holder process incarnation; counters must not cross it
VolumeID string // served volume
Phase storage.RecoveryPhase // highest completed phase in fixed recovery order
Completed uint64 // cumulative completed work in Phase
FenceBytes uint64 // bytes whose fence sync completed
ReplayRecords uint64 // WAL records replayed, not bytes
CounterProgressAt time.Time // last completed replay record or synced fence slice; phase-only reports do not change it
LastProgress time.Time // last new completed frontier or authority-wait end
AuthorityWaitSince time.Time // start of the current master-owned pause
AwaitingAuthority bool // the master-owned authority wait pauses the window
Stalled bool // recovery_stalled latch; late work cannot clear it
}
func (h *Host) recoveryProgressStatus() RecoveryProgressStatus {
w := h.wd
w.mu.Lock()
defer w.mu.Unlock()
return RecoveryProgressStatus{ProcessID: h.incarnation, VolumeID: h.cfg.VolumeID,
Phase: w.progressPhase, Completed: w.progressDone, FenceBytes: w.fenceBytes,
ReplayRecords: w.replayRecords, CounterProgressAt: w.counterProgressAt, LastProgress: w.lastProgress,
AwaitingAuthority: w.awaiting > 0, AuthorityWaitSince: w.authorityWaitSince, Stalled: w.timedOut}
}
// ReportAuthorityWait observes the chunk layer's wait for master
@@ -158,6 +196,7 @@ func (w *recoveryWatchdog) authorityWaitEnds() {
w.awaiting--
if w.awaiting == 0 {
w.lastProgress = w.now()
w.authorityWaitSince = time.Time{}
}
}
@@ -176,6 +215,9 @@ func (w *recoveryWatchdog) authorityWaitStarts() (fired bool) {
w.timedOut, fired = true, true
}
}
if w.awaiting == 0 {
w.authorityWaitSince = w.now()
}
w.awaiting++
return fired
}
@@ -27,6 +27,7 @@ var statusRoutes = []struct {
typ reflect.Type
}{
{"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})},
{"/status/recovery-progress", "completed recovery work in this holder process; reading never renews progress", reflect.TypeOf(RecoveryProgressStatus{})},
{"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})},
{"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})},
{"/status/wal-hold", "atomic WAL hold observations scoped to this process and store open", reflect.TypeOf(walHoldStatusBody{})},
@@ -400,6 +400,7 @@ func (s *StatusServer) Start(addr string) (string, error) {
mux := http.NewServeMux()
registerLabHeapProfile(mux)
mux.HandleFunc("/status", s.handleStatus)
mux.HandleFunc("/status/recovery-progress", s.handleRecoveryProgress)
mux.HandleFunc("/metrics", s.handleWALHoldMetrics)
mux.HandleFunc("/status/wal-hold", s.handleWALHoldStatus)
mux.HandleFunc("/status/peers", s.handleStatusPeers)
@@ -439,6 +440,25 @@ func (s *StatusServer) externalAccessAllowed() bool {
return s.allowExternal
}
func (s *StatusServer) handleRecoveryProgress(w http.ResponseWriter, r *http.Request) {
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden)
return
}
vol := r.URL.Query().Get("volume")
if vol == "" {
http.Error(w, "missing volume query param", http.StatusBadRequest)
return
}
h, ok := s.view.probe.(*Host)
if !ok || h == nil || h.wd == nil || vol != h.cfg.VolumeID {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(h.recoveryProgressStatus())
}
// Close gracefully shuts the server down. Idempotent.
func (s *StatusServer) Close(ctx context.Context) error {
if err := s.StopSnapshotOperations(ctx); err != nil {
@@ -0,0 +1,89 @@
package storage
import (
"bytes"
"context"
"os"
"os/exec"
"testing"
"time"
)
// A child bounds even a regressed Close/observer join. The sink is released
// and every child goroutine joined before reporting the assertion.
func TestWALStoreCloseDoesNotWaitForDiagnosticOutput(t *testing.T) {
if os.Getenv("SWBLOCK_CLOSE_BLOCKED_OUTPUT_CHILD") != "1" {
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWALStoreCloseDoesNotWaitForDiagnosticOutput$", "-test.timeout=10s")
cmd.Env = append(os.Environ(), "SWBLOCK_CLOSE_BLOCKED_OUTPUT_CHILD=1")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bounded blocked-output child: %v\n%s", err, out)
}
return
}
s, _ := newMappedCheckpointStoreV3(t)
r, sink, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stderr
os.Stderr = sink
filled := make(chan struct{})
go func() { defer close(filled); _, _ = sink.Write(bytes.Repeat([]byte{'x'}, 8<<20)) }()
select {
case <-filled:
os.Stderr = old
r.Close()
sink.Close()
t.Fatal("pipe did not provide a blocked sink")
case <-time.After(100 * time.Millisecond):
}
// Keep Close active long enough to exercise a periodic observer as well
// as its phase-entry and final diagnostics, if any are reintroduced.
s.testCloseSnapshot = func() { time.Sleep(1100 * time.Millisecond) }
results := make(chan error, 2)
go func() { results <- s.Close() }()
go func() { results <- s.Close() }()
completed := 0
timer := time.NewTimer(3 * time.Second)
var closeErr error
wait:
for completed < 2 {
select {
case err := <-results:
completed++
if err != nil {
closeErr = err
}
case <-timer.C:
break wait
}
}
timer.Stop()
beforeRelease := completed
// Release the blocked producer and any regressed Close logger; no writer
// is abandoned to make the success path appear bounded.
r.Close()
<-filled
for completed < 2 {
select {
case err := <-results:
completed++
if err != nil {
closeErr = err
}
case <-time.After(2 * time.Second):
t.Fatal("Close did not join after releasing diagnostic sink")
}
}
os.Stderr = old
sink.Close()
if beforeRelease != 2 || closeErr != nil {
t.Fatalf("Close/closeComplete depended on diagnostic sink: completed=%d err=%v", beforeRelease, closeErr)
}
if stop := s.ChunkMapStatsV3().LastStop; stop == nil || stop.TotalNs <= 0 {
t.Fatalf("in-memory stop phases lost: %+v", stop)
}
}
+1 -1
View File
@@ -698,7 +698,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|---|---|---|---|---|---|---|
| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE |
| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_stalled only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE |
| `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_stalled only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); observation: `TestRecoveryStatusReportsOnlyCompletedFrontiers` (`core/host/volume/recovery_status_test.go`); C3: `TestRecoveryPrimaryWaitUsesProgressNotTotalTime`, `TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall`, `TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown`, `TestRecoveryPrimaryWaitLateProgressCannotHideSilence`, `TestRecoveryPrimaryWaitUnavailableSamplePreservesPause`, `TestRecoveryPrimaryWaitPhaseChangeIsNotProgress`, `TestRecoveryPrimaryWaitDoesNotCountPreReplayWork`, `TestRecoveryPrimaryWaitExitNeedsTimelyWitness`, `TestRecoveryPrimaryWaitMissingCounterTimeIsUnknown` (`cmd/blockvolume/recovery_primary_wait_test.go`); diagnostic shutdown isolation: `TestWALStoreCloseDoesNotWaitForDiagnosticOutput` (`core/storage/close_blocked_output_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE |
| `INV-RECOVERY-SIZED-STEP-SLICES-001` | A sized startup step (a new store's prezero, the WAL fence) reports its bytes as recovery progress only after their sync, prezero one 1 MiB slice at a time. | M1 Recovering | `core/storage/recovery_progress.go` `syncedSlices`; `core/storage/data_sync.go` `prezeroNewStore`; `core/storage/walstore_v3.go` `fenceV3` | `TestSyncedSlicesCountOnlySyncedSlices`, `TestPrezeroReportsEachSyncedSlice`, `TestRecoveryReportsTheSyncedFence`, `TestRecoveryFenceHeldSyncReportsAfterRelease`, `TestPrezeroReportsAfterEachSyncAndStopsAtAFailedOne`, `TestCreateRecoveryReportsTheFenceThroughTheOptions` (`core/storage/recovery_create_progress_test.go`); `TestRecoveryStalled_CreateSlicesRenewTheWindow` (`core/host/volume/recovery_authority_wait_test.go`) | — | ACTIVE |
| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts at the grant, before local attach work; silence that filled the window before the wait is latched at its start. The master bounds the wait. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught`, `TestRecoveryStalled_SilenceBeforeTheWaitIsLatchedAtItsStart`, `TestRecoveryStalled_HeldAttachAfterTheGrantStalls` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap`, `TestAuthorityWaitEndsAtTheGrantBeforeTheAttach`, `TestAuthorityLostAfterAGrantPausesAgain` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE |
| `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | A volume whose header carries a removed experimental engine's magic (smartwal `SWAW`; parallel-walstore `SWPW` at offset 0 or 4096) is refused typed (copy the data to a walstore volume with v1.0.x first) under every selector, read-only and never modified. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `TestDurableProvider_RefusesRemovedEngineVolumes` (byte-identical file after each refusal; `core/frontend/durable/provider_auto_impl_test.go`); `TestWALStoreChunk_SelectorRules` (`core/frontend/durable/provider_chunk_test.go`) | — | ACTIVE |
+18
View File
@@ -49,6 +49,24 @@ The volume's authority and health projection. Go type `volume.StatusProjection`.
| `MasterWait.SinceMs` | int64 | — |
| `MasterWait.UntilMs` | int64 | — (omitted when empty) |
### `GET /status/recovery-progress`
Completed recovery work in this holder process; reading never renews progress. Go type `volume.RecoveryProgressStatus`.
| Field | Type | Meaning |
|---|---|---|
| `ProcessID` | string | holder process incarnation; counters must not cross it |
| `VolumeID` | string | served volume |
| `Phase` | RecoveryPhase (uint8) | highest completed phase in fixed recovery order |
| `Completed` | uint64 | cumulative completed work in Phase |
| `FenceBytes` | uint64 | bytes whose fence sync completed |
| `ReplayRecords` | uint64 | WAL records replayed, not bytes |
| `CounterProgressAt` | time (RFC 3339) | last completed replay record or synced fence slice; phase-only reports do not change it |
| `LastProgress` | time (RFC 3339) | last new completed frontier or authority-wait end |
| `AuthorityWaitSince` | time (RFC 3339) | start of the current master-owned pause |
| `AwaitingAuthority` | bool | the master-owned authority wait pauses the window |
| `Stalled` | bool | recovery_stalled latch; late work cannot clear it |
### `GET /status/peers`
Replication peers of the served volume. Go type `volume.peersStatusBody`.