durable, blockvolume: automatic cut scheduler (timer + dirty threshold)

The volume's automatic cuts follow the W3 ruling:
- Timer: a cut is due once ChunkCaptureInterval has passed since the
  last successful cut of any kind; an explicit Cut, Snapshot or Detach
  restarts it.
- Threshold: a cut is due once ChunkDirtyThreshold chunks are dirty
  since the last HEAD. Whichever fires first triggers; zero disables
  either.
- Automatic cuts are at least 1 s apart.
- A failed automatic cut resets nothing and is retried after a backoff
  doubling from 1 s to 30 s.
- A successful cut, including a no-op one (no CAS), clears the backoff
  and restarts the timer.

The decision is a pure policy (cutPolicy), tested with explicit times.
The provider loop polls the layer's Stats every 100 ms for the dirty
count and the last successful cut.

blockvolume defaults: --chunk-capture-interval=30s, and a new
--chunk-dirty-threshold=64 (256 MiB of 4 MiB chunks). The --chunk-*
flags stay refused with other implementations when set away from their
defaults.

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:16 -08:00
1 parent b2862307ac
commit 022c9077dd
7 files changed
+359 -12

No files matched your search

+12 -2
View File
@@ -18,7 +18,11 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage"
)
const defaultChunkPath = "/swblock/chunks"
const (
defaultChunkPath = "/swblock/chunks"
defaultChunkCaptureInterval = 30 * time.Second
defaultChunkDirtyThreshold = 64 // chunks, 256 MiB at 4 MiB chunks
)
type chunkFlags struct {
filer string
@@ -26,6 +30,7 @@ type chunkFlags struct {
collection string
replication string
captureInterval time.Duration
dirtyThreshold int
// controlEndpoint mounts the /chunk/* routes on the status listener.
controlEndpoint bool
}
@@ -33,7 +38,9 @@ type chunkFlags struct {
func validateChunkFlags(f flags) error {
c := f.chunk
if f.durableImpl != "walstore-chunk" {
if c.filer != "" || c.collection != "" || c.replication != "" || c.captureInterval != 0 || c.path != defaultChunkPath || c.controlEndpoint {
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
c.controlEndpoint {
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
}
return nil
@@ -53,6 +60,9 @@ func validateChunkFlags(f flags) error {
if c.captureInterval < 0 {
return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval)
}
if c.dirtyThreshold < 0 {
return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold)
}
return nil
}
@@ -27,6 +27,21 @@ func TestWALStoreChunkFlags(t *testing.T) {
if err != nil || !f.chunk.controlEndpoint {
t.Fatalf("walstore-chunk with the control endpoint: %+v %v", f.chunk, err)
}
d, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"))
if err != nil {
t.Fatal(err)
}
if d.chunk.captureInterval != 30*time.Second || d.chunk.dirtyThreshold != 64 {
t.Fatalf("scheduler defaults interval %s threshold %d, want 30s and 64", d.chunk.captureInterval, d.chunk.dirtyThreshold)
}
off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
"--chunk-capture-interval=0", "--chunk-dirty-threshold=0"))
if err != nil || off.chunk.captureInterval != 0 || off.chunk.dirtyThreshold != 0 {
t.Fatalf("disabling both triggers: %+v %v", off.chunk, err)
}
if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore")); err != nil {
t.Fatalf("walstore with the chunk defaults untouched: %v", err)
}
refused := map[string][]string{
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
@@ -39,6 +54,9 @@ func TestWALStoreChunkFlags(t *testing.T) {
"--chunk-control-endpoint"),
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
"--chunk-filer=x:1", "--chunk-control-endpoint"),
"negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"),
"threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"),
"interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"),
}
for name, args := range refused {
if _, err := parseFlags(args); err == nil {
+3 -1
View File
@@ -174,7 +174,8 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)")
fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)")
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", 0, "walstore-chunk: publish a cut every interval while healthy; 0 = only on demand")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 disables the timer")
fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: automatic cut once this many chunks are dirty since the last HEAD; 0 disables the threshold")
fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener")
fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)")
fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create")
@@ -552,6 +553,7 @@ func run(f flags) int {
if cfg.Impl == durable.ImplWALStoreChunk {
chunk, chunkErr = newChunkWiring(f.chunk)
cfg.ChunkCaptureInterval = f.chunk.captureInterval
cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold
cfg.ChunkHolder = chunkHolder(f)
if chunkErr == nil {
cfg.ChunkRemoteFor = chunk.remoteFor
@@ -0,0 +1,102 @@
package durable
// The automatic cut policy (B9 W3 ruling), with explicit times.
import (
"errors"
"testing"
"time"
)
var t0 = time.Unix(1_700_000_000, 0)
func testPolicy() cutPolicy {
return cutPolicy{interval: 30 * time.Second, threshold: 64, minSpacing: time.Second, backoffMin: time.Second, backoffMax: 30 * time.Second}
}
func at(d time.Duration) time.Time { return t0.Add(d) }
func TestCutPolicy_TimerAndThresholdWhicheverFirst(t *testing.T) {
pol := testPolicy()
s := cutSchedule{lastSuccess: t0}
if r, ok := pol.due(s, at(29*time.Second), 63); ok {
t.Fatalf("due (%s) before the interval and below the threshold", r)
}
if r, ok := pol.due(s, at(30*time.Second), 0); !ok || r != "periodic" {
t.Fatalf("at the interval with nothing dirty: %q %v; want a periodic cut (a no-op cut still resets the timer)", r, ok)
}
if r, ok := pol.due(s, at(5*time.Second), 64); !ok || r != "threshold" {
t.Fatalf("at the threshold: %q %v; want a threshold cut", r, ok)
}
pol.interval, pol.threshold = 0, 0
if r, ok := pol.due(s, at(time.Hour), 1<<20); ok {
t.Fatalf("due (%s) with timer and threshold disabled", r)
}
}
func TestCutPolicy_AnySuccessfulCutResetsTheTimer(t *testing.T) {
pol := testPolicy()
s := cutSchedule{lastSuccess: t0}
// An explicit Cut, Snapshot or Detach succeeded at 20 s: the layer
// reports it and the timer restarts from there.
s = s.observe(at(20 * time.Second).UnixNano())
if r, ok := pol.due(s, at(45*time.Second), 0); ok {
t.Fatalf("due (%s) 25 s after an explicit cut", r)
}
if _, ok := pol.due(s, at(50*time.Second), 0); !ok {
t.Fatal("not due 30 s after the explicit cut")
}
// An older report never moves the timer back.
if got := s.observe(at(5 * time.Second).UnixNano()); !got.lastSuccess.Equal(at(20 * time.Second)) {
t.Fatalf("older report moved the timer to %v", got.lastSuccess)
}
// An automatic success restarts it too.
s = pol.after(s, at(50*time.Second), at(50*time.Second+200*time.Millisecond), nil)
if _, ok := pol.due(s, at(79*time.Second), 0); ok {
t.Fatal("due less than 30 s after an automatic success")
}
}
func TestCutPolicy_MinimumSpacingBetweenAutomaticCuts(t *testing.T) {
pol := testPolicy()
s := cutSchedule{lastSuccess: t0}
s = pol.after(s, at(10*time.Second), at(10*time.Second+50*time.Millisecond), nil)
if r, ok := pol.due(s, at(10*time.Second+900*time.Millisecond), 1000); ok {
t.Fatalf("hot writer at the threshold cut again after 0.9 s (%s)", r)
}
if _, ok := pol.due(s, at(11*time.Second), 1000); !ok {
t.Fatal("threshold cut not due 1 s after the last automatic cut")
}
}
func TestCutPolicy_FailureBacksOffAndResetsNothing(t *testing.T) {
pol := testPolicy()
s := cutSchedule{lastSuccess: t0}
fail := errors.New("remote unavailable")
now := at(30 * time.Second)
var waits []time.Duration
for i := 0; i < 7; i++ {
s = pol.after(s, now, now, fail)
waits = append(waits, s.backoff)
if _, ok := pol.due(s, now.Add(s.backoff-time.Millisecond), 1000); ok {
t.Fatalf("retry %d due before its backoff %s", i, s.backoff)
}
now = now.Add(s.backoff)
if _, ok := pol.due(s, now, 0); !ok {
t.Fatalf("retry %d not due after its backoff %s (the failure must not reset the timer)", i, s.backoff)
}
}
want := []time.Duration{1, 2, 4, 8, 16, 30, 30}
for i, w := range want {
if waits[i] != w*time.Second {
t.Fatalf("backoffs %v, want %v seconds", waits, want)
}
}
if !s.lastSuccess.Equal(t0) {
t.Fatalf("a failure moved the last success to %v", s.lastSuccess)
}
s = pol.after(s, now, now, nil)
if s.backoff != 0 || !s.retryAt.IsZero() || !s.lastSuccess.Equal(now) {
t.Fatalf("success did not clear the backoff: %+v", s)
}
}
@@ -143,10 +143,15 @@ type ProviderConfig struct {
// ChunkReadMissTimeout bounds one remote fetch of an absent block.
// Zero: the storage default.
ChunkReadMissTimeout time.Duration
// ChunkCaptureInterval runs a cut every interval while the volume's
// projection is healthy. Zero: cuts only on CaptureVolume and
// MakeVolumeRemoteDurable.
// ChunkCaptureInterval: an automatic cut is due once this long has
// passed since the volume's last successful cut (of any kind). Zero
// disables the timer.
ChunkCaptureInterval time.Duration
// ChunkDirtyThreshold: an automatic cut is due once this many chunks
// are dirty since the last HEAD. Zero disables the threshold. With
// both zero there are no automatic cuts (only CaptureVolume and
// MakeVolumeRemoteDurable).
ChunkDirtyThreshold int
}
// DurableProvider is the production frontend.Provider implementation.
@@ -208,7 +208,7 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
h.backend.mu.Lock()
h.backend.chunkFenced = layer.Fenced
h.backend.mu.Unlock()
if p.cfg.ChunkCaptureInterval > 0 {
if p.cfg.ChunkCaptureInterval > 0 || p.cfg.ChunkDirtyThreshold > 0 {
ctx, cancel := context.WithCancel(context.Background())
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
go p.chunkLoop(ctx, volumeID, layer, h.chunkDone)
@@ -443,11 +443,100 @@ func syncParentDir(path string) error {
return nil
}
// chunkLoop takes a periodic cut. A refused cut (not a healthy primary,
// BASE install) is normal and skipped quietly.
// Cut scheduler constants (B9 W3 ruling).
const (
chunkSchedulePoll = 100 * time.Millisecond
chunkCutMinSpacing = time.Second
chunkCutBackoffMin = time.Second
chunkCutBackoffMax = 30 * time.Second
)
// cutPolicy decides when an automatic cut is due:
// - the timer fires once interval has passed since the last successful
// cut of any kind (explicit Cut, Snapshot and Detach included);
// - the threshold fires once threshold chunks are dirty since the last
// HEAD;
// - whichever fires first triggers; zero disables either;
// - automatic cuts are at least minSpacing apart (explicit ones are not
// subject to it);
// - a failed automatic cut resets nothing and is retried after a backoff
// doubling from backoffMin to backoffMax; a success (a no-op cut
// included) clears the backoff and restarts the timer.
type cutPolicy struct {
interval, minSpacing, backoffMin, backoffMax time.Duration
threshold int
}
type cutSchedule struct {
lastSuccess time.Time // last successful cut of any kind
lastAuto time.Time // start of the last automatic cut
retryAt time.Time // a failed automatic cut's backoff ends here
backoff time.Duration
}
// observe takes in a successful cut the layer reports (any trigger).
func (s cutSchedule) observe(lastCutNs int64) cutSchedule {
if lastCutNs > 0 {
if c := time.Unix(0, lastCutNs); c.After(s.lastSuccess) {
s.lastSuccess = c
}
}
return s
}
// due reports whether an automatic cut is due at now, and why.
func (pol cutPolicy) due(s cutSchedule, now time.Time, dirty int) (string, bool) {
if now.Before(s.retryAt) {
return "", false
}
if !s.lastAuto.IsZero() && now.Sub(s.lastAuto) < pol.minSpacing {
return "", false
}
if pol.interval > 0 && now.Sub(s.lastSuccess) >= pol.interval {
return "periodic", true
}
if pol.threshold > 0 && dirty >= pol.threshold {
return "threshold", true
}
return "", false
}
// after records the outcome of an automatic cut started at start.
func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSchedule {
s.lastAuto = start
if err == nil {
s.backoff, s.retryAt = 0, time.Time{}
if end.After(s.lastSuccess) {
s.lastSuccess = end
}
return s
}
switch {
case s.backoff == 0:
s.backoff = pol.backoffMin
case s.backoff*2 > pol.backoffMax:
s.backoff = pol.backoffMax
default:
s.backoff *= 2
}
s.retryAt = end.Add(s.backoff)
return s
}
// chunkLoop runs the volume's automatic cuts under cutPolicy. A refused
// cut (not a healthy primary of this lineage, BASE install) is expected
// and logged only when it is something else.
func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}) {
defer close(done)
t := time.NewTicker(p.cfg.ChunkCaptureInterval)
pol := cutPolicy{
interval: p.cfg.ChunkCaptureInterval,
threshold: p.cfg.ChunkDirtyThreshold,
minSpacing: chunkCutMinSpacing,
backoffMin: chunkCutBackoffMin,
backoffMax: chunkCutBackoffMax,
}
s := cutSchedule{lastSuccess: time.Now()}
t := time.NewTicker(chunkSchedulePoll)
defer t.Stop()
for {
select {
@@ -455,8 +544,17 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
return
case <-t.C:
}
if _, err := layer.Capture(ctx); err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
log.Printf("durable: chunk cut for volume=%s: %v", volumeID, err)
ls := layer.Stats()
s = s.observe(ls.LastCutNs)
start := time.Now()
reason, ok := pol.due(s, start, ls.DirtyChunks)
if !ok {
continue
}
_, err := layer.Cut(ctx)
s = pol.after(s, start, time.Now(), err)
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff)
}
}
}
@@ -0,0 +1,112 @@
package durable_test
// The automatic cut scheduler through the real provider loop.
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration, threshold int) *durable.DurableProvider {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkCaptureInterval: interval,
ChunkDirtyThreshold: threshold,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
func headGen(t *testing.T, remote storage.ChunkRemote) storage.ChunkHead {
t.Helper()
h, err := remote.GetHead(context.Background())
if err != nil {
t.Fatal(err)
}
return h
}
// With the timer off, enough dirty chunks trigger a cut on their own.
func TestWALStoreChunk_DirtyThresholdTriggersCut(t *testing.T) {
remote := storage.NewMemChunkRemote()
p := schedProvider(t, remote, 0, 2)
s := openRecovered(t, p)
if _, err := s.Write(1, block(0x01)); err != nil { // chunk 0
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
if h := headGen(t, remote); h.Gen != 0 {
t.Fatalf("cut below the threshold (HEAD gen %d)", h.Gen)
}
if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil { // chunk 1
t.Fatal(err)
}
deadline := time.Now().Add(15 * time.Second)
for {
h := headGen(t, remote)
if _, ok := h.Chunks[1]; ok && h.Gen >= 1 {
if _, ok := h.Chunks[0]; !ok {
t.Fatalf("threshold cut HEAD lacks chunk 0: %+v", h.Chunks)
}
return
}
if time.Now().After(deadline) {
t.Fatalf("no threshold cut after two dirty chunks (HEAD gen %d)", h.Gen)
}
time.Sleep(50 * time.Millisecond)
}
}
// An explicit cut restarts the timer of the running loop: the automatic
// cut comes one interval after it, not one interval after the loop began.
func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) {
const interval = 3 * time.Second
remote := storage.NewMemChunkRemote()
p := schedProvider(t, remote, interval, 0)
s := openRecovered(t, p)
begin := time.Now()
time.Sleep(2 * time.Second)
if _, err := s.Write(1, block(0x01)); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
explicit := time.Now()
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("explicit cut: HEAD gen %d, want 1", h.Gen)
}
if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil {
t.Fatal(err)
}
// Past the loop's own first deadline (begin + interval) but before
// explicit + interval: no automatic cut yet.
time.Sleep(time.Until(begin.Add(interval + 1200*time.Millisecond)))
if time.Now().After(explicit.Add(interval - 300*time.Millisecond)) {
t.Skip("scheduling too slow to separate the two deadlines on this host")
}
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("automatic cut %s after the explicit one (HEAD gen %d): the timer did not restart", time.Since(explicit), h.Gen)
}
deadline := explicit.Add(interval + 5*time.Second)
for {
if h := headGen(t, remote); h.Gen >= 2 {
return
}
if time.Now().After(deadline) {
t.Fatal("no automatic cut one interval after the explicit cut")
}
time.Sleep(50 * time.Millisecond)
}
}