storage: one free-space read per cut for staging and the window; a zero cap shows its cause (no_room_to_cut, free_space_unreadable) in stats and abort counts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-21 05:30:15 -08:00
1 parent 3204537cb5
commit dad0b347d3
7 files changed
+166 -68

No files matched your search

+48 -6
View File
@@ -26,19 +26,57 @@ const defaultCOWSpillLimit = 1 << 30
// on top of leaving half of the rest.
const cowSpillFreeReserve = 1 << 30
var (
// errCutNoRoom: the free space leaves this cut no side-file room.
errCutNoRoom = errors.New("storage: no room to cut")
// errCutFreeUnreadable: the free space could not be read, so this cut
// has no side-file room.
errCutFreeUnreadable = errors.New("storage: free space unreadable")
)
// cowSpillCap is one cut's side-file cap. cause is set when the free space
// made it zero: errCutNoRoom or errCutFreeUnreadable.
type cowSpillCap struct {
bytes int64
cause error
}
// cowSpillLimit is this cut's side-file cap: COWSpillLimit, lowered to
// half the free space minus cowSpillFreeReserve when COWSpillFree is set.
func (l *chunkLayerImpl) cowSpillLimit() int64 {
// A read error gives a cap of 0 with its own cause.
func (l *chunkLayerImpl) cowSpillLimit() cowSpillCap {
limit := l.cfg.COWSpillLimit
if l.cfg.COWSpillFree == nil {
return limit
return cowSpillCap{bytes: limit}
}
free, err := l.cfg.COWSpillFree()
if err != nil {
free = 0
return cowSpillCap{cause: fmt.Errorf("%w: %w", errCutFreeUnreadable, err)}
}
return max(0, min(limit, free/2-cowSpillFreeReserve))
c := cowSpillCap{bytes: max(0, min(limit, free/2-cowSpillFreeReserve))}
if c.bytes == 0 {
c.cause = errCutNoRoom
}
return c
}
// readCutSpill reads this cut's side-file cap once, for both the staging
// bound and the copy window, and records it in the stats.
func (l *chunkLayerImpl) readCutSpill() cowSpillCap {
c := l.cowSpillLimit()
reason := ""
switch {
case errors.Is(c.cause, errCutFreeUnreadable):
reason = "free_space_unreadable"
case errors.Is(c.cause, errCutNoRoom):
reason = "no_room_to_cut"
}
l.stMu.Lock()
l.stats.COWSpillCap, l.stats.COWSpillCapReason = c.bytes, reason
l.stMu.Unlock()
return c
}
const (
cowPending uint8 = iota
cowCopying
@@ -86,6 +124,7 @@ type cutCOWWindow struct {
memory int64
spillBytes int64 // bytes written to the side file; at most spillLimit
spillLimit int64
spillCause error // why spillLimit is 0, when the free space made it so
chunkBytes int64
memoryLimit int64
saverSlots chan struct{}
@@ -161,12 +200,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() {
}
// The caller owns captureMu exclusive, so no writer can miss this publication.
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) {
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) {
size := uint64(l.blockSize) * l.chunkBlocks
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cowSpillLimit(), chunkBytes: int64(size)}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
w.ctx, w.cancel = context.WithCancel(context.Background())
_, reserved, limit := l.cutPayloadWorkers()
savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size))))
@@ -391,6 +430,9 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error
// The side file is sparse but its saved chunks are real bytes on the
// volume's filesystem: abort the cut (retried) instead of filling it.
w.mu.Unlock()
if w.spillCause != nil {
return fmt.Errorf("%w: %w: %w: COW spill cap is 0", errCutCOWAborted, errCutCOWCapacity, w.spillCause)
}
return fmt.Errorf("%w: %w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, errCutCOWCapacity, w.spillLimit)
} else {
w.spillBytes += w.chunkBytes
@@ -3,18 +3,19 @@ package storage
import (
"context"
"errors"
"strings"
"fmt"
"sync/atomic"
"testing"
)
// The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read
// from COWSpillFree on every call; an error counts as no free space, and
// without COWSpillFree the configured cap applies.
// from COWSpillFree on every call. A cap of 0 carries its cause: no room
// (the free space is within the reserve) or a read error, which is not
// reported as a full disk. Without COWSpillFree the configured cap applies.
func TestCOWSpillLimit_FromFreeSpace(t *testing.T) {
l := &chunkLayerImpl{cfg: ChunkLayerConfig{COWSpillLimit: 4 << 30}}
if got := l.cowSpillLimit(); got != 4<<30 {
t.Fatalf("no free-space reader: cap %d, want the configured 4 GiB", got)
if got := l.cowSpillLimit(); got.bytes != 4<<30 || got.cause != nil {
t.Fatalf("no free-space reader: cap %+v, want the configured 4 GiB", got)
}
var free atomic.Int64
var reads atomic.Int64
@@ -28,74 +29,116 @@ func TestCOWSpillLimit_FromFreeSpace(t *testing.T) {
}
for _, c := range []struct {
free, want int64
cause error
}{
{100 << 30, 4 << 30}, // plenty: the configured cap
{6 << 30, 2 << 30}, // 6 GiB free: half is 3, minus the 1 GiB reserve
{2 << 30, 0}, // half the free space is all reserve
{1 << 30, 0}, // below the reserve: never negative
{10<<30 + 2, 4 << 30}, // the configured cap still bounds it
{3 << 30, (3<<30)/2 - (1 << 30)}, // 1.5 GiB - 1 GiB
{100 << 30, 4 << 30, nil}, // plenty: the configured cap
{6 << 30, 2 << 30, nil}, // 6 GiB free: half is 3, minus the 1 GiB reserve
{2 << 30, 0, errCutNoRoom}, // half the free space is all reserve
{1 << 30, 0, errCutNoRoom}, // below the reserve: never negative
{10<<30 + 2, 4 << 30, nil}, // the configured cap still bounds it
{3 << 30, (3<<30)/2 - (1 << 30), nil}, // 1.5 GiB - 1 GiB
} {
free.Store(c.free)
if got := l.cowSpillLimit(); got != c.want {
t.Fatalf("free %d: cap %d, want %d", c.free, got, c.want)
if got := l.cowSpillLimit(); got.bytes != c.want || !errors.Is(got.cause, c.cause) || (c.cause == nil) != (got.cause == nil) {
t.Fatalf("free %d: cap %+v, want %d (cause %v)", c.free, got, c.want, c.cause)
}
}
if reads.Load() != 6 {
t.Fatalf("free space read %d times for 6 calls; want once per call", reads.Load())
}
fail.Store(true)
if got := l.cowSpillLimit(); got != 0 {
t.Fatalf("free-space error: cap %d, want 0 (no free space)", got)
if got := l.cowSpillLimit(); got.bytes != 0 || !errors.Is(got.cause, errCutFreeUnreadable) || errors.Is(got.cause, errCutNoRoom) {
t.Fatalf("free-space read error: cap %+v, want 0 with cause free_space_unreadable (not no room)", got)
}
}
// The copy window reads the free space when it opens, not only when the
// cut starts staging: free space that shrinks below the reserve between
// the two gives the window a cap of 0, so once the in-memory budget is used
// a save aborts that cut (the guest write completes); after space is freed
// the cap reads the new value.
func TestCutCOWV3_SpillCapFollowsFreeSpaceEachCut(t *testing.T) {
// Each cut reads the free space once, for both the staging bound and the
// window, and shows the cap in the stats: the configured cap with ample
// free space; 0 with reason no_room_to_cut when the free space is within
// the reserve (the cut still completes by staging before the barrier);
// 0 with reason free_space_unreadable when the read fails.
func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) {
s, l, _, gate := cowFixture(t)
gate.unblock()
var free, reads atomic.Int64
free.Store(100 << 30)
var fail atomic.Bool
l.cfg.COWSpillFree = func() (int64, error) {
if reads.Add(1) == 2 { // the window opens: the filesystem has filled up
free.Store(1 << 30)
reads.Add(1)
if fail.Load() {
return 0, errors.New("statfs failed")
}
return free.Load(), nil
}
cutDone, cutErr := cowStartCut(t, l, gate)
w := l.cowActive.Load()
w.mu.Lock()
w.memory = cutCOWMemoryLimit // the in-memory budget is used
limit := w.spillLimit
w.mu.Unlock()
if limit != 0 {
t.Fatalf("window cap %d with 1 GiB free; want 0", limit)
for i, c := range []struct {
free int64
fail bool
cap int64
reason string
}{
{100 << 30, false, l.cfg.COWSpillLimit, ""},
{1 << 30, false, 0, "no_room_to_cut"},
{100 << 30, true, 0, "free_space_unreadable"},
} {
free.Store(c.free)
fail.Store(c.fail)
if _, err := s.Write(uint32(i*ctChunkBlocks+1), makeBlock(ctBlockSize, byte(0x60+i))); err != nil {
t.Fatal(err)
}
before := reads.Load()
if _, err := l.Cut(context.Background()); err != nil && c.reason == "" {
t.Fatal(err)
}
if n := reads.Load() - before; n != 1 {
t.Fatalf("cut %d read the free space %d times; want once", i, n)
}
if st := l.Stats(); st.COWSpillCap != c.cap || st.COWSpillCapReason != c.reason {
t.Fatalf("cut %d: stats cap %d reason %q; want %d %q", i, st.COWSpillCap, st.COWSpillCapReason, c.cap, c.reason)
}
}
writeDone := make(chan struct{})
writeErr := make(chan error, 1)
// Registered before the writer starts: release the copier and join the
// writer (bounded) whatever the test's outcome.
t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "free-space-cap writer cleanup") })
go func() {
defer close(writeDone)
_, err := s.Write(5, makeBlock(ctBlockSize, 0xd6))
writeErr <- err
}()
cowWaitSignal(t, writeDone, "guest write at the free-space cap")
if err := <-writeErr; err != nil {
t.Fatal("guest write refused at the free-space cap:", err)
}
gate.unblock()
cowWaitSignal(t, cutDone, "cut at the free-space cap")
if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !strings.Contains(err.Error(), "cap of 0 bytes") {
t.Fatalf("cut at a 0 cap: %v, want the cap abort", err)
}
free.Store(100 << 30)
if got := l.cowSpillLimit(); got != l.cfg.COWSpillLimit {
t.Fatalf("after freeing space the cap is %d, want the configured %d", got, l.cfg.COWSpillLimit)
}
// A save that meets a zero cap aborts the cut under the cap's own cause:
// no_room_to_cut or free_space_unreadable, not cow_capacity; the guest
// write completes and the next cut is not blocked.
func TestCutCOWV3_ZeroCapAbortIsCountedByItsCause(t *testing.T) {
for _, c := range []struct {
cause error
reason string
}{
{errCutNoRoom, "no_room_to_cut"},
{fmt.Errorf("%w: %w", errCutFreeUnreadable, errors.New("statfs failed")), "free_space_unreadable"},
} {
t.Run(c.reason, func(t *testing.T) {
s, l, _, gate := cowFixture(t)
cutDone, cutErr := cowStartCut(t, l, gate)
w := l.cowActive.Load()
w.mu.Lock()
w.memory = cutCOWMemoryLimit // the in-memory budget is used
w.spillLimit, w.spillCause = 0, c.cause
w.mu.Unlock()
writeDone := make(chan struct{})
writeErr := make(chan error, 1)
// Registered before the writer starts: release the copier and
// join the writer (bounded) whatever the test's outcome.
t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "zero-cap writer cleanup") })
go func() {
defer close(writeDone)
_, err := s.Write(5, makeBlock(ctBlockSize, 0xd7))
writeErr <- err
}()
cowWaitSignal(t, writeDone, "guest write at a zero cap")
if err := <-writeErr; err != nil {
t.Fatal("guest write refused at a zero cap:", err)
}
gate.unblock()
cowWaitSignal(t, cutDone, "cut at a zero cap")
if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !errors.Is(err, c.cause) {
t.Fatalf("cut at a zero cap: %v, want an abort carrying %v", err, c.cause)
}
if st := l.Stats(); st.CutsAborted[c.reason] != 1 || st.CutsAborted["cow_capacity"] != 0 {
t.Fatalf("aborts %v; want one %s and no cow_capacity", st.CutsAborted, c.reason)
}
})
}
}
@@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) {
for i := 0; i < candidates; i++ {
pending[uint64(i)] = true
}
w, err := l.installCOWWindow(pending, nil, nil)
w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit())
if err != nil {
t.Fatal(err)
}
+9 -4
View File
@@ -765,8 +765,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
var staged map[uint64]stagedChunk
var intents []string
_, guestFrozen := FrozenDetachFromContext(ctx)
spill := l.readCutSpill()
if !guestFrozen {
staged, intents, err = l.stage(ctx, &st)
staged, intents, err = l.stage(ctx, &st, spill.bytes)
}
if st.UploadedBytes > 0 {
st.PayloadNs += time.Since(stageStart).Nanoseconds()
@@ -911,7 +912,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
{
var w *cutCOWWindow
windowStart := time.Now()
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill)
if copyErr == nil {
w.budget = budget
}
@@ -1405,6 +1406,10 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error
switch {
case errors.Is(err, errCutSaverCapacity):
abortReason = "saver_capacity"
case errors.Is(err, errCutFreeUnreadable):
abortReason = "free_space_unreadable"
case errors.Is(err, errCutNoRoom):
abortReason = "no_room_to_cut"
case errors.Is(err, errCutCOWCapacity):
abortReason = "cow_capacity"
case errors.Is(err, errCutBudgetRevoked):
@@ -1540,10 +1545,10 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) {
// stage uploads large native dirty sets through logical reads, before fixing H.
// It stops when the spill-budget remainder is reached or a round makes no
// progress. Versions/HEAD generation bind every reusable immutable result.
func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) {
func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, []string, error) {
// Leave at most half the side budget exposed at the barrier. Streaming
// staging uses no local payload file, even for a much larger image.
bound := int(l.cowSpillLimit() / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
bound := int(spillCap / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
staged := map[uint64]stagedChunk{}
var intents []string
+7 -1
View File
@@ -486,7 +486,7 @@ type chunkLayerStats struct {
CutsNoop uint64 // cuts with nothing new (no CAS)
CutsFailed uint64 // every other cut failure
CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached
CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload
CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload
CASConflicts uint64 // HEAD CAS precondition failures
CASUnknown uint64 // HEAD CAS results still unresolved after the re-read
PendingUnresolved bool // an unresolved HEAD proposal is held now
@@ -503,6 +503,12 @@ type chunkLayerStats struct {
// AbsentChunks is the number of HEAD-named chunks still absent with a
// block not local (what HydrateAll would still fetch); 0 = fully local.
AbsentChunks int
// COWSpillCap is the last cut's side-file cap in bytes, read once per
// cut; COWSpillCapReason is why it is 0, when the free space made it so:
// no_room_to_cut (half the free space is within the 1 GiB reserve) or
// free_space_unreadable (the free space could not be read).
COWSpillCap int64
COWSpillCapReason string `json:",omitempty"`
}
// chunkCutResult is the outcome of one successful cut.
+1 -1
View File
@@ -678,4 +678,4 @@ Frozen estimate reporting: a tail above the existing 60 s estimator ceiling repo
| Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap |
|---|---|---|---|---|---|
| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; free space read at each cut (staging bound and window open); a read error counts as no free space; off Linux, the configured cap | the saver: `core/storage/chunk_cut_cow.go` `cowSpillLimit`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (`cow_capacity`, retryable); the guest write completes and nothing partial is published |
| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; the free space is read once per cut and that cap bounds both staging and the copy window; off Linux, the configured cap. Shown per cut in the layer stats (`COWSpillCap`, `COWSpillCapReason`: `no_room_to_cut` when the free space is within the reserve, `free_space_unreadable` when the read fails) | the saver: `core/storage/chunk_cut_cow.go` `readCutSpill`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (retryable), counted as `cow_capacity`, or as `no_room_to_cut` / `free_space_unreadable` when the free space made the cap 0; the guest write completes and nothing partial is published |
+3 -1
View File
@@ -222,7 +222,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) |
| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure |
| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached |
| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload |
| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload |
| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures |
| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read |
| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now |
@@ -275,6 +275,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) |
| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. |
| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. |
| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). |
| `Volumes[].Chunk.Stats.COWSpillCapReason` | string | (group of `COWSpillCap`) COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). (omitted when empty) |
| `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) |
| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |