storage: per-cut stats and cumulative cut counters

Every cut now fills its ChunkCutStats:
- barrier pause, sync and copy time;
- candidate, uploaded, zeroed and unchanged chunks, and uploaded bytes;
- upload time; CAS time and result (ok, precondition, unknown,
  resolved-by-reread; empty for a no-op cut);
- total time.

The layer keeps cumulative counters, exposed by Stats():
- cuts ok, no-op and failed;
- refusals by reason (admission, fenced, detached);
- CAS conflicts, and unknown CAS outcomes left unresolved by the HEAD
  re-read;
- whether a proposal is pending, and the current dirty-chunk count (the
  C11 bitmap popcount, for the cut scheduler's threshold);
- the last successful cut's stats, LSN and time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 10:35:00 -08:00
1 parent 6daca22e2f
commit b2862307ac
4 files changed
+248 -1

No files matched your search

+85 -1
View File
@@ -75,6 +75,8 @@ type chunkLayerImpl struct {
// pendingIntent is the intent of the unresolved proposal in pending;
// it is deleted once that proposal is settled.
pendingIntent string
// stats holds the cumulative cut counters (under stMu).
stats chunkLayerStats
// leftoverIntents are this layer's own intents whose delete failed
// after their cut was settled; every cut retries them.
leftoverIntents []string
@@ -578,12 +580,21 @@ type capturedChunk struct {
zero bool
}
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkCutResult, error) {
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) {
done, err := l.register()
if err != nil {
return chunkCutResult{}, err
}
defer done()
start := time.Now()
var st chunkCutStats
defer func() {
st.TotalNs = time.Since(start).Nanoseconds()
if err == nil {
res.Stats = st
}
l.recordCut(res, st, err)
}()
if err := l.admit(); err != nil {
return chunkCutResult{}, err
}
@@ -600,9 +611,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
// Quiesced cut.
l.s.captureMu.Lock()
barrier := time.Now()
h, err := l.s.Sync()
st.SyncNs = time.Since(barrier).Nanoseconds()
if err != nil {
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err)
}
candidates := map[uint64]bool{}
@@ -631,8 +645,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
baseHead := copyHead(l.head)
l.stMu.Unlock()
st.CandidateChunks = len(candidates)
var captured []capturedChunk
var copyErr error
copyStart := time.Now()
for _, idx := range sortedKeys(candidates) {
buf := make([]byte, int(l.chunkBlocks)*l.blockSize)
for i := uint64(0); i < l.chunkBlocks; i++ {
@@ -652,7 +668,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
}
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
}
st.CopyNs = time.Since(copyStart).Nanoseconds()
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
if copyErr != nil {
l.abortCut(all)
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr)
@@ -684,16 +702,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
ref, had := baseHead.Chunks[c.idx]
switch {
case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum:
st.UnchangedChunks++
continue
case c.zero:
delete(next.Chunks, c.idx)
changed = append(changed, c.idx)
st.ZeroedChunks++
continue
}
uploads = append(uploads, upload{c: c, key: l.newKey(c.idx)})
}
// The intent names every key this cut uploads and is durable before
// the first upload: GC treats it as a root until the cut is settled.
uploadStart := time.Now()
var intent string
if len(uploads) > 0 {
keys := make([]string, len(uploads))
@@ -716,7 +737,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum}
newKeys[u.c.idx] = u.key
changed = append(changed, u.c.idx)
st.UploadedChunks++
st.UploadedBytes += int64(len(u.c.data))
}
st.UploadNs = time.Since(uploadStart).Nanoseconds()
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
// A no-op cut still observes authority: a fresh host may have
// claimed HEAD without uploading a single chunk since our last cut.
@@ -749,7 +773,15 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
return chunkCutResult{}, errChunkLayerFenced
}
expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch}
casStart := time.Now()
gen, casErr := l.remote.CASHead(ctx, expected, next)
st.CASNs = time.Since(casStart).Nanoseconds()
st.CASResult = "ok"
if errors.Is(casErr, errChunkHeadPrecondition) {
st.CASResult = "precondition"
} else if casErr != nil {
st.CASResult = "unknown"
}
if casErr == nil {
next.Gen = gen
l.finishCut(next, h, changed, newKeys)
@@ -780,6 +812,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
}
if sameProposal(cur, next) {
st.CASResult = "resolved-by-reread"
l.finishCut(cur, h, changed, newKeys)
l.dropIntent(ctx, intent)
return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil
@@ -924,6 +957,57 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error {
return nil
}
// recordCut updates the cumulative counters after one cut attempt.
func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error) {
l.stMu.Lock()
defer l.stMu.Unlock()
switch st.CASResult {
case "precondition":
l.stats.CASConflicts++
case "unknown":
if l.pending != nil { // the HEAD re-read did not settle it
l.stats.CASUnknown++
}
}
reason := ""
switch {
case err == nil && r.Noop:
l.stats.CutsNoop++
case err == nil:
l.stats.CutsOK++
case errors.Is(err, errChunkCaptureRefused):
reason = "admission"
case errors.Is(err, errChunkLayerFenced):
reason = "fenced"
case errors.Is(err, errChunkLayerDetached):
reason = "detached"
default:
l.stats.CutsFailed++
}
if reason != "" {
if l.stats.CutsRefused == nil {
l.stats.CutsRefused = map[string]uint64{}
}
l.stats.CutsRefused[reason]++
}
if err == nil {
l.stats.LastCut, l.stats.LastCutH, l.stats.LastCutNs = st, r.H, time.Now().UnixNano()
}
}
func (l *chunkLayerImpl) Stats() chunkLayerStats {
l.stMu.Lock()
defer l.stMu.Unlock()
out := l.stats
out.CutsRefused = make(map[string]uint64, len(l.stats.CutsRefused))
for k, v := range l.stats.CutsRefused {
out.CutsRefused[k] = v
}
out.PendingUnresolved = l.pending != nil
out.DirtyChunks = len(l.dirty)
return out
}
// dropIntent deletes this layer's own intent id (none if empty) once its
// cut is settled. A failed delete is kept and retried by the next cut; it
// never fails a cut whose outcome is already settled.
@@ -0,0 +1,131 @@
package storage
// W3: per-cut stats (B9 7.1) and cumulative counters (7.2).
import (
"errors"
"testing"
)
func TestChunkCutStats_PublishedZeroedUnchangedAndNoop(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22) // chunk 0
w.write(t, s, 5, 0x25) // chunk 1
if err := flushWithin(t, s, "flush before the cut"); err != nil { // the bitmap counts flushed writes
t.Fatal(err)
}
if d := layer.Stats().DirtyChunks; d != 2 {
t.Fatalf("dirty chunks before the cut: %d, want 2", d)
}
r, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
st := r.Stats
if st.UploadedChunks != 2 || st.UploadedBytes != 2*ctChunkBytes || st.ZeroedChunks != 0 || st.CandidateChunks < 2 {
t.Fatalf("first cut stats %+v: want 2 uploaded chunks (%d bytes), 0 zeroed, >=2 candidates", st, 2*ctChunkBytes)
}
if st.CASResult != "ok" || st.CASNs < 0 || st.UploadNs < 0 || st.TotalNs <= 0 {
t.Fatalf("first cut timings/result %+v", st)
}
if st.BarrierPauseNs <= 0 || st.BarrierPauseNs < st.SyncNs || st.BarrierPauseNs < st.CopyNs {
t.Fatalf("barrier %d ns must cover sync %d and copy %d", st.BarrierPauseNs, st.SyncNs, st.CopyNs)
}
if st.TotalNs < st.BarrierPauseNs+st.UploadNs+st.CASNs {
t.Fatalf("total %d ns shorter than barrier %d + upload %d + CAS %d", st.TotalNs, st.BarrierPauseNs, st.UploadNs, st.CASNs)
}
w.write(t, s, 2, 0x00) // chunk 0 back to zero: dropped
w.write(t, s, 5, 0x25) // chunk 1 rewritten with the same bytes: unchanged
r2, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if st2 := r2.Stats; st2.UploadedChunks != 0 || st2.ZeroedChunks != 1 || st2.UnchangedChunks != 1 || st2.CASResult != "ok" {
t.Fatalf("second cut stats %+v: want 0 uploaded, 1 zeroed, 1 unchanged, CAS ok", st2)
}
r3, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !r3.Noop || r3.Stats.CASResult != "" || r3.Stats.UploadedChunks != 0 || r3.Stats.CASNs != 0 {
t.Fatalf("no-op cut: noop=%v stats %+v; want no CAS and no upload", r3.Noop, r3.Stats)
}
c := layer.Stats()
if c.DirtyChunks != 0 {
t.Fatalf("dirty chunks after the cuts: %d, want 0", c.DirtyChunks)
}
if c.CutsOK != 2 || c.CutsNoop != 1 || c.CutsFailed != 0 || len(c.CutsRefused) != 0 {
t.Fatalf("counters %+v: want 2 ok, 1 noop", c)
}
if c.LastCutH != r3.H || c.LastCutNs == 0 || c.LastCut.TotalNs != r3.Stats.TotalNs {
t.Fatalf("last cut %+v (H %d), want the no-op cut H %d", c.LastCut, c.LastCutH, r3.H)
}
}
func TestChunkCutStats_RefusalsConflictsAndUnknown(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
refuse := false
cfg.CaptureAllowed = func() error {
if refuse {
return errors.New("not primary")
}
return nil
}
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
// Admission refused.
w.write(t, s, 2, 0x22)
refuse = true
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
t.Fatalf("refused cut: %v", err)
}
refuse = false
// Unknown outcome, then settled by the next cut.
f.mu.Lock()
f.casModes = []fakeCASMode{casUnknownNotApplied}
f.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("unknown cut: %v", err)
}
if c := layer.Stats(); c.CASUnknown != 1 || !c.PendingUnresolved || c.CutsFailed != 1 {
t.Fatalf("after an unknown CAS outcome: %+v", c)
}
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatalf("settling cut: %v", err)
}
// The settling cut lands the held proposal first; with nothing new
// after it, the cut itself is a no-op.
if c := layer.Stats(); c.PendingUnresolved || c.CutsOK+c.CutsNoop != 1 {
t.Fatalf("after settlement: %+v", c)
}
// Taken over: the CAS conflicts and the layer fences.
w.write(t, s, 5, 0x25)
f.mu.Lock()
f.beforeCAS = func(f *fakeChunkRemote) { f.takeOverLocked("host-b") }
f.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) {
t.Fatalf("taken-over cut: %v", err)
}
c := layer.Stats()
if c.CutsRefused["admission"] != 1 || c.CutsRefused["fenced"] != 1 || c.CASConflicts != 1 || c.CASUnknown != 1 {
t.Fatalf("counters %+v: want 1 admission refusal, 1 fenced, 1 CAS conflict", c)
}
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) {
t.Fatalf("cut on a fenced layer: %v", err)
}
if c := layer.Stats(); c.CutsRefused["fenced"] != 2 {
t.Fatalf("fenced refusals %d, want 2", c.CutsRefused["fenced"])
}
}
@@ -17,6 +17,7 @@ type (
ChunkLayer = chunkLayer
ChunkCutResult = chunkCutResult
ChunkCutStats = chunkCutStats
ChunkLayerStats = chunkLayerStats
ChunkIntent = chunkIntent
ChunkDetachedBy = chunkDetachedBy
)
+31
View File
@@ -345,6 +345,35 @@ type chunkCutStats struct {
TotalNs int64
}
// chunkLayerStats are a layer's cumulative cut counters and its last
// successful cut (B9 7.2-7.3). Cuts counts every Cut, Capture,
// MakeRemoteDurable and Detach attempt that got past the closed check.
// - CutsOK counts cuts that installed a HEAD; CutsNoop those with
// nothing new (no CAS); CutsFailed every other failure.
// - CutsRefused counts refusals by reason: "admission" (CaptureAllowed:
// not a healthy primary of this lineage, BASE install), "fenced",
// "detached".
// - CASConflicts counts CAS precondition failures; CASUnknown CAS
// results whose outcome stayed unresolved after the HEAD re-read.
// - PendingUnresolved: an unresolved proposal is held now.
// - DirtyChunks is the number of chunks dirty since the last HEAD now
// (the C11 bitmap popcount); the cut scheduler's threshold reads it.
// - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the
// last successful cut, whatever triggered it.
type chunkLayerStats struct {
CutsOK uint64
CutsNoop uint64
CutsFailed uint64
CutsRefused map[string]uint64
CASConflicts uint64
CASUnknown uint64
PendingUnresolved bool
DirtyChunks int
LastCut chunkCutStats
LastCutH uint64
LastCutNs int64
}
// chunkCutResult is the outcome of one successful cut.
// - H is the cut LSN; Head.RemoteLSN = H when the cut installed a HEAD.
// A volume's LSNs carry forward across hosts: a new host's WAL starts
@@ -370,6 +399,8 @@ type chunkLayer interface {
// It returns the HEAD it installed, so a snapshot can copy exactly the
// image of H even when other cuts follow.
Cut(ctx context.Context) (chunkCutResult, error)
// Stats returns the cumulative cut counters and the last cut.
Stats() chunkLayerStats
// Capture is Cut, returning only H.
Capture(ctx context.Context) (uint64, error)
// Detach is the final cut of a clean stop: one cut whose CAS publishes