durable: seed log outside the store locks; log every claim outcome

Fold of the #248 review:
- the v3 seed logs after the capture and lifecycle locks are released,
  and names its intervals for what they include (lock wait, store mutex
  and validation, data sync incl. sync serialization, checkpoint publish);
- the HEAD claim logs its start before the claim's own HEAD read and its
  elapsed time on failure; the observed HEAD is logged as an observation;
- a close during the attach retry backoff ends the wait as closed, not
  superseded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-19 00:07:59 -08:00
1 parent f99db46603
commit a5ae7fb0d3
4 files changed
+183 -25

No files matched your search

@@ -239,6 +239,10 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err)
select {
case <-waitCtx.Done():
ended = "provider closed during the retry backoff"
if errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
ended = "deadline during the retry backoff"
}
return
case <-time.After(chunkAttachRetry):
}
@@ -393,8 +397,8 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
// Attach preparation is gated. Seed the exact observed HEAD before
// its takeover CAS; only then finalize lazy attachment and expose I/O.
cfg.PrepareRestore = func(head storage.ChunkHead) error {
log.Printf("durable: claiming HEAD for volume=%s: gen=%d epoch=%d holder=%q state=%v remote_lsn=%d -> epoch=%d holder=%q",
volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN, cfg.Epoch, cfg.Holder)
log.Printf("durable: HEAD claim for volume=%s observed HEAD gen=%d epoch=%d holder=%q state=%v remote_lsn=%d; preparing",
volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN)
if baseLSN, complete := ws.InstalledBaseLSN(); complete {
// The fresh marker can outlive a full local BASE. It is not
// permission to seed backwards or to fill from an older HEAD.
@@ -424,8 +428,10 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) })
}
claimStart := time.Now()
log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder)
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
if err != nil {
log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err)
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
}
claimed := "claimed"
@@ -3,8 +3,10 @@ package durable_test
import (
"bytes"
"context"
"errors"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -86,7 +88,8 @@ func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) {
inOrder(t, got,
[]string{"volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0"},
[]string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"},
[]string{"claiming HEAD for volume=v1: gen=", `-> epoch=3 holder="r1"`},
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
[]string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"},
[]string{"HEAD claim for volume=v1 done in ", `gen=0 epoch=0 holder="", no HEAD to claim (new lineage)`},
[]string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"},
)
@@ -139,9 +142,84 @@ func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) {
[]string{"volume=v1 waits for master authority (up to " + limit.String() + "): projection lacks healthy=false epoch=0"},
[]string{"chunk authority wait for volume=v1 ended after", end},
)
if strings.Contains(got, "first attach attempt") || strings.Contains(got, "claiming HEAD") {
if strings.Contains(got, "first attach attempt") || strings.Contains(got, "HEAD claim for") {
t.Fatalf("attach logged without authority:\n%s", got)
}
})
}
}
// headFailRemote fails GetHead while fails > 0 (forever when < 0).
type headFailRemote struct {
*storage.MemChunkRemote
fails atomic.Int32
}
var errHeadRead = errors.New("injected HEAD read failure")
func (r *headFailRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
if n := r.fails.Load(); n != 0 {
if n > 0 {
r.fails.Add(-1)
}
return storage.ChunkHead{}, errHeadRead
}
return r.MemChunkRemote.GetHead(ctx)
}
// A claim whose first HEAD read fails logs its start and its failure with
// the elapsed time; the retry then claims. Close during the retry backoff
// ends the wait as closed, not superseded.
func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) {
for _, mode := range []string{"retried", "closed in backoff"} {
t.Run(mode, func(t *testing.T) {
logs := &lockedLog{}
captureWriteLogs(t, logs)
remote := &headFailRemote{MemChunkRemote: storage.NewMemChunkRemote()}
remote.fails.Store(1)
if mode != "retried" {
remote.fails.Store(-1)
}
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v)
if err != nil {
t.Fatal(err)
}
defer p.Close()
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
v.active.Store(true)
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
waitLog(t, logs, "waits for master authority")
close(v.assigned)
if mode == "retried" {
got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after")
inOrder(t, got,
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
[]string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()},
[]string{"chunk layer attach for volume=v1:", "(retrying)"},
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
[]string{"HEAD claim for volume=v1 observed HEAD gen=0"},
[]string{"HEAD claim for volume=v1 done in "},
[]string{"chunk authority wait for volume=v1 ended after", ": attached after 2 attempt(s)"},
)
return
}
waitLog(t, logs, "(retrying)")
if err := p.Close(); err != nil {
t.Fatal(err)
}
got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after")
inOrder(t, got,
[]string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()},
[]string{"chunk authority wait for volume=v1 ended after", ": provider closed during the retry backoff"},
)
})
}
}
+26 -18
View File
@@ -67,28 +67,35 @@ func (s *WALStore) SeedChunkFrontier(lsn uint64) error {
// publication succeeded; any failure publishes nothing and may be retried.
// An unmapped v3 store has no map candidate for the new checkpoint and is
// refused. Order: captureMu -> lifecycleMu -> (syncMu ->) mu.
func (s *WALStore) seedChunkFrontierV3(lsn uint64) (err error) {
v := s.v3
start := time.Now()
s.captureMu.Lock()
defer s.captureMu.Unlock()
s.lifecycleMu.RLock()
defer s.lifecycleMu.RUnlock()
locked := time.Now()
var synced, published time.Time
defer func() {
if synced.IsZero() {
return // refused or already seeded: no I/O to time
}
func (s *WALStore) seedChunkFrontierV3(lsn uint64) error {
var t seedTimes
err := s.seedChunkFrontierV3Locked(lsn, &t)
// Logged after the capture and lifecycle locks are released: a slow log
// writer never extends them. A refused or no-op seed did no I/O.
if !t.validated.IsZero() {
stage := func(from, to time.Time) string {
if to.IsZero() {
return "-"
}
return to.Sub(from).String()
}
log.Printf("storage: seed frontier %d: lock wait %s, data fsync %s, checkpoint publish %s, err=%v",
lsn, locked.Sub(start), synced.Sub(locked), stage(synced, published), err)
}()
log.Printf("storage: seed frontier %d: capture+lifecycle lock wait %s, store mutex+validation %s, data sync (incl. sync serialization) %s, checkpoint publish %s, err=%v",
lsn, t.locked.Sub(t.start), t.validated.Sub(t.locked), stage(t.validated, t.synced), stage(t.synced, t.published), err)
}
return err
}
// seedTimes are the stage boundaries of one v3 seed (zero: not reached).
type seedTimes struct{ start, locked, validated, synced, published time.Time }
func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err error) {
v := s.v3
t.start = time.Now()
s.captureMu.Lock()
defer s.captureMu.Unlock()
s.lifecycleMu.RLock()
defer s.lifecycleMu.RUnlock()
t.locked = time.Now()
s.mu.Lock()
if s.closed || s.chunk.Load() != nil {
s.mu.Unlock()
@@ -114,13 +121,14 @@ func (s *WALStore) seedChunkFrontierV3(lsn uint64) (err error) {
}
gen := v.recoverGen.Load()
s.mu.Unlock()
t.validated = time.Now()
err = s.syncFile(nil, s.fd.Sync)
synced = time.Now()
t.synced = time.Now()
if err != nil {
return fmt.Errorf("storage: seed data sync: %w", err)
}
_, err = s.publishCheckpointV3(lsn, true, gen)
published = time.Now()
t.published = time.Now()
if err != nil {
return fmt.Errorf("storage: seed frontier %d: %w", lsn, err)
}
@@ -7,6 +7,7 @@ import (
"strings"
"sync"
"testing"
"time"
)
type seedLog struct {
@@ -42,7 +43,7 @@ func captureSeedLog(t *testing.T) *seedLog {
return l
}
var seedTimes = regexp.MustCompile(`storage: seed frontier 7: lock wait [0-9.]+[a-zµ]+s, data fsync [0-9.]+[a-zµ]+s, checkpoint publish [0-9.]+[a-zµ]+s, err=`)
var seedTimesLine = regexp.MustCompile(`storage: seed frontier 7: capture\+lifecycle lock wait [0-9.]+[a-zµ]+s, store mutex\+validation [0-9.]+[a-zµ]+s, data sync \(incl\. sync serialization\) [0-9.]+[a-zµ]+s, checkpoint publish [0-9.]+[a-zµ]+s, err=`)
// A v3 seed logs its lock wait, data fsync and checkpoint publication
// times once per seed that did I/O, with its outcome; a no-op repeat and a
@@ -58,7 +59,7 @@ func TestWALStoreV3SeedLogsItsStageTimes(t *testing.T) {
t.Fatal(err)
}
got := logs.lines()
if len(got) != 1 || !seedTimes.MatchString(got[0]) || !strings.HasSuffix(got[0], "err=<nil>") {
if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.HasSuffix(got[0], "err=<nil>") {
t.Fatalf("seed log lines %q; want one line with the three stage times and err=<nil>", got)
}
})
@@ -76,7 +77,7 @@ func TestWALStoreV3SeedLogsItsStageTimes(t *testing.T) {
t.Fatal("seed across a lifetime change succeeded")
}
got := logs.lines()
if len(got) != 1 || !seedTimes.MatchString(got[0]) || !strings.Contains(got[0], ErrMapCoverageStale.Error()) {
if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.Contains(got[0], ErrMapCoverageStale.Error()) {
t.Fatalf("seed log lines %q; want one line with the stage times and the coverage error", got)
}
})
@@ -92,3 +93,68 @@ func TestWALStoreV3SeedLogsItsStageTimes(t *testing.T) {
}
})
}
// blockingLog blocks its first write until released.
type blockingLog struct {
entered, release chan struct{}
once sync.Once
}
func (b *blockingLog) Write(p []byte) (int, error) {
first := false
b.once.Do(func() { first = true })
if first {
close(b.entered)
<-b.release
}
return len(p), nil
}
// The seed's log line is written after the capture and lifecycle locks are
// released: while the log output is blocked, both are free.
func TestWALStoreV3SeedLogsOutsideTheStoreLocks(t *testing.T) {
s, _ := newMappedCheckpointStoreV3(t)
b := &blockingLog{entered: make(chan struct{}), release: make(chan struct{})}
old := log.Writer()
log.SetOutput(b)
t.Cleanup(func() { log.SetOutput(old) })
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(b.release) }) }
done := make(chan error, 1)
joined := false
t.Cleanup(func() { // release the blocked writer, then join the seed, bounded
release()
if joined {
return
}
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("seed not joined")
}
})
go func() { done <- s.SeedChunkFrontier(7) }()
select {
case <-b.entered:
case <-time.After(5 * time.Second):
t.Fatal("the seed never logged")
}
if !s.captureMu.TryLock() {
t.Fatal("captureMu held while the seed log output is blocked")
}
s.captureMu.Unlock()
if !s.lifecycleMu.TryLock() {
t.Fatal("lifecycleMu held while the seed log output is blocked")
}
s.lifecycleMu.Unlock()
release()
select {
case err := <-done:
joined = true
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("the seed did not finish after the log output was released")
}
}