storage: OwnBatch bounded re-own cut and a byte-paced walker (restore part B)

OwnBatch(n, foreign) runs one ordinary cut whose candidates include up to n
local chunks whose HEAD keys name another volume; streamCutPayloads uploads
each under a new own key even when its bytes equal HEAD's, and the cut's one
intent and HEAD CAS publish them (M6.Restore.Owning>Owning). An absent chunk is
never fetched by a batch; with nothing to own no cut runs. HydrateAllAt paces
the walker to a byte rate before admission (HydrateAll = unpaced).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-20 23:23:16 -08:00
1 parent ca2069ce25
commit 29c81a1dca
6 files changed
+246 -2

No files matched your search

@@ -58,7 +58,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return err
}
ref, had := head.Chunks[c.idx]
if !c.zero && !(had && ref.SHA256 == c.sum) {
if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) {
c.key, c.size = keys[i], len(c.data)
once.Do(func() {
intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys})
@@ -47,7 +47,16 @@ var (
// or on a fill error that is not a retryable pending state; the caller may
// call it again.
func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) {
return l.HydrateAllAt(ctx, 0)
}
// HydrateAllAt is HydrateAll paced to at most bytesPerSecond of fill payload
// (one chunk per fill), counted from its start; 0 means unpaced. The pace
// applies before admission, so a paced walker holds no permit while it waits.
func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) (HydrateProgress, error) {
var p HydrateProgress
start := time.Now()
started := int64(0) // fills started, for the pace
walk, stop := context.WithCancelCause(ctx)
defer stop(nil)
backoff := hydrateAllMinBackoff
@@ -89,6 +98,21 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error
}
continue
}
if bytesPerSecond > 0 && started > 0 {
due := start.Add(time.Duration(float64(started*int64(l.chunkBlocks)*int64(l.blockSize)) / float64(bytesPerSecond) * float64(time.Second)))
if d := time.Until(due); d > 0 {
t := time.NewTimer(d)
select {
case <-t.C:
case <-walk.Done():
t.Stop()
return quit(context.Cause(walk))
case <-l.ctx.Done():
t.Stop()
return quit(errChunkLayerClosed)
}
}
}
release, err := l.admitFill(walk, stop)
if err != nil {
p.Deferred++
@@ -110,6 +134,7 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error
if f == nil {
continue // resolved meanwhile
}
started++
select {
case <-f.done:
case <-walk.Done():
@@ -406,3 +406,20 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) {
t.Fatalf("absent after the walk: %d, want 0", n)
}
}
// The walker's byte pace bounds the fill rate: 8 chunks at 4 chunks/s take
// at least (8-1)/4 s.
func TestHydrateAll_PacedByByteRate(t *testing.T) {
fastWalker(t)
_, layer, _, _ := hydrationFixture(t, 2, 64)
rate := int64(4 * ctChunkBytes)
start := time.Now()
p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate)
took := time.Since(start)
if err != nil || p.Remaining != 0 {
t.Fatalf("paced walk: %+v %v", p, err)
}
if min := time.Duration(p.Filled-1) * time.Second / 4; took < min {
t.Fatalf("%d fills at %d B/s took %v, want at least %v", p.Filled, rate, took, min)
}
}
+11 -1
View File
@@ -116,6 +116,9 @@ type chunkLayerImpl struct {
dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD
inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed
allDirty bool // a BASE block landed: every chunk is dirty
// own names the chunks OwnBatch re-uploads under this layer's own keys in
// the cut it runs (set and cleared under capMu, read under stMu).
own map[uint64]bool
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkMut counts the mutations of each chunk: every dirty-map insert
@@ -850,6 +853,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
candidates[i] = true
}
}
for idx := range l.own {
if !l.absent[idx] { // a re-own reads the local copy, never fetches
candidates[idx] = true
}
}
// A staged chunk stands for the barrier copy while no write reached
// it since staging (its version is unchanged) and HEAD is the one it
// was compared against.
@@ -973,7 +981,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
c.birth = births[c.idx]
ref, had := baseHead.Chunks[c.idx]
switch {
case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum:
case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum && c.key == "":
// A chunk equal to HEAD is skipped unless streamCutPayloads
// uploaded it under a new key: a re-owned chunk (OwnBatch).
st.UnchangedChunks++
continue
case c.zero:
+96
View File
@@ -0,0 +1,96 @@
package storage
import (
"context"
"sort"
)
// OwnProgress reports one OwnBatch call.
// - Owned: foreign chunks this call's cut re-uploaded under own keys.
// - Remaining: chunks HEAD still names with a foreign key after the call.
// - NotLocal: of those, chunks not local yet (the hydrate walker fills them).
type OwnProgress struct {
Owned int
Remaining int
NotLocal int
}
// OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n
// chunks, lowest index first, whose HEAD key is foreign (foreign reports
// whether a key names another volume's object) and that are local, and cuts
// with them as candidates: each is uploaded under a new own key under the
// cut's intent and published by the cut's one HEAD CAS, even when its bytes
// equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut
// is an ordinary cut, so guest writes since the last HEAD go with it. With
// nothing to own it runs no cut. A failed cut leaves HEAD as it was; the next
// call picks again from the current HEAD.
func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (OwnProgress, error) {
l.capMu.Lock()
defer l.capMu.Unlock()
l.stMu.Lock()
var picked []uint64
for _, idx := range sortedForeign(l.head.Chunks, foreign) {
if len(picked) < n && !l.absent[idx] {
picked = append(picked, idx)
}
}
if len(picked) == 0 {
p := l.ownProgressLocked(foreign)
l.stMu.Unlock()
return p.OwnProgress, nil
}
l.own = make(map[uint64]bool, len(picked))
for _, idx := range picked {
l.own[idx] = true
}
l.stMu.Unlock()
_, err := l.captureLocked(ctx, false)
l.stMu.Lock()
l.own = nil
p := l.ownProgressLocked(foreign)
l.stMu.Unlock()
if err == nil {
for _, idx := range picked {
if ref, ok := p.head[idx]; !ok || !foreign(ref.Key) {
p.Owned++
}
}
}
return p.OwnProgress, err
}
type ownCount struct {
OwnProgress
head map[uint64]chunkRef
}
// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu.
func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount {
c := ownCount{head: l.head.Chunks}
for _, idx := range sortedForeign(l.head.Chunks, foreign) {
c.Remaining++
if l.absent[idx] {
c.NotLocal++
}
}
return c
}
func sortedForeign(chunks map[uint64]chunkRef, foreign func(string) bool) []uint64 {
var out []uint64
for idx, ref := range chunks {
if foreign(ref.Key) {
out = append(out, idx)
}
}
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
return out
}
// owning reports whether chunk idx is re-owned by the running OwnBatch cut:
// it is uploaded under a new own key even when its bytes equal HEAD's.
func (l *chunkLayerImpl) owning(idx uint64) bool {
l.stMu.Lock()
defer l.stMu.Unlock()
return l.own[idx]
}
@@ -0,0 +1,96 @@
package storage
import (
"bytes"
"context"
"strings"
"testing"
)
func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") }
func ownCtx(t *testing.T) context.Context { return boundedCtx(t, context.Background()) }
// M6.Restore.Owning>Owning: each batch is one cut that re-uploads at most n
// foreign chunks under own keys, the image unchanged, until none is left.
func TestOwnBatch_BoundedBatchesReplaceEveryForeignKey(t *testing.T) {
fastWalker(t)
_, layer, remote, _ := hydrationFixture(t, 2, 64)
before := remote.stats()
want := remote.imageOf(t, before.head)
if p, err := layer.HydrateAll(ownCtx(t)); err != nil || p.Remaining != 0 {
t.Fatalf("hydrate: %+v %v", p, err)
}
total := ctNumBlocks / ctChunkBlocks
left := total
for left > 0 {
puts := remote.stats().puts
cas := remote.stats().cas
p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign)
if err != nil {
t.Fatal(err)
}
step := min(3, left)
if p.Owned != step || p.Remaining != left-step || p.NotLocal != 0 {
t.Fatalf("batch: %+v, want %d owned and %d remaining", p, step, left-step)
}
if got := remote.stats().puts - puts; got != step {
t.Fatalf("batch uploaded %d chunks, want exactly %d (bounded)", got, step)
}
if got := remote.stats().cas - cas; got != 1 {
t.Fatalf("batch made %d HEAD CAS, want one", got)
}
left -= step
}
after := remote.stats().head
for idx, ref := range after.Chunks {
if seedForeign(ref.Key) {
t.Fatalf("chunk %d still foreign after the last batch: %s", idx, ref.Key)
}
}
if !bytes.Equal(remote.imageOf(t, after), want) {
t.Fatal("owning changed the volume image")
}
cas := remote.stats().cas
if p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign); err != nil || p != (OwnProgress{}) || remote.stats().cas != cas {
t.Fatalf("nothing left to own must run no cut: %+v %v", p, err)
}
}
// A chunk not local yet is never fetched by a batch: it waits for the walker.
func TestOwnBatch_SkipsChunksNotLocal(t *testing.T) {
_, layer, remote, _ := hydrationFixture(t, 2, 64)
before := remote.stats()
p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign)
total := ctNumBlocks / ctChunkBlocks
if err != nil || p.Owned != 0 || p.Remaining != total || p.NotLocal != total {
t.Fatalf("batch before any hydration: %+v %v", p, err)
}
after := remote.stats()
if after.cas != before.cas || after.gets != before.gets {
t.Fatalf("a batch with nothing local cut or fetched: cas %d->%d gets %d->%d", before.cas, after.cas, before.gets, after.gets)
}
}
// A batch is an ordinary cut: a guest write since the last HEAD goes with it.
func TestOwnBatch_CarriesGuestWrites(t *testing.T) {
fastWalker(t)
s, layer, remote, _ := hydrationFixture(t, 2, 64)
if _, err := layer.HydrateAll(ownCtx(t)); err != nil {
t.Fatal(err)
}
if _, err := s.Write(ctChunkBlocks*6+1, makeBlock(ctBlockSize, 0xAB)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if _, err := layer.OwnBatch(ownCtx(t), 2, seedForeign); err != nil {
t.Fatal(err)
}
img := remote.imageOf(t, remote.stats().head)
off := (ctChunkBlocks*6 + 1) * ctBlockSize
if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xAB)) {
t.Fatal("the guest write did not reach HEAD with the batch")
}
}