From 6a89b14a8549696ce0014cbaa6cae1deebd05d54 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:47:32 -0800 Subject: [PATCH 01/15] test(chunkstore): batch-assign ranges and put rounds (red) Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/chunk_remote_round_test.go | 343 ++++++++++++++++++ .../frontend/chunkstore/swfs_batch_test.go | 240 ++++++++++++ 2 files changed, 583 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_batch_test.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go new file mode 100644 index 0000000000..cb4adfb98f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go @@ -0,0 +1,343 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// rangeFake is a blob store with batch reservations: each reserve hands out +// a new volume id; puts are recorded by fid. Hooks shape the replies. +type rangeFake struct { + *fakeBlobs + mu sync.Mutex + nextVid int + reserves []int // requested counts, in order + grant func(requested int) int + auth func() string + refuse func(fid string) error // non-nil: the put fails with it + puts []string + putAuth map[string]string + inflight int + peak int + hold chan struct{} // non-nil: reserve waits for it (or ctx) +} + +func newRangeFake() *rangeFake { + return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}} +} + +func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) { + b.mu.Lock() + b.reserves = append(b.reserves, n) + hold := b.hold + b.mu.Unlock() + if hold != nil { + select { + case <-hold: + case <-ctx.Done(): + return blobRange{}, ctx.Err() + } + } + b.mu.Lock() + defer b.mu.Unlock() + count := n + if b.grant != nil { + count = b.grant(n) + } + auth := "" + if b.auth != nil { + auth = b.auth() + } + vid := b.nextVid + b.nextVid++ + return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake", auth: auth}, nil +} + +func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error { + fid, err := r.fid(i) + if err != nil { + return err + } + b.mu.Lock() + b.puts = append(b.puts, fid) + b.putAuth[fid] = r.auth + refuse := b.refuse + b.mu.Unlock() + if refuse != nil { + if err := refuse(fid); err != nil { + return err + } + } + b.fakeBlobs.mu.Lock() + b.fakeBlobs.data[fid] = append([]byte(nil), data...) + b.fakeBlobs.mu.Unlock() + return nil +} + +func (b *rangeFake) reserveCounts() []int { + b.mu.Lock() + defer b.mu.Unlock() + return append([]int(nil), b.reserves...) +} + +func roundRemote(t *testing.T, b *rangeFake) *ChunkRemote { + t.Helper() + r, err := NewChunkRemote(newFakeFiler(), b, "/swblock/vols/v1") + if err != nil { + t.Fatal(err) + } + return r +} + +func roundKey(i int) string { return fmt.Sprintf("k%05d", i) } + +// putAll runs one round of n objects with w concurrent workers. +func putAll(t *testing.T, r *ChunkRemote, n, w int) error { + t.Helper() + rd := r.BeginPutRound(n, 4096) + var mu sync.Mutex + next := 0 + var first error + var wg sync.WaitGroup + for j := 0; j < w; j++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + mu.Lock() + i := next + next++ + mu.Unlock() + if i >= n { + return + } + if err := rd.Put(context.Background(), i, roundKey(i), []byte(roundKey(i))); err != nil { + mu.Lock() + if first == nil { + first = err + } + mu.Unlock() + } + } + }() + } + wg.Wait() + return first +} + +func checkBound(t *testing.T, r *ChunkRemote, n int) { + t.Helper() + for i := 0; i < n; i++ { + got, err := r.Get(context.Background(), roundKey(i)) + if err != nil || !bytes.Equal(got, []byte(roundKey(i))) { + t.Fatalf("key %d: %q %v", i, got, err) + } + } +} + +// D objects take G = min(8, ceil(D/64)) reservations, balanced across the +// groups; D = 0 makes none. Every key is bound to its own fid. +func TestChunkRound_GroupsPerRound(t *testing.T) { + for _, c := range []struct{ d, g int }{{0, 0}, {1, 1}, {64, 1}, {65, 2}, {512, 8}, {513, 8}, {1000, 8}} { + t.Run(fmt.Sprint(c.d), func(t *testing.T) { + b := newRangeFake() + r := roundRemote(t, b) + if err := putAll(t, r, c.d, 16); err != nil { + t.Fatal(err) + } + got := b.reserveCounts() + if len(got) != c.g { + t.Fatalf("%d reservations %v for %d objects, want %d", len(got), got, c.d, c.g) + } + total, lo, hi := 0, c.d, 0 + for _, n := range got { + total += n + lo, hi = min(lo, n), max(hi, n) + } + if total != c.d || (c.g > 0 && hi-lo > 1) { + t.Fatalf("reservations %v: want %d ids balanced within one", got, c.d) + } + checkBound(t, r, c.d) + seen := map[string]bool{} + for i := 0; i < c.d; i++ { + fid := r.fids[roundKey(i)] + if seen[fid] { + t.Fatalf("fid %s bound twice", fid) + } + seen[fid] = true + } + if a := r.AssignCounts(); a.Initial != int64(c.g) || a.Extra() != 0 { + t.Fatalf("assign counts %+v, want %d initial, no extras", a, c.g) + } + }) + } +} + +// A short grant is topped up by a reservation for the remainder, counted as +// an extra, not an initial assign. +func TestChunkRound_ShortGrantReservesRemainder(t *testing.T) { + b := newRangeFake() + first := true + b.grant = func(n int) int { + if first { + first = false + return n / 2 + } + return n + } + r := roundRemote(t, b) + if err := putAll(t, r, 10, 4); err != nil { + t.Fatal(err) + } + if got := b.reserveCounts(); len(got) != 2 || got[0] != 10 || got[1] != 5 { + t.Fatalf("reservations %v, want [10 5]", got) + } + checkBound(t, r, 10) + if a := r.AssignCounts(); a.Initial != 1 || a.Short != 1 || a.Extra() != 1 { + t.Fatalf("assign counts %+v", a) + } +} + +// A definite capacity refusal leaves objects already stored on the old range +// alone and moves the rest of the group to a fresh range; a volume that keeps +// refusing ends the round after a bounded number of replacements. +func TestChunkRound_CapacityRefusalReplacesRemainder(t *testing.T) { + b := newRangeFake() + b.refuse = func(fid string) error { + // The first volume is full from its third id on. + if fid == "1,0a0b0c0d0e_2" || fid == "1,0a0b0c0d0e_3" { + return errRangeRefused + } + return nil + } + r := roundRemote(t, b) + if err := putAll(t, r, 6, 1); err != nil { + t.Fatal(err) + } + checkBound(t, r, 6) + if r.fids[roundKey(0)] != "1,0a0b0c0d0e" || r.fids[roundKey(1)] != "1,0a0b0c0d0e_1" { + t.Fatalf("committed prefix moved: %s %s", r.fids[roundKey(0)], r.fids[roundKey(1)]) + } + if got := b.reserveCounts(); len(got) != 2 || got[1] != 4 { + t.Fatalf("reservations %v, want a fresh range for the remaining 4", got) + } + if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 { + t.Fatalf("assign counts %+v", a) + } + + b2 := newRangeFake() + b2.refuse = func(string) error { return errRangeRefused } + r2 := roundRemote(t, b2) + err := putAll(t, r2, 3, 1) + if !errors.Is(err, errRangeRefused) { + t.Fatalf("always-full volumes: %v; want the refusal after bounded replacements", err) + } + if got := b2.reserveCounts(); len(got) != 1+roundMaxReplacements { + t.Fatalf("%d reservations %v; want 1 + %d replacements, then stop", len(got), got, roundMaxReplacements) + } +} + +// An expired token is never sent: the remainder gets a fresh range. A 401 is +// terminal: no replacement. +func TestChunkRound_TokenExpiryAndAuth(t *testing.T) { + b := newRangeFake() + calls := 0 + b.auth = func() string { + calls++ + if calls == 1 { + return jwtWithExp(time.Now().Add(-time.Minute).Unix()) + } + return jwtWithExp(time.Now().Add(time.Hour).Unix()) + } + r := roundRemote(t, b) + if err := putAll(t, r, 3, 1); err != nil { + t.Fatal(err) + } + checkBound(t, r, 3) + b.mu.Lock() + for fid, a := range b.putAuth { + if exp, ok := (blobRange{auth: a}).sendDeadline(); !ok || exp.Before(time.Now()) { + t.Fatalf("upload to %s sent with an expired token", fid) + } + } + b.mu.Unlock() + if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 { + t.Fatalf("assign counts %+v", a) + } + + b2 := newRangeFake() + b2.refuse = func(string) error { return errRangeAuth } + r2 := roundRemote(t, b2) + if err := putAll(t, r2, 2, 1); !errors.Is(err, errRangeAuth) { + t.Fatalf("401: %v", err) + } + if got := b2.reserveCounts(); len(got) != 1 { + t.Fatalf("reservations %v after a 401; want no replacement", got) + } +} + +// A transient failure leaves the slot frozen: the retry sends the same fid. +func TestChunkRound_RetryKeepsTheSlot(t *testing.T) { + b := newRangeFake() + failed := false + b.refuse = func(fid string) error { + if fid == "1,0a0b0c0d0e_1" && !failed { + failed = true + return errors.New("connection reset") + } + return nil + } + r := roundRemote(t, b) + rd := r.BeginPutRound(2, 4096) + ctx := context.Background() + if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { + t.Fatal(err) + } + if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil { + t.Fatal("transient failure reported success") + } + if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil { + t.Fatal(err) + } + b.mu.Lock() + puts := append([]string(nil), b.puts...) + b.mu.Unlock() + if len(puts) != 3 || puts[1] != "1,0a0b0c0d0e_1" || puts[2] != "1,0a0b0c0d0e_1" { + t.Fatalf("uploads %v; want the retry on the same fid", puts) + } + if got := b.reserveCounts(); len(got) != 1 { + t.Fatalf("reservations %v; a transient failure takes no new range", got) + } + // A bound key is never rebound. + if err := rd.Put(ctx, 1, roundKey(1), []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a key: %v", err) + } +} + +// A reservation waiting on the filer ends with the caller's context, and a +// reply that arrives after it never starts an upload. +func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { + b := newRangeFake() + b.hold = make(chan struct{}) + r := roundRemote(t, b) + rd := r.BeginPutRound(1, 4096) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("held reservation: %v", err) + } + close(b.hold) + b.mu.Lock() + n := len(b.puts) + b.mu.Unlock() + if n != 0 { + t.Fatalf("%d uploads after the caller gave up", n) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go new file mode 100644 index 0000000000..aaea826fcc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go @@ -0,0 +1,240 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// batchVolume is a volume server that records every upload by its path (the +// fid as sent), with the Authorization header and query. +type batchVolume struct { + mu sync.Mutex + stored map[string][]byte + auth map[string]string + query map[string]string + refuse func(fid string) (status int, header string) // non-zero status: refuse + srv *httptest.Server + uploads []string +} + +func newBatchVolume(t *testing.T) *batchVolume { + v := &batchVolume{stored: map[string][]byte{}, auth: map[string]string{}, query: map[string]string{}} + v.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fid := strings.TrimPrefix(r.URL.Path, "/") + b, _ := io.ReadAll(r.Body) + v.mu.Lock() + defer v.mu.Unlock() + if r.Method != http.MethodPost { + if d, ok := v.stored[fid]; ok { + _, _ = w.Write(d) + return + } + w.WriteHeader(http.StatusNotFound) + return + } + v.uploads = append(v.uploads, fid) + if v.refuse != nil { + if st, h := v.refuse(fid); st != 0 { + if h != "" { + w.Header().Set("X-Seaweed-Write-Outcome", h) + } + w.WriteHeader(st) + _, _ = w.Write([]byte(`{"error":"refused"}`)) + return + } + } + v.stored[fid] = b + v.auth[fid] = r.Header.Get("Authorization") + v.query[fid] = r.URL.RawQuery + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"size":1}`)) + })) + t.Cleanup(v.srv.Close) + return v +} + +func (v *batchVolume) host() string { return strings.TrimPrefix(v.srv.URL, "http://") } + +func (v *batchVolume) snapshot() (uploads []string, stored map[string][]byte, auth map[string]string) { + v.mu.Lock() + defer v.mu.Unlock() + stored, auth = map[string][]byte{}, map[string]string{} + for k, d := range v.stored { + stored[k] = d + } + for k, a := range v.auth { + auth[k] = a + } + return append([]string(nil), v.uploads...), stored, auth +} + +// One reservation of n ids is addressed in SeaweedFS's native form: offset 0 +// is the base fid, offset i is "_"; every offset carries the base's +// token and the assign's fsync policy. +func TestSWFSRange_NativeOffsetFids(t *testing.T) { + vol := newBatchVolume(t) + f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 3, Auth: "tok", Fsync: true, Location: &filerpb.Location{Url: vol.host()}}} + c := startFakeFiler(t, f) + ctx := context.Background() + r, err := c.reserve(ctx, 3, 4096) + if err != nil { + t.Fatal(err) + } + if f.lastAssign.Count != 3 || f.lastAssign.ExpectedDataSize != 4096 || f.lastAssign.Collection != "swblock" || f.lastAssign.Path != "/swblock/vols/v1" { + t.Fatalf("assign request %+v; want count 3 and the per-object expected size", f.lastAssign) + } + want := []string{"7,01abcdef12", "7,01abcdef12_1", "7,01abcdef12_2"} + for i, w := range want { + fid, err := r.fid(i) + if err != nil || fid != w { + t.Fatalf("offset %d: fid %q %v, want %q", i, fid, err, w) + } + if err := c.putRange(ctx, r, i, []byte(fmt.Sprintf("obj%d", i))); err != nil { + t.Fatalf("offset %d: %v", i, err) + } + } + _, stored, auth := vol.snapshot() + vol.mu.Lock() + query := vol.query + vol.mu.Unlock() + for i, w := range want { + if !bytes.Equal(stored[w], []byte(fmt.Sprintf("obj%d", i))) { + t.Fatalf("offset %d stored %q at %s", i, stored[w], w) + } + if auth[w] != "BEARER tok" { + t.Fatalf("offset %d authorization %q; want the base token", i, auth[w]) + } + if q := query[w]; q != "fsync=true" { + t.Fatalf("offset %d query %q; want the assign's fsync policy", i, q) + } + } + for _, i := range []int{-1, 3, 4} { + if fid, err := r.fid(i); err == nil { + t.Fatalf("offset %d outside a range of 3 gave fid %q", i, fid) + } + } +} + +// A reservation reply is checked before any id in it is used. +func TestSWFSRange_ReserveValidates(t *testing.T) { + loc := &filerpb.Location{Url: "127.0.0.1:1"} + for _, c := range []struct { + name string + n int + resp *filerpb.AssignVolumeResponse + ok bool + want int + }{ + {"full grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: loc}, true, 4}, + {"short grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: loc}, true, 2}, + {"zero count", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 0, Location: loc}, false, 0}, + {"more than asked", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 5, Location: loc}, false, 0}, + {"no location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4}, false, 0}, + {"no fid", 4, &filerpb.AssignVolumeResponse{Count: 4, Location: loc}, false, 0}, + {"fid with a suffix", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e_1", Count: 4, Location: loc}, false, 0}, + {"fid without a comma", 4, &filerpb.AssignVolumeResponse{FileId: "30a0b0c0d0e", Count: 4, Location: loc}, false, 0}, + {"non-numeric volume", 4, &filerpb.AssignVolumeResponse{FileId: "x,0a0b0c0d0e", Count: 4, Location: loc}, false, 0}, + {"non-hex key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0dzz", Count: 4, Location: loc}, false, 0}, + {"key too short for a cookie", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d", Count: 4, Location: loc}, false, 0}, + {"assign error", 4, &filerpb.AssignVolumeResponse{Error: "no free volumes"}, false, 0}, + } { + t.Run(c.name, func(t *testing.T) { + s := startFakeFiler(t, &fakeFilerGRPC{assignResp: c.resp}) + r, err := s.reserve(context.Background(), c.n, 4096) + if c.ok != (err == nil) { + t.Fatalf("reserve: %+v %v; want ok=%v", r, err, c.ok) + } + if c.ok && r.count != c.want { + t.Fatalf("count %d, want %d", r.count, c.want) + } + }) + } + s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}}) + for _, n := range []int{0, -1, maxRangeCount + 1} { + if _, err := s.reserve(context.Background(), n, 4096); err == nil { + t.Fatalf("reserve of %d ids accepted", n) + } + } +} + +// A read-only volume (409, or a write refused before append) is a definite +// refusal: nothing was appended, so a fresh range may take the object. A 401 +// is terminal. Anything else is not classified (the caller retries the same +// slot). +func TestSWFSRange_PutClassifiesRefusals(t *testing.T) { + vol := newBatchVolume(t) + f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 4, Location: &filerpb.Location{Url: vol.host()}}} + c := startFakeFiler(t, f) + ctx := context.Background() + r, err := c.reserve(ctx, 4, 4096) + if err != nil { + t.Fatal(err) + } + vol.mu.Lock() + vol.refuse = func(fid string) (int, string) { + switch fid { + case "7,01abcdef12": + return http.StatusConflict, "" + case "7,01abcdef12_1": + return http.StatusInternalServerError, "refused-before-append" + case "7,01abcdef12_2": + return http.StatusUnauthorized, "" + case "7,01abcdef12_3": + return http.StatusInternalServerError, "" + } + return 0, "" + } + vol.mu.Unlock() + for i, want := range []error{errRangeRefused, errRangeRefused, errRangeAuth, nil} { + err := c.putRange(ctx, r, i, []byte("x")) + if err == nil { + t.Fatalf("offset %d: refused upload reported success", i) + } + for _, e := range []error{errRangeRefused, errRangeAuth} { + if errors.Is(err, e) != (e == want) { + t.Fatalf("offset %d: %v; classified as %v=%v, want %v", i, err, e, errors.Is(err, e), want) + } + } + } +} + +// jwtWithExp returns an unsigned token whose payload names exp (unix seconds). +func jwtWithExp(exp int64) string { + enc := base64.RawURLEncoding + return enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." + + enc.EncodeToString([]byte(fmt.Sprintf(`{"exp":%d,"fid":"7,01abcdef12"}`, exp))) + ".sig" +} + +// The send deadline of a range is its token's stated expiry less a skew; a +// token with no readable expiry gives no deadline. +func TestSWFSRange_TokenSendDeadline(t *testing.T) { + now := time.Unix(1700000000, 0) + for _, c := range []struct { + name string + auth string + ok bool + want time.Time + }{ + {"no token", "", false, time.Time{}}, + {"opaque token", "tok", false, time.Time{}}, + {"no exp claim", base64.RawURLEncoding.EncodeToString([]byte(`{}`)) + "." + base64.RawURLEncoding.EncodeToString([]byte(`{"fid":"x"}`)) + ".s", false, time.Time{}}, + {"exp", jwtWithExp(now.Unix() + 10), true, now.Add(10*time.Second - jwtSendSkew)}, + } { + got, ok := blobRange{auth: c.auth}.sendDeadline() + if ok != c.ok || !got.Equal(c.want) { + t.Errorf("%s: deadline %v %v, want %v %v", c.name, got, ok, c.want, c.ok) + } + } +} From c32467824dfd1dbfc293216734579ec4152e4ac6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:57:01 -0800 Subject: [PATCH 02/15] chunkstore, storage: batch assign for upload rounds Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/chunk_remote.go | 40 ++- .../frontend/chunkstore/chunk_remote_round.go | 260 ++++++++++++++++++ .../core/frontend/chunkstore/swfs.go | 28 +- .../core/frontend/chunkstore/swfs_batch.go | 196 +++++++++++++ .../core/storage/chunk_cut_payload.go | 3 +- seaweed-block/core/storage/chunk_layer.go | 3 +- seaweed-block/core/storage/chunk_put_round.go | 30 ++ seaweed-block/core/storage/chunk_upload.go | 8 +- 8 files changed, 527 insertions(+), 41 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_round.go create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_batch.go create mode 100644 seaweed-block/core/storage/chunk_put_round.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 4c8dcc5da0..a127f5a2d7 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -90,6 +90,8 @@ type ChunkRemote struct { mu sync.Mutex fids map[string]string // key -> fid; key entries are write-once + + assigns assignCounters // reservations made by upload rounds } // NewChunkRemote returns the remote for the volume rooted at root, an @@ -150,26 +152,42 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error { } func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error { - if err := storage.ValidChunkKey(key); err != nil { - return fmt.Errorf("%w: %v", ErrInvalidKey, err) - } - if strings.HasPrefix(key, "@") { - return fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key) - } - name, err := keyName(key) + name, err := r.ownKeyName(key) if err != nil { return err } - r.mu.Lock() - _, known := r.fids[key] - r.mu.Unlock() - if known { + if r.knownKey(key) { return storage.ErrChunkKeyExists } fid, err := r.b.Put(ctx, data) if err != nil { return err } + return r.bindKey(ctx, key, name, fid, data, object) +} + +// ownKeyName checks that key is one of this volume's own keys and returns +// its binding's entry name. +func (r *ChunkRemote) ownKeyName(key string) (string, error) { + if err := storage.ValidChunkKey(key); err != nil { + return "", fmt.Errorf("%w: %v", ErrInvalidKey, err) + } + if strings.HasPrefix(key, "@") { + return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key) + } + return keyName(key) +} + +// knownKey reports whether key is already bound (as far as this remote saw). +func (r *ChunkRemote) knownKey(key string) bool { + r.mu.Lock() + defer r.mu.Unlock() + _, known := r.fids[key] + return known +} + +// bindKey binds key to the stored needle fid with an exclusive create. +func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error { now := time.Now().Unix() e := &filerpb.Entry{ Name: name, diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go new file mode 100644 index 0000000000..eaf2763e7a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go @@ -0,0 +1,260 @@ +package chunkstore + +// Upload rounds over batch assign. The n objects of one round are split into +// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G), +// and each group takes one reservation for all its slots, made when its +// first object is uploaded. So a round costs G assigns instead of n, its +// objects still spread over up to G volumes, and a round with no upload +// makes none. +// +// A slot is frozen once reserved: retrying object i sends the same fid. A +// group's ranges change only for slots no upload has stored yet: +// - a short grant is topped up by a reservation for the remaining slots; +// - a refusal before append (read-only or full volume) moves this and the +// later slots of the group to a fresh range, at most roundMaxReplacements +// times per group; +// - a range whose token is past its stated expiry is never sent to; its +// unsent slots get a fresh range under the same bound. +// A rejected token (401) is terminal. Extra reservations are counted apart +// from the initial ones (AssignCounts). + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + roundGroupSize = 64 + roundMaxGroups = 8 + roundMaxReplacements = 3 +) + +// AssignCounts counts the reservations this remote's upload rounds made. +type AssignCounts struct { + Initial int64 // the first reservation of each group + Short int64 // top-ups after a short grant + Capacity int64 // replacements after a refusal before append + Expired int64 // replacements of ranges whose token expired before use +} + +// Extra is every reservation beyond the initial ones. +func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired } + +type assignCounters struct{ initial, short, capacity, expired atomic.Int64 } + +// AssignCounts reports the reservations made so far. +func (r *ChunkRemote) AssignCounts() AssignCounts { + return AssignCounts{ + Initial: r.assigns.initial.Load(), + Short: r.assigns.short.Load(), + Capacity: r.assigns.capacity.Load(), + Expired: r.assigns.expired.Load(), + } +} + +var _ storage.ChunkPutRounds = (*ChunkRemote)(nil) + +// BeginPutRound starts a round of n objects of objSize bytes. Without batch +// support in the blob store, the round is one Put per object. +func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound { + rb, ok := r.b.(rangeBlobs) + if !ok || n <= 0 { + return plainRound{r} + } + g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize) + rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)} + for j := range rd.groups { + // Group j holds objects j, j+g, j+2g, ... + rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g} + } + return rd +} + +type plainRound struct{ r *ChunkRemote } + +func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error { + return p.r.Put(ctx, key, data) +} + +type putRound struct { + r *ChunkRemote + rb rangeBlobs + n int + size uint64 + groups []*roundGroup +} + +// roundGroup's ranges cover its slots [0, end) as consecutive spans. +type roundGroup struct { + slots int + + mu sync.Mutex + spans []roundSpan + reserving chan struct{} // non-nil while a reservation is in flight + replacements int + next reserveReason // what the next reservation is for +} + +type reserveReason int + +const ( + reserveInitial reserveReason = iota + reserveShort + reserveCapacity + reserveExpired +) + +type roundSpan struct { + from int + rng blobRange +} + +func (g *roundGroup) end() int { + if len(g.spans) == 0 { + return 0 + } + last := g.spans[len(g.spans)-1] + return last.from + last.rng.count +} + +// lookup returns the range and offset of slot s, if reserved. g.mu held. +func (g *roundGroup) lookup(s int) (blobRange, int, bool) { + for _, sp := range g.spans { + if s >= sp.from && s < sp.from+sp.rng.count { + return sp.rng, s - sp.from, true + } + } + return blobRange{}, 0, false +} + +// retire drops slots s and later of the span using rng, so they take a fresh +// range; it reports false once the group's replacements are used up. A span +// already replaced (by a concurrent upload) is left as is. +func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool { + g.mu.Lock() + defer g.mu.Unlock() + for k, sp := range g.spans { + if sp.rng.base != rng.base { + continue + } + if g.replacements >= roundMaxReplacements { + return false + } + g.replacements++ + g.next = why + if s <= sp.from { + g.spans = g.spans[:k] + } else { + g.spans[k].rng.count = s - sp.from + g.spans = g.spans[:k+1] + } + return true + } + return true +} + +// slot returns slot s's range and offset, reserving the group's remaining +// slots when s is not covered yet. Concurrent callers share one reservation; +// waiting follows ctx, and a reply after ctx ends is not used. +func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) { + for { + g.mu.Lock() + if rng, off, ok := g.lookup(s); ok { + g.mu.Unlock() + return rng, off, nil + } + if wait := g.reserving; wait != nil { + g.mu.Unlock() + select { + case <-wait: + continue + case <-ctx.Done(): + return blobRange{}, 0, ctx.Err() + } + } + from := g.end() + why := g.next + done := make(chan struct{}) + g.reserving = done + g.mu.Unlock() + + rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size) + if err == nil { + err = ctx.Err() + } + g.mu.Lock() + g.reserving = nil + close(done) + if err == nil { + g.spans = append(g.spans, roundSpan{from: from, rng: rng}) + g.next = reserveShort // only a short grant leaves slots uncovered now + switch why { + case reserveInitial: + rd.r.assigns.initial.Add(1) + case reserveShort: + rd.r.assigns.short.Add(1) + case reserveCapacity: + rd.r.assigns.capacity.Add(1) + case reserveExpired: + rd.r.assigns.expired.Add(1) + } + } + g.mu.Unlock() + if err != nil { + return blobRange{}, 0, err + } + } +} + +// Put stores object i under key in its group's range and binds key to it. +func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error { + if i < 0 || i >= rd.n { + return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n) + } + name, err := rd.r.ownKeyName(key) + if err != nil { + return err + } + if rd.r.knownKey(key) { + return storage.ErrChunkKeyExists + } + g := rd.groups[i%len(rd.groups)] + s := i / len(rd.groups) + for { + if err := ctx.Err(); err != nil { + return err + } + rng, off, err := rd.slot(ctx, g, s) + if err != nil { + return err + } + if dl, ok := rng.sendDeadline(); ok && !time.Now().Before(dl) { + // Never sent: the unsent slots take a fresh range. + if !g.retire(rng, s, reserveExpired) { + return fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i) + } + continue + } + fid, err := rng.fid(off) + if err != nil { + return err + } + err = rd.rb.putRange(ctx, rng, off, data) + if errors.Is(err, errRangeRefused) { + if !g.retire(rng, s, reserveCapacity) { + return fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err) + } + continue + } + if err != nil { + return err + } + return rd.r.bindKey(ctx, key, name, fid, data, "") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index 1180b84e87..3c2102b004 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -1,9 +1,7 @@ package chunkstore import ( - "bytes" "context" - "encoding/json" "errors" "fmt" "io" @@ -219,33 +217,9 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) { if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" { return "", fmt.Errorf("chunkstore: assign returned no fid/location") } - u := "http://" + ar.Location.Url + "/" + ar.FileId - if ar.GetFsync() { - u += "?fsync=true" - } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data)) - if err != nil { + if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil { return "", err } - req.Header.Set("Content-Type", "application/octet-stream") - if ar.GetAuth() != "" { - req.Header.Set("Authorization", "BEARER "+ar.Auth) - } - resp, err := c.http.Do(req) - if err != nil { - return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err) - } - defer resp.Body.Close() - body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) - if resp.StatusCode/100 != 2 { - return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body))) - } - var ur struct { - Error string `json:"error"` - } - if json.Unmarshal(body, &ur) == nil && ur.Error != "" { - return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error) - } return ar.FileId, nil } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch.go b/seaweed-block/core/frontend/chunkstore/swfs_batch.go new file mode 100644 index 0000000000..f50713697d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch.go @@ -0,0 +1,196 @@ +package chunkstore + +// Batch assign: one AssignVolume(Count = n) reserves n consecutive needle ids +// on one volume. They are addressed in SeaweedFS's native form: offset 0 is +// the base fid, offset i is "_". The volume server adds i to the +// needle key and checks the assign's token against the base fid, so every +// offset carries the base's token and shares its cookie. Never write such an +// id as a different fid (key+i): that one has no token. + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +const ( + // maxRangeCount bounds one reservation. + maxRangeCount = 1 << 16 + // jwtSendSkew: an upload is not sent within this much of its token's + // stated expiry. + jwtSendSkew = 2 * time.Second +) + +var ( + // errRangeRefused: the volume refused the write before appending it + // (read-only or full). Nothing was stored; a fresh range may take it. + errRangeRefused = errors.New("chunkstore: volume refused the write before append") + // errRangeAuth: the volume rejected the upload's token. Terminal. + errRangeAuth = errors.New("chunkstore: volume rejected the upload token") +) + +// blobRange is one batch reservation: count ids starting at base, on the +// volume server at url, with the assign's token and fsync policy. +type blobRange struct { + base string + count int + url string + auth string + fsync bool +} + +// fid returns the native id of offset i. +func (r blobRange) fid(i int) (string, error) { + if i < 0 || i >= r.count { + return "", fmt.Errorf("chunkstore: offset %d outside a range of %d ids", i, r.count) + } + if i == 0 { + return r.base, nil + } + return r.base + "_" + strconv.Itoa(i), nil +} + +// sendDeadline is the last time an upload with this range's token may be +// sent: the token's stated expiry less jwtSendSkew. The claim is read, not +// verified: it only ever stops an upload, it never authorizes one. A token +// without a readable expiry gives no deadline. +func (r blobRange) sendDeadline() (time.Time, bool) { + parts := strings.Split(r.auth, ".") + if len(parts) != 3 { + return time.Time{}, false + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return time.Time{}, false + } + var claims struct { + Exp *int64 `json:"exp"` + } + if json.Unmarshal(payload, &claims) != nil || claims.Exp == nil { + return time.Time{}, false + } + return time.Unix(*claims.Exp, 0).Add(-jwtSendSkew), true +} + +// rangeBlobs is the optional batch capability of a blob store. +type rangeBlobs interface { + reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) + putRange(ctx context.Context, r blobRange, i int, data []byte) error +} + +var _ rangeBlobs = (*SWFS)(nil) + +// validBaseFid checks ",": a decimal volume id, then hex +// with at least a cookie's 8 digits after a key, and no offset suffix. +func validBaseFid(fid string) error { + vid, kc, ok := strings.Cut(fid, ",") + if !ok || vid == "" { + return fmt.Errorf("chunkstore: assign fid %q has no volume id", fid) + } + if _, err := strconv.ParseUint(vid, 10, 32); err != nil { + return fmt.Errorf("chunkstore: assign fid %q: volume id: %v", fid, err) + } + if len(kc) <= 8 { + return fmt.Errorf("chunkstore: assign fid %q: no key before the cookie", fid) + } + for _, c := range kc { + if !strings.ContainsRune("0123456789abcdefABCDEF", c) { + return fmt.Errorf("chunkstore: assign fid %q: not a plain hex key and cookie", fid) + } + } + return nil +} + +// reserve asks for n ids of objSize bytes each (the master counts +// ExpectedDataSize per id). A shorter valid grant is returned as is; the +// caller reserves the rest. +func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) { + if n <= 0 || n > maxRangeCount { + return blobRange{}, fmt.Errorf("chunkstore: reserve %d ids: want 1..%d", n, maxRangeCount) + } + ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{ + Count: int32(n), + Collection: c.cfg.Collection, + Replication: c.cfg.Replication, + Path: c.cfg.AssignPath, + ExpectedDataSize: objSize, + }) + if err != nil { + return blobRange{}, fmt.Errorf("chunkstore: assign %d: %w", n, err) + } + if ar.GetError() != "" { + return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError()) + } + if ar.GetLocation().GetUrl() == "" { + return blobRange{}, fmt.Errorf("chunkstore: assign %d returned no location", n) + } + if err := validBaseFid(ar.GetFileId()); err != nil { + return blobRange{}, err + } + count := int(ar.GetCount()) + if count <= 0 || count > n { + return blobRange{}, fmt.Errorf("chunkstore: assign %d returned %d ids", n, count) + } + return blobRange{base: ar.FileId, count: count, url: ar.Location.Url, auth: ar.GetAuth(), fsync: ar.GetFsync()}, nil +} + +// putRange uploads data as offset i of r. A refusal before append is +// errRangeRefused, a rejected token errRangeAuth; any other failure is +// returned as is (the caller retries the same offset). +func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) error { + fid, err := r.fid(i) + if err != nil { + return err + } + return c.upload(ctx, r.url, fid, r.auth, r.fsync, data) +} + +// upload POSTs data raw to fid on the volume server at host. +func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, data []byte) error { + u := "http://" + host + "/" + fid + if fsync { + u += "?fsync=true" + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/octet-stream") + if auth != "" { + req.Header.Set("Authorization", "BEARER "+auth) + } + resp, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("chunkstore: upload %s: %w", fid, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if resp.StatusCode/100 != 2 { + err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body))) + switch { + case resp.StatusCode == http.StatusUnauthorized: + return errors.Join(errRangeAuth, err) + case resp.StatusCode == http.StatusConflict, + resp.Header.Get("X-Seaweed-Write-Outcome") == "refused-before-append": + return errors.Join(errRangeRefused, err) + } + return err + } + var ur struct { + Error string `json:"error"` + } + if json.Unmarshal(body, &ur) == nil && ur.Error != "" { + return fmt.Errorf("chunkstore: upload %s: %s", fid, ur.Error) + } + return nil +} diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 2a3e226c8f..3cac8535be 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -51,6 +51,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, var once sync.Once var intent string var intentErr error + put := l.beginPutRound(len(batch)) err := l.uploadBatch(ctx, len(batch), func(ctx context.Context, i int) error { c, err := read(ctx, batch[i]) if err != nil { @@ -69,7 +70,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, intentErr) } c.intent = intent - if err := l.putCaptured(ctx, c.key, c.data); err != nil { + if err := l.putCapturedWith(ctx, c.key, c.data, func(ctx context.Context) error { return put(ctx, i, c.key, c.data) }); err != nil { return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 7ed3c1631c..a0492820d4 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -959,9 +959,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch intents = append(intents, id) } payloadStart := time.Now() + put := l.beginPutRound(len(uploads)) if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] - return l.putCaptured(ctx, u.key, u.c.data) + return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) }) }); err != nil { l.abortCut(all) l.dropIntents(ctx, intents) diff --git a/seaweed-block/core/storage/chunk_put_round.go b/seaweed-block/core/storage/chunk_put_round.go new file mode 100644 index 0000000000..e9c661d9d3 --- /dev/null +++ b/seaweed-block/core/storage/chunk_put_round.go @@ -0,0 +1,30 @@ +package storage + +import "context" + +// ChunkPutRounds is an optional ChunkRemote capability: the objects of one +// upload round share remote reservations (batch assign) instead of taking +// one each. The round belongs to the cut or staging round that begins it and +// ends with it; it starts no goroutine of its own, so joining the round's +// workers joins every call it made. +type ChunkPutRounds interface { + BeginPutRound(n, objSize int) ChunkPutRound +} + +// ChunkPutRound stores object i (0 <= i < n) of its round under key, with +// Put's rules: a bound key is never rebound (ErrChunkKeyExists). A failed Put +// may be retried with the same i and bytes. +type ChunkPutRound interface { + Put(ctx context.Context, i int, key string, data []byte) error +} + +// beginPutRound returns the put for a round of n objects: the remote's +// round when it has one, otherwise one Put per object. +func (l *chunkLayerImpl) beginPutRound(n int) func(ctx context.Context, i int, key string, data []byte) error { + if rounds, ok := l.remote.(ChunkPutRounds); ok && n > 0 { + return rounds.BeginPutRound(n, int(uint64(l.blockSize)*l.chunkBlocks)).Put + } + return func(ctx context.Context, _ int, key string, data []byte) error { + return l.remote.Put(ctx, key, data) + } +} diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index 8f9fdf658b..a0a2239e0e 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -14,6 +14,12 @@ import ( // Keep the point and frozen buffer through transient failures until the cut // context ends (deadline, Close or window abort), never a fresh point. func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { + return l.putCapturedWith(ctx, key, data, func(ctx context.Context) error { return l.remote.Put(ctx, key, data) }) +} + +// putCapturedWith is putCaptured over put, one object's slot in an upload +// round: every retry sends through the same put. +func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data []byte, put func(context.Context) error) error { // The per-object retry deadline also bounds a contextless cut. It retains // the same point and buffer through a remote outage, never re-reads live data. ctx, cancel := context.WithTimeout(ctx, 30*time.Second) @@ -24,7 +30,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt if err := ctx.Err(); err != nil { return errors.Join(lastErr, err) } - err := l.remote.Put(ctx, key, data) + err := put(ctx) if err == nil { return nil } From 7c4d08199f49bbfccb029558c143305048661149 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:04:27 -0800 Subject: [PATCH 03/15] test: cuts upload through rounds; JWT integration for native offset fids Co-Authored-By: Claude Opus 5.5 --- .../chunk_remote_integration_test.go | 12 ++ .../chunkstore/swfs_batch_integration_test.go | 108 ++++++++++++++++ .../core/storage/chunk_put_round_test.go | 121 ++++++++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go create mode 100644 seaweed-block/core/storage/chunk_put_round_test.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go index 5250c781b3..66bbebd860 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go @@ -68,6 +68,13 @@ func waitTCP(t *testing.T, addr string, d time.Duration) { } func startWeed(t *testing.T) *weedCluster { + t.Helper() + return startWeedWith(t, "") +} + +// startWeedWith starts the cluster with security (the contents of a +// security.toml in its working directory; "" for none). +func startWeedWith(t *testing.T, security string) *weedCluster { t.Helper() weed := os.Getenv("CHUNKSTORE_WEED") if weed == "" { @@ -112,6 +119,11 @@ func startWeed(t *testing.T) *weedCluster { t.Fatal(err) } } + if security != "" { + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil { + t.Fatal(err) + } + } run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") waitTCP(t, c.master, 20*time.Second) run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32") diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go new file mode 100644 index 0000000000..744fcf5551 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go @@ -0,0 +1,108 @@ +//go:build chunkstore_integration + +package chunkstore + +import ( + "bytes" + "context" + "errors" + "fmt" + "strconv" + "strings" + "testing" + "time" +) + +const jwtSecurity = `[jwt.signing] +key = "batch-assign-integration" +expires_after_seconds = 60 +` + +// arithmeticFid is the fid key+i with the base's cookie: a different needle +// id, which the base's token does not cover. +func arithmeticFid(t *testing.T, base string, i int) string { + t.Helper() + vid, kc, _ := strings.Cut(base, ",") + key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64) + if err != nil { + t.Fatal(err) + } + return fmt.Sprintf("%s,%x%s", vid, key+uint64(i), kc[len(kc)-8:]) +} + +// With JWT on, every offset of a reservation is written with the base's +// token in the native "_" form and reads back as itself; the same +// token on the arithmetic fid key+i is refused. +func TestIntegrationBatch_JWTNativeOffsets(t *testing.T) { + c := startWeedWith(t, jwtSecurity) + cl := c.client(t, "/swblock/vols/v1") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + const n = 5 + r, err := cl.reserve(ctx, n, 4096) + if err != nil { + t.Fatal(err) + } + if r.auth == "" { + t.Fatal("assign with JWT on returned no token") + } + if r.count != n { + t.Fatalf("reserved %d of %d", r.count, n) + } + data := func(i int) []byte { return bytes.Repeat([]byte(fmt.Sprintf("offset-%d|", i)), 400) } + for _, i := range []int{0, 2, n - 1} { // first, middle, last + if err := cl.putRange(ctx, r, i, data(i)); err != nil { + t.Fatalf("offset %d: %v", i, err) + } + } + for _, i := range []int{0, 2, n - 1} { + fid, _ := r.fid(i) + got, err := cl.Get(ctx, fid) + if err != nil || !bytes.Equal(got, data(i)) { + t.Fatalf("offset %d (%s) read back %d bytes, %v", i, fid, len(got), err) + } + } + arith := arithmeticFid(t, r.base, 1) + err = cl.upload(ctx, r.url, arith, r.auth, r.fsync, data(1)) + if !errors.Is(err, errRangeAuth) { + t.Fatalf("upload to the arithmetic fid %s with the base token: %v; want a rejected token", arith, err) + } +} + +// A round of more than one group writes through real assigns, binds every +// key, and reads every key back; it takes one assign per group. +func TestIntegrationBatch_RoundBindsAndReadsBack(t *testing.T) { + c := startWeedWith(t, jwtSecurity) + cl := c.client(t, "/swblock/vols/v1") + r, err := NewChunkRemote(cl, cl, "/swblock/vols/v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + const n = 130 // three groups + rd := r.BeginPutRound(n, 4096) + for i := 0; i < n; i++ { + if err := rd.Put(ctx, i, roundKey(i), []byte(roundKey(i))); err != nil { + t.Fatalf("object %d: %v", i, err) + } + } + for i := 0; i < n; i++ { + got, err := r.Get(ctx, roundKey(i)) + if err != nil || !bytes.Equal(got, []byte(roundKey(i))) { + t.Fatalf("key %d read back %q, %v", i, got, err) + } + } + if a := r.AssignCounts(); a.Initial != 3 || a.Extra() != 0 { + t.Fatalf("assign counts %+v; want 3 initial", a) + } + suffixed := 0 + for i := 0; i < n; i++ { + if strings.Contains(r.fids[roundKey(i)], "_") { + suffixed++ + } + } + if suffixed != n-3 { + t.Fatalf("%d of %d bindings use an offset fid; want all but the 3 bases", suffixed, n) + } +} diff --git a/seaweed-block/core/storage/chunk_put_round_test.go b/seaweed-block/core/storage/chunk_put_round_test.go new file mode 100644 index 0000000000..ea06562386 --- /dev/null +++ b/seaweed-block/core/storage/chunk_put_round_test.go @@ -0,0 +1,121 @@ +package storage + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +// roundChunkRemote adds upload rounds to the fake remote and records them. +type roundChunkRemote struct { + *fakeChunkRemote + mu sync.Mutex + rounds []int // n of each round begun + puts [][2]int // {round, i} of each round Put + keys []string // key of each round Put + fail func(round, i int, attempt int) error + tries map[[2]int]int +} + +type recordedRound struct { + r *roundChunkRemote + id int +} + +func (r *roundChunkRemote) BeginPutRound(n, objSize int) ChunkPutRound { + r.mu.Lock() + defer r.mu.Unlock() + r.rounds = append(r.rounds, n) + return recordedRound{r: r, id: len(r.rounds) - 1} +} + +func (rr recordedRound) Put(ctx context.Context, i int, key string, data []byte) error { + r := rr.r + r.mu.Lock() + r.puts = append(r.puts, [2]int{rr.id, i}) + r.keys = append(r.keys, key) + if r.tries == nil { + r.tries = map[[2]int]int{} + } + r.tries[[2]int{rr.id, i}]++ + attempt := r.tries[[2]int{rr.id, i}] + fail := r.fail + r.mu.Unlock() + if fail != nil { + if err := fail(rr.id, i, attempt); err != nil { + return err + } + } + return r.fakeChunkRemote.Put(ctx, key, data) +} + +// A cut uploads its changed chunks through one round of the remote, one +// object index per chunk (the round may be sized for more candidates than +// end up changed); a cut with nothing to upload begins none. A retried +// upload keeps its index. +func TestChunkCut_UploadsThroughOneRound(t *testing.T) { + s, _ := newChunkTestStore(t) + f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()} + f.fail = func(round, i, attempt int) error { + if i == 0 && attempt == 1 { + return errors.New("transient upload failure") + } + return nil + } + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + f.mu.Lock() + rounds, puts := append([]int(nil), f.rounds...), append([][2]int(nil), f.puts...) + f.mu.Unlock() + if len(rounds) != 1 || rounds[0] < 1 { + t.Fatalf("rounds %v; want one round for the cut", rounds) + } + seen := map[int]int{} + for _, p := range puts { + if p[0] != 0 || p[1] < 0 || p[1] >= rounds[0] { + t.Fatalf("round put %v outside round 0 of %d", p, rounds[0]) + } + seen[p[1]]++ + } + if seen[0] != 2 { + t.Fatalf("object 0 sent %d times; want the failed attempt and its retry on the same index", seen[0]) + } + if len(seen) != 2 { + t.Fatalf("round of %d used indexes %v; want one per changed chunk (2)", rounds[0], seen) + } + + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + f.mu.Lock() + n := len(f.rounds) + f.mu.Unlock() + if n != 1 { + t.Fatalf("a cut with nothing to upload began a round (%d rounds)", n) + } +} + +// A round that cannot store an object fails the cut: no HEAD names it. +func TestChunkCut_FailedRoundPublishesNothing(t *testing.T) { + s, _ := newChunkTestStore(t) + f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()} + f.fail = func(int, int, int) error { return ErrChunkKeyExists } + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if _, err := layer.Cut(ctx); err == nil { + t.Fatal("cut with a refused upload succeeded") + } + if heads := f.installedHeads(); len(heads) != 0 { + t.Fatalf("installed %d HEADs after a failed upload", len(heads)) + } +} From d0fc061a77f09cb132b10dfec2c4d04ef9f7b2e0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:58:35 -0800 Subject: [PATCH 04/15] chunkstore, storage: batch-assign review fold Discard a reservation reply that lost a race with a retirement; keep a slot's fid while an upload to it is unresolved and read it back before giving it up; send under the token's deadline; make a rejected token and used-up replacements final through storage; count every reservation attempt; validate key width, offset overflow and location. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/chunk_remote_round.go | 243 ++++++++++--- .../chunkstore/chunk_remote_round_test.go | 343 ++++++++++++++++-- .../core/frontend/chunkstore/swfs_batch.go | 73 +++- .../frontend/chunkstore/swfs_batch_test.go | 24 ++ seaweed-block/core/storage/chunk_put_round.go | 9 +- .../core/storage/chunk_put_round_test.go | 149 ++++++++ seaweed-block/core/storage/chunk_upload.go | 3 + 7 files changed, 749 insertions(+), 95 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go index eaf2763e7a..26c22fffaf 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go @@ -7,18 +7,25 @@ package chunkstore // objects still spread over up to G volumes, and a round with no upload // makes none. // -// A slot is frozen once reserved: retrying object i sends the same fid. A -// group's ranges change only for slots no upload has stored yet: +// A slot is frozen once an upload was sent for it: until that upload is +// resolved (stored and bound, or definitely not stored), every retry uses +// the same fid, whatever happens to the group's ranges. Ranges change only +// for slots with no upload outstanding: // - a short grant is topped up by a reservation for the remaining slots; // - a refusal before append (read-only or full volume) moves this and the // later slots of the group to a fresh range, at most roundMaxReplacements // times per group; -// - a range whose token is past its stated expiry is never sent to; its -// unsent slots get a fresh range under the same bound. -// A rejected token (401) is terminal. Extra reservations are counted apart -// from the initial ones (AssignCounts). +// - a range whose token is past its stated expiry (less a skew) is never +// sent to: an upload is sent under that deadline, and a slot frozen on +// an expired range is resolved by reading its fid back first (the exact +// bytes: bind it; definitely absent: a fresh range takes it). +// A rejected token (401) and used-up replacements end the object for good +// (storage.ErrChunkPutFinal). A reservation reply that arrives after the +// group's ranges changed is discarded (its ids stay unused). AssignCounts +// counts every reservation attempt, by reason, failed ones included. import ( + "bytes" "context" "errors" "fmt" @@ -35,26 +42,32 @@ const ( roundMaxReplacements = 3 ) -// AssignCounts counts the reservations this remote's upload rounds made. +// AssignCounts counts the reservation attempts this remote's upload rounds +// made. Each attempt is counted once, by why it was made, whether or not it +// succeeded; Failed counts the ones that returned no usable range. type AssignCounts struct { - Initial int64 // the first reservation of each group + Initial int64 // the first attempt of each group Short int64 // top-ups after a short grant Capacity int64 // replacements after a refusal before append Expired int64 // replacements of ranges whose token expired before use + Retry int64 // attempts after a failed, lost or discarded reply + Failed int64 // attempts that returned an error or were discarded } -// Extra is every reservation beyond the initial ones. -func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired } +// Extra is every attempt beyond the initial ones. +func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired + a.Retry } -type assignCounters struct{ initial, short, capacity, expired atomic.Int64 } +type assignCounters struct{ initial, short, capacity, expired, retry, failed atomic.Int64 } -// AssignCounts reports the reservations made so far. +// AssignCounts reports the reservation attempts made so far. func (r *ChunkRemote) AssignCounts() AssignCounts { return AssignCounts{ Initial: r.assigns.initial.Load(), Short: r.assigns.short.Load(), Capacity: r.assigns.capacity.Load(), Expired: r.assigns.expired.Load(), + Retry: r.assigns.retry.Load(), + Failed: r.assigns.failed.Load(), } } @@ -71,7 +84,7 @@ func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound { rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)} for j := range rd.groups { // Group j holds objects j, j+g, j+2g, ... - rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g} + rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}} } return rd } @@ -90,17 +103,6 @@ type putRound struct { groups []*roundGroup } -// roundGroup's ranges cover its slots [0, end) as consecutive spans. -type roundGroup struct { - slots int - - mu sync.Mutex - spans []roundSpan - reserving chan struct{} // non-nil while a reservation is in flight - replacements int - next reserveReason // what the next reservation is for -} - type reserveReason int const ( @@ -108,13 +110,36 @@ const ( reserveShort reserveCapacity reserveExpired + reserveRetry ) +// roundGroup's ranges cover its slots [0, end) as consecutive spans. +type roundGroup struct { + slots int + + mu sync.Mutex + spans []roundSpan + ver int // bumped by every change to spans other than an append + reserving chan struct{} // non-nil while a reservation is in flight + replacements int + next reserveReason // why the next reservation is made + pins map[int]slotPin + owners map[int]chan struct{} // slot -> held by one Put at a time +} + type roundSpan struct { from int rng blobRange } +// slotPin freezes a slot on the fid an upload was sent to; stored records +// that the upload succeeded (only its binding is outstanding). +type slotPin struct { + rng blobRange + off int + stored bool +} + func (g *roundGroup) end() int { if len(g.spans) == 0 { return 0 @@ -133,9 +158,54 @@ func (g *roundGroup) lookup(s int) (blobRange, int, bool) { return blobRange{}, 0, false } +// own makes the caller the only Put working on slot s until release. +func (g *roundGroup) own(ctx context.Context, s int) (release func(), err error) { + for { + g.mu.Lock() + held, busy := g.owners[s] + if !busy { + done := make(chan struct{}) + g.owners[s] = done + g.mu.Unlock() + return func() { + g.mu.Lock() + delete(g.owners, s) + g.mu.Unlock() + close(done) + }, nil + } + g.mu.Unlock() + select { + case <-held: + case <-ctx.Done(): + return nil, ctx.Err() + } + } +} + +func (g *roundGroup) pin(s int, p slotPin) { + g.mu.Lock() + g.pins[s] = p + g.mu.Unlock() +} + +func (g *roundGroup) unpin(s int) { + g.mu.Lock() + delete(g.pins, s) + g.mu.Unlock() +} + +func (g *roundGroup) pinned(s int) (slotPin, bool) { + g.mu.Lock() + defer g.mu.Unlock() + p, ok := g.pins[s] + return p, ok +} + // retire drops slots s and later of the span using rng, so they take a fresh -// range; it reports false once the group's replacements are used up. A span -// already replaced (by a concurrent upload) is left as is. +// range (slots with an upload outstanding keep their pinned fid); it reports +// false once the group's replacements are used up. A span already replaced +// (by a concurrent upload) is left as is. func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool { g.mu.Lock() defer g.mu.Unlock() @@ -148,6 +218,7 @@ func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool { } g.replacements++ g.next = why + g.ver++ if s <= sp.from { g.spans = g.spans[:k] } else { @@ -159,9 +230,25 @@ func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool { return true } +func (rd *putRound) count(why reserveReason) { + switch why { + case reserveInitial: + rd.r.assigns.initial.Add(1) + case reserveShort: + rd.r.assigns.short.Add(1) + case reserveCapacity: + rd.r.assigns.capacity.Add(1) + case reserveExpired: + rd.r.assigns.expired.Add(1) + case reserveRetry: + rd.r.assigns.retry.Add(1) + } +} + // slot returns slot s's range and offset, reserving the group's remaining // slots when s is not covered yet. Concurrent callers share one reservation; -// waiting follows ctx, and a reply after ctx ends is not used. +// waiting follows ctx. A reply after ctx ends, or after the group's ranges +// changed while it was in flight, is not used. func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) { for { g.mu.Lock() @@ -178,12 +265,12 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, return blobRange{}, 0, ctx.Err() } } - from := g.end() - why := g.next + from, ver, why := g.end(), g.ver, g.next done := make(chan struct{}) g.reserving = done g.mu.Unlock() + rd.count(why) rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size) if err == nil { err = ctx.Err() @@ -191,19 +278,18 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, g.mu.Lock() g.reserving = nil close(done) - if err == nil { + switch { + case err != nil: + rd.r.assigns.failed.Add(1) + g.next = reserveRetry + case g.ver != ver || g.end() != from: + // The ranges changed while this reply was in flight: its ids + // stay unused, and the uncovered slots are reserved again. + rd.r.assigns.failed.Add(1) + g.next = reserveRetry + default: g.spans = append(g.spans, roundSpan{from: from, rng: rng}) g.next = reserveShort // only a short grant leaves slots uncovered now - switch why { - case reserveInitial: - rd.r.assigns.initial.Add(1) - case reserveShort: - rd.r.assigns.short.Add(1) - case reserveCapacity: - rd.r.assigns.capacity.Add(1) - case reserveExpired: - rd.r.assigns.expired.Add(1) - } } g.mu.Unlock() if err != nil { @@ -212,6 +298,9 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, } } +// final marks an outcome no retry can change. +func final(err error) error { return errors.Join(storage.ErrChunkPutFinal, err) } + // Put stores object i under key in its group's range and binds key to it. func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error { if i < 0 || i >= rd.n { @@ -226,35 +315,77 @@ func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) err } g := rd.groups[i%len(rd.groups)] s := i / len(rd.groups) + release, err := g.own(ctx, s) + if err != nil { + return err + } + defer release() for { if err := ctx.Err(); err != nil { return err } - rng, off, err := rd.slot(ctx, g, s) + p, frozen := g.pinned(s) + if !frozen { + rng, off, err := rd.slot(ctx, g, s) + if err != nil { + return err + } + p = slotPin{rng: rng, off: off} + } + fid, err := p.rng.fid(p.off) if err != nil { return err } - if dl, ok := rng.sendDeadline(); ok && !time.Now().Before(dl) { - // Never sent: the unsent slots take a fresh range. - if !g.retire(rng, s, reserveExpired) { - return fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i) + if p.stored { + if err := rd.r.bindKey(ctx, key, name, fid, data, ""); err != nil { + return err + } + g.unpin(s) + return nil + } + dl, hasDL := p.rng.sendDeadline() + if hasDL && !time.Now().Before(dl) { + if frozen { + // An earlier upload to fid is unresolved: read it back + // before giving the fid up. + got, perr := rd.rb.probe(ctx, p.rng, p.off) + switch { + case perr == nil && bytes.Equal(got, data): + g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true}) + continue + case perr == nil: + return final(fmt.Errorf("chunkstore: round object %d: %s holds other bytes", i, fid)) + case !errors.Is(perr, errBlobAbsent): + return fmt.Errorf("chunkstore: round object %d: earlier upload to %s unresolved: %w", i, fid, perr) + } + g.unpin(s) + } + if !g.retire(p.rng, s, reserveExpired) { + return final(fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i)) } continue } - fid, err := rng.fid(off) - if err != nil { - return err + pctx, cancel := ctx, context.CancelFunc(func() {}) + if hasDL { + pctx, cancel = context.WithDeadline(ctx, dl) } - err = rd.rb.putRange(ctx, rng, off, data) - if errors.Is(err, errRangeRefused) { - if !g.retire(rng, s, reserveCapacity) { - return fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err) + g.pin(s, p) // sent: frozen until resolved + err = rd.rb.putRange(pctx, p.rng, p.off, data) + cancel() + switch { + case err == nil: + g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true}) + continue + case errors.Is(err, errRangeRefused): + g.unpin(s) // definitely not stored + if !g.retire(p.rng, s, reserveCapacity) { + return final(fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err)) } continue + case errors.Is(err, errRangeAuth): + g.unpin(s) // definitely not stored + return final(err) } - if err != nil { - return err - } - return rd.r.bindKey(ctx, key, name, fid, data, "") + return err // outcome unknown: the slot stays frozen on fid } } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go index cb4adfb98f..1f0fece56a 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "strings" "sync" "testing" "time" @@ -21,28 +22,31 @@ type rangeFake struct { reserves []int // requested counts, in order grant func(requested int) int auth func() string - refuse func(fid string) error // non-nil: the put fails with it - puts []string - putAuth map[string]string - inflight int - peak int - hold chan struct{} // non-nil: reserve waits for it (or ctx) + refuse func(fid string) error // non-nil: the put fails with it (nothing stored) + // reserveHook, when set, runs before each reserve (call counts from 1); + // an error fails the reserve. It decides itself whether to follow ctx. + reserveHook func(ctx context.Context, call int) error + // putHook, when set, decides each put: store the bytes or not, and the + // error to return (a stored put with an error is a lost reply). + putHook func(ctx context.Context, fid string) (store bool, err error) + puts []string + putAuth map[string]string + putDL map[string]time.Time // deadline of the context each put was sent under } func newRangeFake() *rangeFake { - return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}} + return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}, putDL: map[string]time.Time{}} } func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) { b.mu.Lock() b.reserves = append(b.reserves, n) - hold := b.hold + call := len(b.reserves) + hook := b.reserveHook b.mu.Unlock() - if hold != nil { - select { - case <-hold: - case <-ctx.Done(): - return blobRange{}, ctx.Err() + if hook != nil { + if err := hook(ctx, call); err != nil { + return blobRange{}, err } } b.mu.Lock() @@ -57,7 +61,7 @@ func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, er } vid := b.nextVid b.nextVid++ - return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake", auth: auth}, nil + return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake:1", auth: auth}, nil } func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error { @@ -68,17 +72,46 @@ func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byt b.mu.Lock() b.puts = append(b.puts, fid) b.putAuth[fid] = r.auth - refuse := b.refuse + if dl, ok := ctx.Deadline(); ok { + b.putDL[fid] = dl + } + refuse, hook := b.refuse, b.putHook b.mu.Unlock() + store, perr := true, error(nil) if refuse != nil { if err := refuse(fid); err != nil { - return err + store, perr = false, err } } + if hook != nil { + store, perr = hook(ctx, fid) + } + if store { + b.fakeBlobs.mu.Lock() + b.fakeBlobs.data[fid] = append([]byte(nil), data...) + b.fakeBlobs.mu.Unlock() + } + return perr +} + +func (b *rangeFake) probe(_ context.Context, r blobRange, i int) ([]byte, error) { + fid, err := r.fid(i) + if err != nil { + return nil, err + } b.fakeBlobs.mu.Lock() - b.fakeBlobs.data[fid] = append([]byte(nil), data...) - b.fakeBlobs.mu.Unlock() - return nil + defer b.fakeBlobs.mu.Unlock() + d, ok := b.fakeBlobs.data[fid] + if !ok { + return nil, fmt.Errorf("%w %s", errBlobAbsent, fid) + } + return append([]byte(nil), d...), nil +} + +func (b *rangeFake) putList() []string { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.puts...) } func (b *rangeFake) reserveCounts() []int { @@ -321,23 +354,275 @@ func TestChunkRound_RetryKeepsTheSlot(t *testing.T) { } } -// A reservation waiting on the filer ends with the caller's context, and a -// reply that arrives after it never starts an upload. +// A reservation waiting on the filer ends with the caller's context when it +// follows it; one that ignores it is still joined (Put does not return +// before it), and its late successful reply never starts an upload. func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { b := newRangeFake() - b.hold = make(chan struct{}) + hold := make(chan struct{}) + b.reserveHook = func(ctx context.Context, _ int) error { + select { + case <-hold: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } r := roundRemote(t, b) - rd := r.BeginPutRound(1, 4096) ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() - if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) { + if err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("held reservation: %v", err) } - close(b.hold) + close(hold) + + b2 := newRangeFake() + hold2 := make(chan struct{}) + b2.reserveHook = func(context.Context, int) error { <-hold2; return nil } // ignores ctx + r2 := roundRemote(t, b2) + ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel2() + done := make(chan error, 1) + go func() { done <- r2.BeginPutRound(1, 4096).Put(ctx2, 0, roundKey(0), []byte("x")) }() + select { + case err := <-done: + t.Fatalf("Put returned (%v) while its reservation call was still running", err) + case <-time.After(200 * time.Millisecond): + } + close(hold2) // the late reply is a success + if err := <-done; !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("late reply after the caller gave up: %v", err) + } + if puts := b2.putList(); len(puts) != 0 { + t.Fatalf("uploads %v after the caller gave up", puts) + } +} + +// A replacement reply that arrives after a lower slot retired the group's +// ranges is discarded: the group is reserved again from its first uncovered +// slot, so no slot is left uncovered (and no zero-id reservation is asked). +func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { + b := newRangeFake() + r := roundRemote(t, b) + rd := r.BeginPutRound(4, 4096).(*putRound) + g := rd.groups[0] + second := make(chan struct{}) + release := make(chan struct{}) + b.reserveHook = func(_ context.Context, call int) error { + if call == 2 { + close(second) + <-release + } + return nil + } + slot0Sent := make(chan struct{}) + b.putHook = func(_ context.Context, fid string) (bool, error) { + switch fid { + case "1,0a0b0c0d0e_1": // slot 1: refused at once + return false, errRangeRefused + case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight + close(slot0Sent) + <-second + return false, errRangeRefused + } + return true, nil + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + errs := make(chan error, 2) + go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }() + <-slot0Sent + go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }() + <-second + for { // slot 0's refusal retires the rest of the group meanwhile + g.mu.Lock() + v := g.ver + g.mu.Unlock() + if v == 2 { + break + } + time.Sleep(time.Millisecond) + } + close(release) + for k := 0; k < 2; k++ { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + got := b.reserveCounts() + for _, n := range got { + if n <= 0 { + t.Fatalf("reservations %v: asked for %d ids", got, n) + } + } + if len(got) != 3 || got[0] != 4 || got[1] != 3 || got[2] != 4 { + t.Fatalf("reservations %v; want [4 3 4] (the stale [1,4) reply discarded)", got) + } + for i := 0; i < 2; i++ { + if fid := r.fids[roundKey(i)]; !strings.HasPrefix(fid, "3,") { + t.Fatalf("slot %d bound to %s; want the fresh range", i, fid) + } + } + if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 || a.Retry != 1 || a.Failed != 1 { + t.Fatalf("assign counts %+v", a) + } +} + +// A lost reservation reply is counted: the retry is an extra attempt. +func TestChunkRound_LostReservationReplyIsCounted(t *testing.T) { + b := newRangeFake() + b.reserveHook = func(_ context.Context, call int) error { + if call == 1 { + return errors.New("lost assign reply") + } + return nil + } + r := roundRemote(t, b) + rd := r.BeginPutRound(1, 4096) + ctx := context.Background() + if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err == nil { + t.Fatal("lost reply reported success") + } + if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err != nil { + t.Fatal(err) + } + if a := r.AssignCounts(); a.Initial != 1 || a.Retry != 1 || a.Failed != 1 || a.Extra() != 1 { + t.Fatalf("assign counts %+v; want 1 initial + 1 retry, 1 failed", a) + } +} + +// An upload whose reply was lost keeps its fid: a retry after the group's +// lower slot retired the range, or after the token expired, does not move +// it. Past expiry the fid is read back: the exact bytes are bound there, +// definitely absent bytes go to a fresh range. +func TestChunkRound_AmbiguousUploadKeepsItsFid(t *testing.T) { + ctx := context.Background() + t.Run("lower slot retires the range", func(t *testing.T) { + b := newRangeFake() + lost := true + b.putHook = func(_ context.Context, fid string) (bool, error) { + switch { + case fid == "1,0a0b0c0d0e_1" && lost: + lost = false + return false, errors.New("connection reset") // outcome unknown to the client + case fid == "1,0a0b0c0d0e": + return false, errRangeRefused + } + return true, nil + } + r := roundRemote(t, b) + rd := r.BeginPutRound(2, 4096) + if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil { + t.Fatal("lost reply reported success") + } + if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { + t.Fatal(err) + } + if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil { + t.Fatal(err) + } + if fid := r.fids[roundKey(1)]; fid != "1,0a0b0c0d0e_1" { + t.Fatalf("retried slot bound to %s; want its first fid", fid) + } + if fid := r.fids[roundKey(0)]; !strings.HasPrefix(fid, "2,") { + t.Fatalf("refused slot bound to %s; want the fresh range", fid) + } + }) + for _, stored := range []bool{true, false} { + t.Run(fmt.Sprintf("token expires, stored=%v", stored), func(t *testing.T) { + b := newRangeFake() + calls := 0 + b.auth = func() string { + calls++ + if calls == 1 { // expires (less skew) about a second from now + return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) + } + return jwtWithExp(time.Now().Add(time.Hour).Unix()) + } + lost := true + b.putHook = func(context.Context, string) (bool, error) { + if lost { + lost = false + return stored, errors.New("reply lost") + } + return true, nil + } + r := roundRemote(t, b) + rd := r.BeginPutRound(1, 4096) + if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err == nil { + t.Fatal("lost reply reported success") + } + b.mu.Lock() + first := b.putAuth["1,0a0b0c0d0e"] + b.mu.Unlock() + dl, _ := (blobRange{auth: first}).sendDeadline() + time.Sleep(time.Until(dl) + 10*time.Millisecond) + if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { + t.Fatal(err) + } + fid, puts := r.fids[roundKey(0)], b.putList() + if stored { + if fid != "1,0a0b0c0d0e" || len(puts) != 1 { + t.Fatalf("stored upload: bound %s after uploads %v; want its first fid, no resend", fid, puts) + } + return + } + if !strings.HasPrefix(fid, "2,") || len(puts) != 2 { + t.Fatalf("absent upload: bound %s after uploads %v; want a fresh range", fid, puts) + } + if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 { + t.Fatalf("assign counts %+v", a) + } + }) + } +} + +// An upload is sent under its token's send deadline: a queued upload ends +// there, not at the caller's later deadline. +func TestChunkRound_UploadCarriesTheTokenDeadline(t *testing.T) { + b := newRangeFake() + b.auth = func() string { return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) } + b.putHook = func(ctx context.Context, _ string) (bool, error) { + <-ctx.Done() // queued until its context ends + return false, ctx.Err() + } + r := roundRemote(t, b) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + start := time.Now() + err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) + if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 10*time.Second { + t.Fatalf("queued upload: %v after %v; want it ended at the token's deadline", err, time.Since(start)) + } b.mu.Lock() - n := len(b.puts) - b.mu.Unlock() - if n != 0 { - t.Fatalf("%d uploads after the caller gave up", n) + defer b.mu.Unlock() + for f, a := range b.putAuth { + dl, _ := (blobRange{auth: a}).sendDeadline() + if !b.putDL[f].Equal(dl) { + t.Fatalf("upload to %s sent under deadline %v; want the token's %v", f, b.putDL[f], dl) + } + } +} + +// A rejected token and used-up replacements are final for the caller; a +// transient failure is not. +func TestChunkRound_FinalOutcomes(t *testing.T) { + put := func(b *rangeFake) error { + return roundRemote(t, b).BeginPutRound(1, 4096).Put(context.Background(), 0, roundKey(0), []byte("x")) + } + b := newRangeFake() + b.refuse = func(string) error { return errRangeAuth } + if err := put(b); !errors.Is(err, storage.ErrChunkPutFinal) { + t.Fatalf("401: %v; want final", err) + } + b2 := newRangeFake() + b2.refuse = func(string) error { return errRangeRefused } + if err := put(b2); !errors.Is(err, storage.ErrChunkPutFinal) { + t.Fatalf("replacements used up: %v; want final", err) + } + b3 := newRangeFake() + b3.refuse = func(string) error { return errors.New("connection reset") } + if err := put(b3); err == nil || errors.Is(err, storage.ErrChunkPutFinal) { + t.Fatalf("transient failure: %v; want retryable", err) } } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch.go b/seaweed-block/core/frontend/chunkstore/swfs_batch.go index f50713697d..cb33513e33 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch.go @@ -15,6 +15,8 @@ import ( "errors" "fmt" "io" + "math" + "net" "net/http" "strconv" "strings" @@ -37,6 +39,9 @@ var ( errRangeRefused = errors.New("chunkstore: volume refused the write before append") // errRangeAuth: the volume rejected the upload's token. Terminal. errRangeAuth = errors.New("chunkstore: volume rejected the upload token") + // errBlobAbsent: the volume server holding a range has no needle at + // the probed fid. + errBlobAbsent = errors.New("chunkstore: no needle at fid") ) // blobRange is one batch reservation: count ids starting at base, on the @@ -86,13 +91,17 @@ func (r blobRange) sendDeadline() (time.Time, bool) { type rangeBlobs interface { reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) putRange(ctx context.Context, r blobRange, i int, data []byte) error + // probe reads offset i back from the range's volume server: + // errBlobAbsent when that server definitely has no such needle. + probe(ctx context.Context, r blobRange, i int) ([]byte, error) } var _ rangeBlobs = (*SWFS)(nil) -// validBaseFid checks ",": a decimal volume id, then hex -// with at least a cookie's 8 digits after a key, and no offset suffix. -func validBaseFid(fid string) error { +// validBaseFid checks "," for a range of count ids: a +// 32-bit decimal volume id, a 64-bit hex needle key (1 to 16 digits) and an +// 8-digit hex cookie, no offset suffix, and room for key + count - 1. +func validBaseFid(fid string, count int) error { vid, kc, ok := strings.Cut(fid, ",") if !ok || vid == "" { return fmt.Errorf("chunkstore: assign fid %q has no volume id", fid) @@ -100,14 +109,36 @@ func validBaseFid(fid string) error { if _, err := strconv.ParseUint(vid, 10, 32); err != nil { return fmt.Errorf("chunkstore: assign fid %q: volume id: %v", fid, err) } - if len(kc) <= 8 { - return fmt.Errorf("chunkstore: assign fid %q: no key before the cookie", fid) + if len(kc) <= 8 || len(kc) > 16+8 { + return fmt.Errorf("chunkstore: assign fid %q: want a 1..16 digit key and an 8 digit cookie", fid) } for _, c := range kc { if !strings.ContainsRune("0123456789abcdefABCDEF", c) { return fmt.Errorf("chunkstore: assign fid %q: not a plain hex key and cookie", fid) } } + key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64) + if err != nil { + return fmt.Errorf("chunkstore: assign fid %q: key: %v", fid, err) + } + if count > 0 && key > math.MaxUint64-uint64(count-1) { + return fmt.Errorf("chunkstore: assign fid %q: key + %d overflows", fid, count-1) + } + return nil +} + +// validHostPort checks a volume server location: host:port, no scheme or path. +func validHostPort(loc string) error { + host, port, err := net.SplitHostPort(loc) + if err != nil { + return fmt.Errorf("chunkstore: assign location %q: %v", loc, err) + } + if host == "" || strings.ContainsAny(host, "/ ?#@") { + return fmt.Errorf("chunkstore: assign location %q: bad host", loc) + } + if p, err := strconv.ParseUint(port, 10, 16); err != nil || p == 0 { + return fmt.Errorf("chunkstore: assign location %q: bad port", loc) + } return nil } @@ -131,16 +162,16 @@ func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, e if ar.GetError() != "" { return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError()) } - if ar.GetLocation().GetUrl() == "" { - return blobRange{}, fmt.Errorf("chunkstore: assign %d returned no location", n) - } - if err := validBaseFid(ar.GetFileId()); err != nil { + if err := validHostPort(ar.GetLocation().GetUrl()); err != nil { return blobRange{}, err } count := int(ar.GetCount()) if count <= 0 || count > n { return blobRange{}, fmt.Errorf("chunkstore: assign %d returned %d ids", n, count) } + if err := validBaseFid(ar.GetFileId(), count); err != nil { + return blobRange{}, err + } return blobRange{base: ar.FileId, count: count, url: ar.Location.Url, auth: ar.GetAuth(), fsync: ar.GetFsync()}, nil } @@ -155,6 +186,30 @@ func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) er return c.upload(ctx, r.url, fid, r.auth, r.fsync, data) } +// probe GETs offset i from the range's own volume server. +func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) { + fid, err := r.fid(i) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+r.url+"/"+fid, nil) + if err != nil { + return nil, err + } + resp, err := c.http.Do(req) + if err != nil { + return nil, fmt.Errorf("chunkstore: probe %s: %w", fid, err) + } + defer resp.Body.Close() + switch resp.StatusCode { + case http.StatusOK: + return io.ReadAll(resp.Body) + case http.StatusNotFound: + return nil, fmt.Errorf("%w %s", errBlobAbsent, fid) + } + return nil, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode) +} + // upload POSTs data raw to fid on the volume server at host. func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, data []byte) error { u := "http://" + host + "/" + fid diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go index aaea826fcc..7bad01ed29 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go @@ -149,6 +149,17 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { {"non-hex key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0dzz", Count: 4, Location: loc}, false, 0}, {"key too short for a cookie", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d", Count: 4, Location: loc}, false, 0}, {"assign error", 4, &filerpb.AssignVolumeResponse{Error: "no free volumes"}, false, 0}, + {"location with a scheme", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "http://127.0.0.1:1"}}, false, 0}, + {"location without a port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1"}}, false, 0}, + {"location with a bad port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:x"}}, false, 0}, + {"location with port 0", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:0"}}, false, 0}, + {"location with a path", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a/b:1"}}, false, 0}, + {"widest key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0123456789abcdef0a0b0c0d", Count: 4, Location: loc}, true, 4}, + {"key of 17 digits (leading zero)", 4, &filerpb.AssignVolumeResponse{FileId: "3,00123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, + {"key wider than 64 bits", 4, &filerpb.AssignVolumeResponse{FileId: "3,10123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, + {"last offset fits", 2, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 2, Location: loc}, true, 2}, + {"last offset overflows the key", 3, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 3, Location: loc}, false, 0}, + {"volume id wider than 32 bits", 4, &filerpb.AssignVolumeResponse{FileId: "4294967296,0a0b0c0d0e", Count: 4, Location: loc}, false, 0}, } { t.Run(c.name, func(t *testing.T) { s := startFakeFiler(t, &fakeFilerGRPC{assignResp: c.resp}) @@ -161,6 +172,19 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { } }) } + for _, n := range []int{1, 256, 4096} { + s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: int32(n), Location: loc}}) + r, err := s.reserve(context.Background(), n, 4096) + if err != nil || r.count != n { + t.Fatalf("reserve %d: %+v %v", n, r, err) + } + if _, err := r.fid(n - 1); err != nil { + t.Fatalf("reserve %d: last offset: %v", n, err) + } + if fid, err := r.fid(n); err == nil { + t.Fatalf("reserve %d: offset %d gave %q", n, n, fid) + } + } s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}}) for _, n := range []int{0, -1, maxRangeCount + 1} { if _, err := s.reserve(context.Background(), n, 4096); err == nil { diff --git a/seaweed-block/core/storage/chunk_put_round.go b/seaweed-block/core/storage/chunk_put_round.go index e9c661d9d3..1bab47a619 100644 --- a/seaweed-block/core/storage/chunk_put_round.go +++ b/seaweed-block/core/storage/chunk_put_round.go @@ -1,6 +1,13 @@ package storage -import "context" +import ( + "context" + "errors" +) + +// ErrChunkPutFinal marks a Put failure no retry can change (for example a +// rejected token): the caller stops retrying the object. +var ErrChunkPutFinal = errors.New("storage: chunk upload refused for good") // ChunkPutRounds is an optional ChunkRemote capability: the objects of one // upload round share remote reservations (batch assign) instead of taking diff --git a/seaweed-block/core/storage/chunk_put_round_test.go b/seaweed-block/core/storage/chunk_put_round_test.go index ea06562386..e9bbf7d5e3 100644 --- a/seaweed-block/core/storage/chunk_put_round_test.go +++ b/seaweed-block/core/storage/chunk_put_round_test.go @@ -1,8 +1,10 @@ package storage import ( + "bytes" "context" "errors" + "fmt" "sync" "testing" "time" @@ -119,3 +121,150 @@ func TestChunkCut_FailedRoundPublishesNothing(t *testing.T) { t.Fatalf("installed %d HEADs after a failed upload", len(heads)) } } + +// A final upload outcome is not retried: the object is sent once, its +// binding is checked, and the cut fails at once. +func TestChunkCut_FinalUploadIsNotRetried(t *testing.T) { + s, _ := newChunkTestStore(t) + f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()} + f.fail = func(int, int, int) error { return errors.Join(ErrChunkPutFinal, errors.New("token rejected")) } + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + start := time.Now() + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkPutFinal) { + t.Fatalf("cut with a final upload refusal: %v", err) + } + if took := time.Since(start); took > 5*time.Second { + t.Fatalf("cut took %v: the final refusal was retried", took) + } + f.mu.Lock() + defer f.mu.Unlock() + for k, n := range f.tries { + if n != 1 { + t.Fatalf("object %v sent %d times; want once", k, n) + } + } +} + +// heldRound blocks every round Put until released; cooperative Puts also +// end with their context. It records the bytes of every attempt. +type heldRound struct { + *fakeChunkRemote + cooperative bool + entered chan struct{} + release chan struct{} + once sync.Once + mu sync.Mutex + sent [][]byte + transient int // the first transient attempts fail after being recorded + mutate func() +} + +func (h *heldRound) BeginPutRound(n, objSize int) ChunkPutRound { return heldRoundPut{h} } + +type heldRoundPut struct{ h *heldRound } + +func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) error { + h := p.h + h.mu.Lock() + h.sent = append(h.sent, append([]byte(nil), data...)) + attempt := len(h.sent) + mutate := h.mutate + h.mu.Unlock() + h.once.Do(func() { close(h.entered) }) + if mutate != nil && attempt == 1 { + mutate() + } + if attempt <= h.transient { + return errors.New("transient upload failure") + } + if h.cooperative { + select { + case <-h.release: + case <-ctx.Done(): + return ctx.Err() + } + } else { + <-h.release + } + return h.fakeChunkRemote.Put(ctx, key, data) +} + +// While a round's upload call is held, guest writes go on; Close cancels a +// cooperative call and joins it; an uncooperative call is still joined: +// Close does not return before it does. +func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { + for _, cooperative := range []bool{true, false} { + t.Run(fmt.Sprintf("cooperative=%v", cooperative), func(t *testing.T) { + s, _ := newChunkTestStore(t) + h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative, entered: make(chan struct{}), release: make(chan struct{})} + layer := mustAttach(t, s, h, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + cutDone := make(chan error, 1) + go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() + select { + case <-h.entered: + case <-time.After(10 * time.Second): + t.Fatal("the cut never reached its upload") + } + wrote := make(chan struct{}) + go func() { w.write(t, s, 7, 0x77); close(wrote) }() + select { + case <-wrote: + case <-time.After(5 * time.Second): + t.Fatal("a guest write waited on the held upload call") + } + closeDone := make(chan error, 1) + go func() { closeDone <- layer.Close() }() + if !cooperative { + select { + case <-closeDone: + t.Fatal("Close returned while an uncooperative upload call was still running") + case <-time.After(300 * time.Millisecond): + } + close(h.release) + } + select { + case <-closeDone: + case <-time.After(10 * time.Second): + t.Fatal("Close did not return") + } + select { + case <-cutDone: + case <-time.After(5 * time.Second): + t.Fatal("the cut did not end with Close") + } + if cooperative { + close(h.release) + } + }) + } +} + +// A retried upload sends the bytes captured for the cut, not the guest's +// newer write to the same block. +func TestChunkCut_RetrySendsTheCapturedBytes(t *testing.T) { + s, _ := newChunkTestStore(t) + h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: true, entered: make(chan struct{}), release: make(chan struct{}), transient: 1} + close(h.release) + w := newWriteLog() + h.mutate = func() { w.write(t, s, 2, 0x99) } // the guest overwrites the block mid-upload + layer := mustAttach(t, s, h, ctConfig(1)) + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + h.mu.Lock() + defer h.mu.Unlock() + if len(h.sent) != 2 { + t.Fatalf("%d upload attempts; want the failed one and its retry", len(h.sent)) + } + if !bytes.Equal(h.sent[0], h.sent[1]) { + t.Fatal("the retry sent different bytes than the first attempt") + } + if bytes.Contains(h.sent[1], makeBlock(ctBlockSize, 0x99)) { + t.Fatal("the retry sent the guest's newer write") + } +} diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index a0a2239e0e..1d1547cd0f 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -43,6 +43,9 @@ func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data [ } return errChunkKeyExists } + if errors.Is(err, ErrChunkPutFinal) { + return err + } timer := time.NewTimer(backoff) select { case <-ctx.Done(): From a89eb5c9cba5202eeb8901e608c3cfe27a2296a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:20:34 -0800 Subject: [PATCH 05/15] chunkstore, storage: batch-assign second fold: authority check, failure-safe witnessed tests Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/chunk_remote_round_test.go | 184 +++++++++++++----- .../core/frontend/chunkstore/swfs_batch.go | 17 +- .../frontend/chunkstore/swfs_batch_test.go | 21 ++ .../core/storage/chunk_put_round_test.go | 117 ++++++++--- 4 files changed, 259 insertions(+), 80 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go index 1f0fece56a..bf9e1c5299 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go @@ -354,48 +354,99 @@ func TestChunkRound_RetryKeepsTheSlot(t *testing.T) { } } +// waitFor waits for ch, failing t after a bound. +func waitFor(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// releaser closes a channel once; registered as cleanup before any worker +// that waits on it starts, so a failing test never strands that worker. +func releaser(t *testing.T) (ch chan struct{}, release func()) { + ch = make(chan struct{}) + var once sync.Once + release = func() { once.Do(func() { close(ch) }) } + t.Cleanup(release) + return ch, release +} + // A reservation waiting on the filer ends with the caller's context when it // follows it; one that ignores it is still joined (Put does not return // before it), and its late successful reply never starts an upload. func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { - b := newRangeFake() - hold := make(chan struct{}) - b.reserveHook = func(ctx context.Context, _ int) error { - select { - case <-hold: - return nil - case <-ctx.Done(): - return ctx.Err() + t.Run("cooperative", func(t *testing.T) { + b := newRangeFake() + hold, _ := releaser(t) + entered := make(chan struct{}) + b.reserveHook = func(ctx context.Context, _ int) error { + close(entered) + select { + case <-hold: + return nil + case <-ctx.Done(): + return ctx.Err() + } } - } - r := roundRemote(t, b) - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - if err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("held reservation: %v", err) - } - close(hold) - - b2 := newRangeFake() - hold2 := make(chan struct{}) - b2.reserveHook = func(context.Context, int) error { <-hold2; return nil } // ignores ctx - r2 := roundRemote(t, b2) - ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel2() - done := make(chan error, 1) - go func() { done <- r2.BeginPutRound(1, 4096).Put(ctx2, 0, roundKey(0), []byte("x")) }() - select { - case err := <-done: - t.Fatalf("Put returned (%v) while its reservation call was still running", err) - case <-time.After(200 * time.Millisecond): - } - close(hold2) // the late reply is a success - if err := <-done; !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("late reply after the caller gave up: %v", err) - } - if puts := b2.putList(); len(puts) != 0 { - t.Fatalf("uploads %v after the caller gave up", puts) - } + r := roundRemote(t, b) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() + waitFor(t, entered, "the reservation call") + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled reservation: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("Put did not end with its context") + } + }) + t.Run("uncooperative", func(t *testing.T) { + b := newRangeFake() + hold, release := releaser(t) + entered := make(chan struct{}) + b.reserveHook = func(context.Context, int) error { close(entered); <-hold; return nil } // ignores ctx + r := roundRemote(t, b) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() + t.Cleanup(func() { // joins the worker whatever happens below + release() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Error("Put never returned") + } + }) + waitFor(t, entered, "the reservation call") + cancel() + select { + case err := <-done: + done <- err + t.Fatalf("Put returned (%v) while its admitted reservation call was still running", err) + case <-time.After(200 * time.Millisecond): + } + release() // the late reply is a success + select { + case err := <-done: + done <- err + if !errors.Is(err, context.Canceled) { + t.Fatalf("late reply after the caller gave up: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("Put did not return after its reservation call did") + } + if puts := b.putList(); len(puts) != 0 { + t.Fatalf("uploads %v after the caller gave up", puts) + } + }) } // A replacement reply that arrives after a lower slot retired the group's @@ -407,33 +458,58 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { rd := r.BeginPutRound(4, 4096).(*putRound) g := rd.groups[0] second := make(chan struct{}) - release := make(chan struct{}) - b.reserveHook = func(_ context.Context, call int) error { + var secondOnce sync.Once + release, releaseAll := releaser(t) + b.reserveHook = func(ctx context.Context, call int) error { if call == 2 { - close(second) - <-release + secondOnce.Do(func() { close(second) }) + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } } return nil } slot0Sent := make(chan struct{}) - b.putHook = func(_ context.Context, fid string) (bool, error) { + b.putHook = func(ctx context.Context, fid string) (bool, error) { switch fid { case "1,0a0b0c0d0e_1": // slot 1: refused at once return false, errRangeRefused case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight close(slot0Sent) - <-second + select { + case <-second: + case <-ctx.Done(): + return false, ctx.Err() + } return false, errRangeRefused } return true, nil } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() errs := make(chan error, 2) + started := 0 + t.Cleanup(func() { // release and join every worker started + releaseAll() + cancel() + for k := 0; k < started; k++ { + select { + case <-errs: + case <-time.After(10 * time.Second): + t.Error("a round worker never returned") + return + } + } + }) + started++ go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }() - <-slot0Sent + waitFor(t, slot0Sent, "slot 0's upload") + started++ go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }() - <-second + waitFor(t, second, "the replacement reservation") + deadline := time.Now().Add(10 * time.Second) for { // slot 0's refusal retires the rest of the group meanwhile g.mu.Lock() v := g.ver @@ -441,12 +517,20 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { if v == 2 { break } + if time.Now().After(deadline) { + t.Fatalf("group version %d; slot 0's refusal never retired the range", v) + } time.Sleep(time.Millisecond) } - close(release) - for k := 0; k < 2; k++ { - if err := <-errs; err != nil { - t.Fatal(err) + releaseAll() + for ; started > 0; started-- { + select { + case err := <-errs: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("a round worker did not finish") } } got := b.reserveCounts() diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch.go b/seaweed-block/core/frontend/chunkstore/swfs_batch.go index cb33513e33..5f0b18c891 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch.go @@ -18,6 +18,7 @@ import ( "math" "net" "net/http" + "net/url" "strconv" "strings" "time" @@ -127,18 +128,28 @@ func validBaseFid(fid string, count int) error { return nil } -// validHostPort checks a volume server location: host:port, no scheme or path. +// validHostPort checks a volume server location: a plain host:port HTTP +// authority ([v6]:port included), with no scheme, path, user, escape, +// space or control byte, so the range's uploads can be addressed at all. func validHostPort(loc string) error { + for _, c := range loc { + if c <= ' ' || c == 0x7f || strings.ContainsRune("/?#@\\", c) { + return fmt.Errorf("chunkstore: assign location %q: not a plain host:port", loc) + } + } host, port, err := net.SplitHostPort(loc) if err != nil { return fmt.Errorf("chunkstore: assign location %q: %v", loc, err) } - if host == "" || strings.ContainsAny(host, "/ ?#@") { - return fmt.Errorf("chunkstore: assign location %q: bad host", loc) + if host == "" { + return fmt.Errorf("chunkstore: assign location %q: no host", loc) } if p, err := strconv.ParseUint(port, 10, 16); err != nil || p == 0 { return fmt.Errorf("chunkstore: assign location %q: bad port", loc) } + if u, err := url.Parse("http://" + loc + "/"); err != nil || u.Host != loc { + return fmt.Errorf("chunkstore: assign location %q: not an HTTP authority", loc) + } return nil } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go index 7bad01ed29..fa0572a17d 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go @@ -154,6 +154,13 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { {"location with a bad port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:x"}}, false, 0}, {"location with port 0", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:0"}}, false, 0}, {"location with a path", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a/b:1"}}, false, 0}, + {"location with a tab", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1\t:1"}}, false, 0}, + {"location with a newline", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a\nb:1"}}, false, 0}, + {"location with a bad escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%zz:1"}}, false, 0}, + {"location with an escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%41:1"}}, false, 0}, + {"location with a space", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a b:1"}}, false, 0}, + {"location with a user", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "u@a:1"}}, false, 0}, + {"bracketed IPv6 location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "[::1]:8080"}}, true, 4}, {"widest key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0123456789abcdef0a0b0c0d", Count: 4, Location: loc}, true, 4}, {"key of 17 digits (leading zero)", 4, &filerpb.AssignVolumeResponse{FileId: "3,00123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, {"key wider than 64 bits", 4, &filerpb.AssignVolumeResponse{FileId: "3,10123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, @@ -185,6 +192,20 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { t.Fatalf("reserve %d: offset %d gave %q", n, n, fid) } } + // A rejected location leaves nothing to upload to: a round over it makes + // no upload at all. + vol := newBatchVolume(t) + bad := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: &filerpb.Location{Url: vol.host() + "\t"}}}) + rr, err := NewChunkRemote(newFakeFiler(), bad, "/swblock/vols/v1") + if err != nil { + t.Fatal(err) + } + if err := rr.BeginPutRound(2, 4096).Put(context.Background(), 0, "k00000", []byte("x")); err == nil { + t.Fatal("round over a malformed location stored an object") + } + if uploads, _, _ := vol.snapshot(); len(uploads) != 0 { + t.Fatalf("uploads %v after a malformed location", uploads) + } s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}}) for _, n := range []int{0, -1, maxRangeCount + 1} { if _, err := s.reserve(context.Background(), n, 4096); err == nil { diff --git a/seaweed-block/core/storage/chunk_put_round_test.go b/seaweed-block/core/storage/chunk_put_round_test.go index e9bbf7d5e3..bb1aaeb862 100644 --- a/seaweed-block/core/storage/chunk_put_round_test.go +++ b/seaweed-block/core/storage/chunk_put_round_test.go @@ -148,19 +148,27 @@ func TestChunkCut_FinalUploadIsNotRetried(t *testing.T) { } // heldRound blocks every round Put until released; cooperative Puts also -// end with their context. It records the bytes of every attempt. +// end with their context. It records the bytes of every attempt, and closes +// cancelled when an outstanding Put's context ends. type heldRound struct { *fakeChunkRemote cooperative bool entered chan struct{} + cancelled chan struct{} release chan struct{} once sync.Once + cancelOnce sync.Once mu sync.Mutex sent [][]byte transient int // the first transient attempts fail after being recorded mutate func() } +func newHeldRound(cooperative bool) *heldRound { + return &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative, + entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})} +} + func (h *heldRound) BeginPutRound(n, objSize int) ChunkPutRound { return heldRoundPut{h} } type heldRoundPut struct{ h *heldRound } @@ -179,6 +187,13 @@ func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) e if attempt <= h.transient { return errors.New("transient upload failure") } + go func() { // witness: the outstanding call's context ended + select { + case <-ctx.Done(): + h.cancelOnce.Do(func() { close(h.cancelled) }) + case <-h.release: + } + }() if h.cooperative { select { case <-h.release: @@ -191,54 +206,101 @@ func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) e return h.fakeChunkRemote.Put(ctx, key, data) } -// While a round's upload call is held, guest writes go on; Close cancels a -// cooperative call and joins it; an uncooperative call is still joined: -// Close does not return before it does. +// waitDone waits for ch, failing t after a bound. +func waitDone(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// While a round's upload call is held, guest writes and flushes go on; +// Close cancels the call's context, then joins it: a cooperative call ends +// and Close returns; an uncooperative one is still joined, and Close does +// not return before it does. func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { for _, cooperative := range []bool{true, false} { t.Run(fmt.Sprintf("cooperative=%v", cooperative), func(t *testing.T) { s, _ := newChunkTestStore(t) - h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative, entered: make(chan struct{}), release: make(chan struct{})} + h := newHeldRound(cooperative) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(h.release) }) } layer := mustAttach(t, s, h, ctConfig(1)) w := newWriteLog() w.write(t, s, 2, 0x22) cutDone := make(chan error, 1) - go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() - select { - case <-h.entered: - case <-time.After(10 * time.Second): - t.Fatal("the cut never reached its upload") - } - wrote := make(chan struct{}) - go func() { w.write(t, s, 7, 0x77); close(wrote) }() - select { - case <-wrote: - case <-time.After(5 * time.Second): - t.Fatal("a guest write waited on the held upload call") - } closeDone := make(chan error, 1) + closeStarted := false + t.Cleanup(func() { // release, then join every worker started + release() + for _, c := range []struct { + ch chan error + started bool + }{{cutDone, true}, {closeDone, closeStarted}} { + if !c.started { + continue + } + select { + case <-c.ch: + case <-time.After(10 * time.Second): + t.Error("a worker never returned") + } + } + }) + go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() + waitDone(t, h.entered, "the cut's upload call") + + guest := make(chan error, 1) + go func() { + if _, err := s.Write(7, makeBlock(ctBlockSize, 0x77)); err != nil { + guest <- err + return + } + _, err := s.Sync() + guest <- err + }() + select { + case err := <-guest: + if err != nil { + t.Fatalf("guest write/flush during the held upload: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("a guest write or flush waited on the held upload call") + } + + closeStarted = true go func() { closeDone <- layer.Close() }() + // Close has cancelled the layer's calls: it is past cancel, at its join. + waitDone(t, h.cancelled, "Close cancelling the held call") if !cooperative { select { - case <-closeDone: + case err := <-closeDone: + closeDone <- err t.Fatal("Close returned while an uncooperative upload call was still running") case <-time.After(300 * time.Millisecond): } - close(h.release) + release() } select { - case <-closeDone: + case err := <-closeDone: + closeDone <- err + if err != nil { + t.Fatalf("Close: %v", err) + } case <-time.After(10 * time.Second): t.Fatal("Close did not return") } select { - case <-cutDone: - case <-time.After(5 * time.Second): + case err := <-cutDone: + cutDone <- err + if err == nil { + t.Fatal("the cut succeeded across Close") + } + case <-time.After(10 * time.Second): t.Fatal("the cut did not end with Close") } - if cooperative { - close(h.release) - } }) } } @@ -247,7 +309,8 @@ func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { // newer write to the same block. func TestChunkCut_RetrySendsTheCapturedBytes(t *testing.T) { s, _ := newChunkTestStore(t) - h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: true, entered: make(chan struct{}), release: make(chan struct{}), transient: 1} + h := newHeldRound(true) + h.transient = 1 close(h.release) w := newWriteLog() h.mutate = func() { w.write(t, s, 2, 0x99) } // the guest overwrites the block mid-upload From 4bd3c3b0cecbdd79473a10bf2558f91c685fb627 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:38:12 -0800 Subject: [PATCH 06/15] test(chunkstore, storage): join every held worker in cleanup Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/chunk_remote_round_test.go | 18 ++++++++++++++++-- .../core/storage/chunk_put_round_test.go | 10 ++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go index bf9e1c5299..a86a5f9e64 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go @@ -395,11 +395,24 @@ func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan error, 1) + joined := false + t.Cleanup(func() { // ends and joins the worker whatever happens below + cancel() + if joined { + return + } + select { + case <-done: + case <-time.After(10 * time.Second): + t.Error("Put never returned") + } + }) go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() waitFor(t, entered, "the reservation call") cancel() select { case err := <-done: + joined = true if !errors.Is(err, context.Canceled) { t.Fatalf("cancelled reservation: %v", err) } @@ -494,7 +507,7 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { t.Cleanup(func() { // release and join every worker started releaseAll() cancel() - for k := 0; k < started; k++ { + for ; started > 0; started-- { select { case <-errs: case <-time.After(10 * time.Second): @@ -523,9 +536,10 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { time.Sleep(time.Millisecond) } releaseAll() - for ; started > 0; started-- { + for started > 0 { select { case err := <-errs: + started-- // joined, before any Fatal: cleanup must not wait for it again if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_put_round_test.go b/seaweed-block/core/storage/chunk_put_round_test.go index bb1aaeb862..cb597c9b57 100644 --- a/seaweed-block/core/storage/chunk_put_round_test.go +++ b/seaweed-block/core/storage/chunk_put_round_test.go @@ -232,13 +232,14 @@ func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { w.write(t, s, 2, 0x22) cutDone := make(chan error, 1) closeDone := make(chan error, 1) - closeStarted := false - t.Cleanup(func() { // release, then join every worker started + guest := make(chan error, 1) + closeStarted, guestStarted := false, false + t.Cleanup(func() { // release, then join every worker started and not yet joined release() for _, c := range []struct { ch chan error started bool - }{{cutDone, true}, {closeDone, closeStarted}} { + }{{cutDone, true}, {closeDone, closeStarted}, {guest, guestStarted}} { if !c.started { continue } @@ -252,7 +253,7 @@ func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() waitDone(t, h.entered, "the cut's upload call") - guest := make(chan error, 1) + guestStarted = true go func() { if _, err := s.Write(7, makeBlock(ctBlockSize, 0x77)); err != nil { guest <- err @@ -263,6 +264,7 @@ func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { }() select { case err := <-guest: + guestStarted = false // joined if err != nil { t.Fatalf("guest write/flush during the held upload: %v", err) } From aabbd7f0123e1956ed77cb1e4d6e057135cc0bcb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:24:25 -0800 Subject: [PATCH 07/15] test(durable): an explicit cut overlapping the timer deadline restarts it (red) Co-Authored-By: Claude Opus 5.5 --- .../durable/provider_chunk_sched_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 6e75b9234d..7171e17de6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -4,6 +4,7 @@ package durable_test import ( "context" + "sync/atomic" "testing" "time" @@ -162,3 +163,66 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { t.Fatalf("walstore status: %+v", st) } } + +// slowCASRemote delays the next HEAD CAS once, by the armed duration. +type slowCASRemote struct { + *storage.MemChunkRemote + delay atomic.Int64 // ns; taken by the next CAS +} + +func (r *slowCASRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if d := time.Duration(r.delay.Swap(0)); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return 0, ctx.Err() + } + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + +// An explicit cut still running when the loop's timer comes due restarts the +// timer all the same: the automatic cut the loop decided on meanwhile does +// not follow the explicit one; the next one comes an interval after it. +func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { + const interval = 3 * time.Second + remote := &slowCASRemote{MemChunkRemote: 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) + } + // The explicit cut's CAS waits until well past the loop's first + // deadline (at most begin + interval): the loop comes due mid-cut. + remote.delay.Store(int64(1500 * time.Millisecond)) // below the CAS operation timeout + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + explicit := time.Now() + if !explicit.After(begin.Add(interval)) { + t.Fatalf("explicit cut ended %v after the start; want past the loop's first deadline", explicit.Sub(begin)) + } + 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) + } + // Well inside explicit + interval: no automatic cut. + time.Sleep(time.Until(explicit.Add(interval / 2))) + if time.Now().After(explicit.Add(interval - 300*time.Millisecond)) { + t.Skip("scheduling too slow to separate the 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) + } + // The timer still runs: the automatic cut follows. + for headGen(t, remote).Gen < 2 { + time.Sleep(50 * time.Millisecond) + } +} From 7da3da0fe2327b31745888e0b9345f687e8d6384 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:25:58 -0800 Subject: [PATCH 08/15] durable, storage: a periodic cut skips when another cut completed after its decision Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_chunk.go | 12 ++++++- .../core/storage/chunk_periodic_cut.go | 29 +++++++++++++++ .../core/storage/chunk_periodic_cut_test.go | 36 +++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_periodic_cut.go create mode 100644 seaweed-block/core/storage/chunk_periodic_cut_test.go diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 32e83250d0..b540dcd889 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -760,7 +760,17 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer if !ok { continue } - _, err := layer.Cut(ctx) + var err error + if pc, ok := layer.(storage.ChunkPeriodicCutter); ok { + // A cut that completed after this decision (an explicit one + // running meanwhile) restarted the timer: no cut now. + var skipped bool + if _, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs); skipped { + continue + } + } else { + _, 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) diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go new file mode 100644 index 0000000000..49822ee959 --- /dev/null +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -0,0 +1,29 @@ +package storage + +import "context" + +// ChunkPeriodicCutter is the chunk layer's cut for a periodic timer. The +// timer decides a cut is due from the last successful cut it saw; another +// cut (explicit, snapshot, detach, no-op) may still be running then and +// complete before this one gets the capture lock. That cut restarted the +// timer, so the due cut is not taken. +type ChunkPeriodicCutter interface { + // CutUnlessCutSince cuts unless a cut succeeded after lastCutNs (the + // LastCutNs the timer decided on); skipped reports that it did not cut. + CutUnlessCutSince(ctx context.Context, lastCutNs int64) (r ChunkCutResult, skipped bool, err error) +} + +var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil) + +func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + l.stMu.Lock() + last := l.stats.LastCutNs + l.stMu.Unlock() + if last > lastCutNs { + return chunkCutResult{}, true, nil + } + r, err := l.captureLocked(ctx, false) + return r, false, err +} diff --git a/seaweed-block/core/storage/chunk_periodic_cut_test.go b/seaweed-block/core/storage/chunk_periodic_cut_test.go new file mode 100644 index 0000000000..5289cb8b9a --- /dev/null +++ b/seaweed-block/core/storage/chunk_periodic_cut_test.go @@ -0,0 +1,36 @@ +package storage + +import "testing" + +// A periodic cut decided before another cut completed is skipped; decided +// after the last cut, it cuts. +func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + pc, ok := layer.(ChunkPeriodicCutter) + if !ok { + t.Fatal("the chunk layer has no periodic cut") + } + w := newWriteLog() + w.write(t, s, 2, 0x22) + decided := layer.Stats().LastCutNs // the timer decides here... + if _, err := layer.Cut(ctTimeout(t)); err != nil { // ...then another cut completes first + t.Fatal(err) + } + w.write(t, s, 9, 0x29) + casBefore := f.stats().cas + if _, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), decided); err != nil || !skipped { + t.Fatalf("periodic cut decided before a newer cut: skipped=%v err=%v; want skipped", skipped, err) + } + if f.stats().cas != casBefore { + t.Fatal("a skipped periodic cut published") + } + r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().LastCutNs) + if err != nil || skipped || r.Noop { + t.Fatalf("periodic cut decided after the last cut: skipped=%v noop=%v err=%v; want a cut", skipped, r.Noop, err) + } + if f.stats().cas != casBefore+1 { + t.Fatalf("CAS calls %d -> %d; want one", casBefore, f.stats().cas) + } +} From 116c1688bc2f4f9f9d179ab125804ee6287737fa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:47:48 -0800 Subject: [PATCH 09/15] fix(storage): budget detach from the guest freeze origin --- .../core/frontend/durable/provider_chunk.go | 53 ++++++++- .../durable/provider_frozen_budget_test.go | 50 +++++++++ .../core/host/volume/chunk_control.go | 76 ++++++++++--- .../host/volume/chunk_frozen_budget_test.go | 66 ++++++++++++ .../core/storage/chunk_candidate_tail_test.go | 47 ++++++++ .../core/storage/chunk_fixed_spans_test.go | 68 ++++++++++++ .../core/storage/chunk_frozen_budget.go | 58 ++++++++++ .../core/storage/chunk_frozen_budget_test.go | 88 +++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 81 ++++++++++---- seaweed-block/core/storage/chunk_precopy.go | 101 ++++++++++++++++-- seaweed-block/core/storage/chunk_seam.go | 35 ++++-- 11 files changed, 667 insertions(+), 56 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_frozen_budget_test.go create mode 100644 seaweed-block/core/host/volume/chunk_frozen_budget_test.go create mode 100644 seaweed-block/core/storage/chunk_candidate_tail_test.go create mode 100644 seaweed-block/core/storage/chunk_fixed_spans_test.go create mode 100644 seaweed-block/core/storage/chunk_frozen_budget.go create mode 100644 seaweed-block/core/storage/chunk_frozen_budget_test.go diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 32e83250d0..8d6886a95d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -886,6 +886,15 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st return p.detachVolume(ctx, volumeID, false) } +// DetachVolumeFrozen uses one budgeted cut when the guest is already frozen. +func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) { + ctx, err := storage.WithFrozenDetach(ctx, opts) + if err != nil { + return storage.ChunkCutResult{}, 0, err + } + return p.detachVolume(ctx, volumeID, false) +} + // ErrPlainDetachBusy refuses a plain detach without closing frontend admission. var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O") @@ -913,11 +922,15 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla return storage.ChunkCutResult{}, 0, err } } - precopy := p.cfg.ChunkDetachPrecopy && !plain + guestFreeze, guestFrozen := storage.FrozenDetachFromContext(ctx) + precopy := (p.cfg.ChunkDetachPrecopy || guestFrozen) && !plain freeze := p.cfg.DetachFreezeTimeout if freeze <= 0 { freeze = defaultDetachFreezeTimeout } + if guestFrozen && !guestFreeze.AllowOverBudget { + freeze = detachFreezeTarget + } // One freeze budget covers the drain, the final cut AND the settlement: // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. @@ -934,10 +947,27 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla cutCtx, cancel := context.WithCancelCause(accountCtx) defer cancel(context.Canceled) var timer *time.Timer + var settleDeadline time.Time beginFreeze := func() { + if timer != nil { + return + } start = time.Now() + if guestFrozen { + start = guestFreeze.StartedAt + } casAtFreeze = countCAS() - timer = time.AfterFunc(freeze*3/4, func() { cancel(context.DeadlineExceeded) }) + operationStart := start + if guestFrozen && guestFreeze.AllowOverBudget { + operationStart = time.Now() + } + settleDeadline = operationStart.Add(freeze) + remaining := max(time.Duration(0), time.Until(settleDeadline)) + // An already exhausted normal guest budget must reach the no-I/O + // forecast refusal, rather than racing a zero-delay cancellation. + if remaining > 0 { + timer = time.AfterFunc(remaining*3/4, func() { cancel(context.DeadlineExceeded) }) + } } defer func() { if timer != nil { @@ -959,6 +989,9 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } var r storage.ChunkCutResult + if guestFrozen { + beginFreeze() + } if precopy { owner, ok := layer.(interface { PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) @@ -981,12 +1014,18 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla }) // Log only after capture releases its barrier; at most five records. for _, a := range r.Precopy.Rounds { + p := a.FixedParts + log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_store_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond)) log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f map_persist_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.MapPersist)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), a.Error) } log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { if !start.IsZero() { - r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false) + elapsed := time.Since(start) + if !guestFrozen { + elapsed += r.Precopy.BarrierBeforeFreeze + } + r.Precopy.Finish(elapsed, 0, false) } return r, h.storage.NextLSN() - 1, nil } @@ -1036,7 +1075,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // resumes: an earlier detach that applied, an unresolved detach CAS or a // fenced layer must never resume serving. The settlement keeps the rest // of the freeze budget even when the caller's context is gone. - sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), start.Add(freeze)) + sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline) defer scancel() if trace := p.testDetachTrace; trace != nil { dl, _ := sctx.Deadline() @@ -1049,7 +1088,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla if attempts > 0 { extra = attempts - 1 } - r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, extra, true) + elapsed := time.Since(start) + if !guestFrozen { + elapsed += r.Precopy.BarrierBeforeFreeze + } + r.Precopy.Finish(elapsed, extra, true) log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr) dr.Precopy = r.Precopy } diff --git a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go new file mode 100644 index 0000000000..a721c9a3aa --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go @@ -0,0 +1,50 @@ +package durable_test + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync/atomic" + "testing" + "time" +) + +type frozenCountRemote struct { + storage.ChunkRemote + puts atomic.Int64 +} + +func (r *frozenCountRemote) Put(ctx context.Context, key string, p []byte) error { + r.puts.Add(1) + return r.ChunkRemote.Put(ctx, key, p) +} +func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) { + mem := storage.NewMemChunkRemote() + remote := &frozenCountRemote{ChunkRemote: mem} + p, _ := parkedProvider(t, remote) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(context.Background(), 4096, block(0x77)); err != nil { + t.Fatal(err) + } + before, _ := remote.GetHead(context.Background()) + puts := remote.puts.Load() + r, _, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-6 * time.Second)}) + after, _ := remote.GetHead(context.Background()) + if !errors.Is(err, storage.ErrFrozenTailTooLarge) || r.Precopy.Frozen || puts != remote.puts.Load() || before.Gen != after.Gen { + t.Fatalf("frozen refusal mutated remote: %+v %v puts=%d/%d", r.Precopy, err, puts, remote.puts.Load()) + } + if _, err = b.Write(context.Background(), 8192, block(0x88)); err != nil { + t.Fatalf("refusal stopped serving before thaw: %v", err) + } + r, _, err = p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-time.Minute), AllowOverBudget: true}) + if err != nil || !r.Precopy.GuestFrozen || !r.Precopy.OverBudget || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 1 || r.Precopy.FreezeElapsed < time.Minute || r.Precopy.DeclaredWorst < time.Minute || !r.Precopy.LatencyGateFailed { + t.Fatalf("explicit final failed/underreported total freeze: %+v %v", r, err) + } + if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 { + t.Fatal("final detached point lost writes") + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 3308ce2d34..1321668cba 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -39,13 +39,14 @@ type ChunkControl interface { // ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). type ChunkCutResponse struct { - VolumeID string `json:"volumeID"` - CutLSN uint64 `json:"cutLSN"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - Holder string `json:"holder"` - Noop bool `json:"noop"` - FullHash bool `json:"fullHash"` + CandidateTail *storage.ChunkCandidateTail `json:"candidateTail,omitempty"` + VolumeID string `json:"volumeID"` + CutLSN uint64 `json:"cutLSN"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + Holder string `json:"holder"` + Noop bool `json:"noop"` + FullHash bool `json:"fullHash"` // Stats are the statistics the chunk layer measured for this cut // (§3.1). A zero field is "not measured" or "none" (a Noop cut // uploads nothing). @@ -56,6 +57,14 @@ type ChunkCutResponse struct { // mirrors storage.ChunkCutStats field for field (a test keeps the two in // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { + CandidateNs int64 `json:"candidateNs"` + WindowSetupNs int64 `json:"windowSetupNs"` + PublishPrepareNs int64 `json:"publishPrepareNs"` + ManifestNs int64 `json:"manifestNs"` + CommitStateNs int64 `json:"commitStateNs"` + IntentCleanupNs int64 `json:"intentCleanupNs"` + NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` + PayloadNs int64 `json:"payloadNs"` COWWALReadAttempts uint64 `json:"cowWALReadAttempts"` COWLocalReadNs int64 `json:"cowLocalReadNs"` @@ -88,6 +97,14 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ + CandidateNs: s.CandidateNs, + WindowSetupNs: s.WindowSetupNs, + PublishPrepareNs: s.PublishPrepareNs, + ManifestNs: s.ManifestNs, + CommitStateNs: s.CommitStateNs, + IntentCleanupNs: s.IntentCleanupNs, + NonPayloadCopyNs: s.NonPayloadCopyNs, + PayloadNs: s.PayloadNs, COWWALReadAttempts: s.COWWALReadAttempts, COWLocalReadNs: s.COWLocalReadNs, @@ -286,6 +303,12 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, codeClosing, false // stays closed until a new attach case errors.Is(err, storage.ErrChunkLayerClosed): return http.StatusServiceUnavailable, codeClosing, false // the process is shutting down + case errors.Is(err, errFrozenDetachUnsupported): + return http.StatusConflict, "frozen_detach_unsupported", false + case errors.Is(err, storage.ErrInvalidFreezeBudget): + return http.StatusBadRequest, "bad_request", false + case errors.Is(err, storage.ErrFrozenTailTooLarge): + return http.StatusConflict, "frozen_tail_too_large", true // A local window abort cancels its uploads; that cancellation is not // a remote outage. Keep authority and uncertain-publication precedence. case errors.Is(err, storage.ErrCutCOWAborted): @@ -496,13 +519,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) return } var req struct { - VolumeID string `json:"volumeID"` - TimeoutMs int64 `json:"timeoutMs"` - Plain bool `json:"plain,omitempty"` + VolumeID string `json:"volumeID"` + TimeoutMs int64 `json:"timeoutMs"` + Plain bool `json:"plain,omitempty"` + Frozen bool `json:"frozen,omitempty"` + FreezeStartedAtNs int64 `json:"freezeStartedAtNs,omitempty"` + AllowOverBudget bool `json:"allowOverBudget,omitempty"` } if !decodeChunkBody(w, r, &req) { return } + if (req.Frozen && (req.Plain || req.FreezeStartedAtNs <= 0 || time.Unix(0, req.FreezeStartedAtNs).After(time.Now()))) || (!req.Frozen && (req.FreezeStartedAtNs != 0 || req.AllowOverBudget)) { + writeChunkErr(w, http.StatusBadRequest, "bad_request", false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") + return + } ctl := s.chunkTarget(w, req.VolumeID) if ctl == nil { return @@ -511,7 +541,16 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) defer cancel() var res ChunkDetachResponse var err error - if req.Plain { + if req.Frozen { + frozen, ok := ctl.(interface { + DetachFrozen(context.Context, string, storage.FrozenDetachOptions) (ChunkDetachResponse, error) + }) + if !ok { + writeChunkErr(w, http.StatusConflict, "frozen_detach_unsupported", false, "frozen detach unsupported") + return + } + res, err = frozen.DetachFrozen(ctx, req.VolumeID, storage.FrozenDetachOptions{StartedAt: time.Unix(0, req.FreezeStartedAtNs), AllowOverBudget: req.AllowOverBudget}) + } else if req.Plain { plain, ok := ctl.(interface { DetachPlain(context.Context, string) (ChunkDetachResponse, error) }) @@ -543,6 +582,8 @@ type ChunkProvider interface { DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) } +var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") + type chunkControl struct { p ChunkProvider cat *chunkstore.Catalog @@ -560,7 +601,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) return ChunkCutResponse{}, err } return ChunkCutResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, Holder: r.Head.Holder, - Noop: r.Noop, FullHash: r.FullHash, Stats: cutStatsBody(r.Stats)}, nil + Noop: r.Noop, FullHash: r.FullHash, CandidateTail: r.CandidateTail, Stats: cutStatsBody(r.Stats)}, nil } // Snapshot resolves the request against the catalog first (§3.2 step 1): @@ -626,6 +667,17 @@ func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetach return chunkDetachResponse(volumeID, r, last, err) } +func (c *chunkControl) DetachFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (ChunkDetachResponse, error) { + p, ok := c.p.(interface { + DetachVolumeFrozen(context.Context, string, storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) + }) + if !ok { + return ChunkDetachResponse{}, errFrozenDetachUnsupported + } + r, last, err := p.DetachVolumeFrozen(ctx, volumeID, opts) + return chunkDetachResponse(volumeID, r, last, err) +} + func (c *chunkControl) DetachPlain(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { p, ok := c.p.(interface { DetachVolumePlain(context.Context, string) (storage.ChunkCutResult, uint64, error) diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go new file mode 100644 index 0000000000..58534c3fee --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -0,0 +1,66 @@ +package volume + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/seaweedfs/seaweed-block/core/storage" + "net/http" + "testing" + "time" +) + +type frozenDetachProvider struct { + *fakeChunkProvider + opts storage.FrozenDetachOptions + calls int + err error +} + +func (p *frozenDetachProvider) DetachVolumeFrozen(_ context.Context, _ string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) { + p.opts = opts + p.calls++ + return p.detach, p.last, p.err +} +func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) { + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}} + s := chunkServer(t, NewChunkControl(p, nil), true) + at := time.Now().Add(-time.Second).UnixNano() + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at) + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + if w.Code != 200 || p.calls != 1 || p.opts.StartedAt.UnixNano() != at || !p.opts.AllowOverBudget { + t.Fatalf("frozen wire lost fields: %d %s %+v", w.Code, w.Body, p.opts) + } + for _, invalid := range []string{`{"volumeID":"v1","frozen":true}`, `{"volumeID":"v1","allowOverBudget":true}`, fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, at)} { + before := p.calls + w = serve(t, s, http.MethodPost, "/chunk/detach", invalid, "") + if w.Code != 400 || p.calls != before { + t.Fatalf("invalid request reached provider: %d %s", w.Code, w.Body) + } + } + p.err = storage.ErrFrozenTailTooLarge + w = serve(t, s, http.MethodPost, "/chunk/detach", body, "") + var e chunkErrorBody + _ = json.Unmarshal(w.Body.Bytes(), &e) + if w.Code != 409 || e.Code != "frozen_tail_too_large" || !e.Retryable { + t.Fatalf("wrong frozen refusal: %d %s", w.Code, w.Body) + } + for _, terminal := range []error{storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced, storage.ErrChunkCASOutcomeUnknown} { + expectedStatus, expectedCode, expectedRetry := chunkErrorCode(terminal) + status, code, retry := chunkErrorCode(errors.Join(terminal, storage.ErrFrozenTailTooLarge)) + if status != expectedStatus || code != expectedCode || retry != expectedRetry { + t.Fatalf("frozen refusal hid terminal/unknown cause %v: %d %s %t", terminal, status, code, retry) + } + } +} +func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { + tail := &storage.ChunkCandidateTail{Bytes: 4096, Estimate: time.Second, Known: true, RateSamples: 3, BytesPerSecond: 4096} + p := &fakeChunkProvider{cut: storage.ChunkCutResult{CandidateTail: tail}} + s := chunkServer(t, NewChunkControl(p, nil), true) + w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "") + var body ChunkCutResponse + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 200 || body.CandidateTail == nil || *body.CandidateTail != *tail { + t.Fatalf("cut response lost tail: %d %s %v", w.Code, w.Body, err) + } +} diff --git a/seaweed-block/core/storage/chunk_candidate_tail_test.go b/seaweed-block/core/storage/chunk_candidate_tail_test.go new file mode 100644 index 0000000000..4bdd9648ff --- /dev/null +++ b/seaweed-block/core/storage/chunk_candidate_tail_test.go @@ -0,0 +1,47 @@ +package storage + +import ( + "testing" + "time" +) + +func TestCheckpointTailMeasuresWritesAfterItsCut(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: 2 * float64(ctChunkBytes)}) + } + w.write(t, s, 1, 0x11) + f.beforeCAS = func(*fakeChunkRemote) { f.beforeCAS = nil; w.write(t, s, 2, 0x22) } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + tail := r.CandidateTail + if tail == nil || tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond <= 0 { + t.Fatalf("missing post-cut dirty tail: %+v", tail) + } + expected := time.Duration(float64(tail.Bytes) / tail.BytesPerSecond * float64(time.Second)) + if expected > precopyDuration { + expected = precopyDuration + } + if tail.Estimate != expected { + t.Fatalf("tail and rate sampled inconsistently: %+v want=%s", tail, expected) + } + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.CandidateTail == nil || r.CandidateTail.Bytes != 0 || !r.CandidateTail.Known || r.CandidateTail.Estimate != 0 { + t.Fatalf("settled checkpoint not clean: %+v", r.CandidateTail) + } + assertEveryHeadIsPrefixImage(t, f, w) +} +func TestCheckpointTailUnknownRateIsNotZeroCost(t *testing.T) { + s, _, l, w := precopyLayer(t, 1024, 0) + w.write(t, s, 1, 0x44) + l.precopySamples = []precopySample{{at: time.Now(), fixed: time.Millisecond, rate: 100}} + tail := l.candidateTail() + if tail.Bytes == 0 || tail.Known || tail.RateSamples != 1 { + t.Fatalf("partial rate window misreported ready: %+v", tail) + } +} diff --git a/seaweed-block/core/storage/chunk_fixed_spans_test.go b/seaweed-block/core/storage/chunk_fixed_spans_test.go new file mode 100644 index 0000000000..4d19b7011e --- /dev/null +++ b/seaweed-block/core/storage/chunk_fixed_spans_test.go @@ -0,0 +1,68 @@ +package storage + +import ( + "context" + "reflect" + "testing" + "time" +) + +type fixedSpanRemote struct { + *fakeChunkRemote + delay time.Duration +} + +func (r *fixedSpanRemote) PrepareManifest(_ context.Context, _ ChunkHead, next ChunkHead, _ uint64) (ChunkHead, []string, error) { + time.Sleep(r.delay) + return next, nil, nil +} +func (r *fixedSpanRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) { + time.Sleep(r.delay) + return r.fakeChunkRemote.CASHead(ctx, v, h) +} + +func (r *fixedSpanRemote) DeleteIntent(ctx context.Context, id string) error { + time.Sleep(r.delay) + return r.fakeChunkRemote.DeleteIntent(ctx, id) +} +func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + delay := 10 * time.Millisecond + l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: delay} + w.write(t, s, 1, 0x32) + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"ManifestNs", "IntentCleanupNs"} { + v := reflect.ValueOf(r.Stats).FieldByName(name) + if !v.IsValid() || time.Duration(v.Int()) < delay { + t.Fatalf("missing fixed span %s: %+v", name, r.Stats) + } + } + if len(l.precopySamples) == 0 { + t.Fatal("no fixed sample") + } + parts := reflect.ValueOf(l.precopySamples[len(l.precopySamples)-1].parts) + for _, name := range []string{"Manifest", "IntentCleanup"} { + v := parts.FieldByName(name) + if !v.IsValid() || time.Duration(v.Int()) < delay { + t.Fatalf("missing selected fixed part %s", name) + } + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestPrecopyLiveBarrierSpansExplainOverage(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + seedFrozenSamples(l, time.Millisecond) + delay := 20 * time.Millisecond + l.testBeforeBarrierLockHook = func() { time.Sleep(delay) } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if err != nil { + t.Fatal(err) + } + if r.Precopy.BarrierOverage <= 0 || r.Precopy.BarrierParts.StoreLock < delay || len(r.Precopy.Rounds) != 1 || r.Precopy.Rounds[0].BarrierParts.StoreLock < delay { + t.Fatalf("live lock overage hidden as retained other: %+v", r.Precopy) + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go new file mode 100644 index 0000000000..9f81e4de31 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -0,0 +1,58 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "time" +) + +var ErrFrozenTailTooLarge = errors.New("storage: frozen tail does not fit remaining freeze budget") +var ErrInvalidFreezeBudget = errors.New("storage: invalid guest freeze budget") + +// FrozenDetachOptions is supplied by the trusted guest orchestrator. It owns +// the maximum two re-freeze cycles; AllowOverBudget explicitly requests its +// final attempt. It never bypasses authority, lifecycle or CAS settlement. +type FrozenDetachOptions struct { + StartedAt time.Time + AllowOverBudget bool +} +type frozenDetachKey struct{} + +func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) { + now := time.Now() + if opts.StartedAt.IsZero() || opts.StartedAt.Before(time.Unix(0, 1)) || opts.StartedAt.After(now) { + return nil, ErrInvalidFreezeBudget + } + // Convert remote wall time to a local monotonic origin once at admission. + opts.StartedAt = now.Add(-now.Sub(opts.StartedAt)) + return context.WithValue(ctx, frozenDetachKey{}, opts), nil +} +func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { + v, ok := ctx.Value(frozenDetachKey{}).(FrozenDetachOptions) + return v, ok +} +func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { + r.GuestFrozen = true + r.GuestFreezeElapsed = time.Since(opts.StartedAt) + r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) + known := r.Reason != "samples_unknown" && r.Estimate > 0 + if !known || r.Estimate > r.RemainingFreeze { + r.Reason = "frozen_tail_too_large" + if !opts.AllowOverBudget { + return false + } + r.Reason = "over_budget" + r.OverBudget = true + } else { + r.Reason = "fit" + } + r.DeclaredFreeze = r.GuestFreezeElapsed + r.Estimate + if !known { + r.DeclaredFreeze = max(r.DeclaredFreeze, precopyFreezeLimit) + } + return true +} +func frozenRefusal(r PrecopyReport) error { + return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget_test.go b/seaweed-block/core/storage/chunk_frozen_budget_test.go new file mode 100644 index 0000000000..174324318a --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_budget_test.go @@ -0,0 +1,88 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +func frozenContext(t *testing.T, elapsed time.Duration, force bool) context.Context { + t.Helper() + ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: time.Now().Add(-elapsed), AllowOverBudget: force}) + if err != nil { + t.Fatal(err) + } + return ctx +} +func seedFrozenSamples(l *chunkLayerImpl, fixed time.Duration) { + l.precopySamples = nil + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, rate: 20 * float64(ctChunkBytes)}) + } +} +func TestFrozenDetachRejectsBeforeStagingOrUpload(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x12) + seedFrozenSamples(l, 1300*time.Millisecond) + before := f.stats() + l.testBeforeBarrierLockHook = func() { t.Fatal("preflight rejection reached capture") } + r, err := l.PrecopyDetach(frozenContext(t, 4*time.Second, false), func() bool { t.Fatal("over-budget attempt stopped backend"); return true }) + after := f.stats() + if !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || r.Precopy.Reason != "frozen_tail_too_large" || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen { + t.Fatalf("over-budget frozen cut did work: %+v %v before=%+v after=%+v", r.Precopy, err, before, after) + } + l.testBeforeBarrierLockHook = nil + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x12)) { + t.Fatal("refusal dropped dirty bytes") + } +} +func TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x24) + seedFrozenSamples(l, time.Millisecond) + before := f.stats() + reached := false + l.testBeforeBarrierLockHook = func() { reached = true; seedFrozenSamples(l, 6*time.Second) } + r, err := l.PrecopyDetach(frozenContext(t, 0, false), func() bool { t.Fatal("authoritative refusal stopped backend"); return true }) + after := f.stats() + if !reached || !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 1 || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen { + t.Fatalf("barrier rejection uploaded or rolled: %+v %v", r.Precopy, err) + } + l.testBeforeBarrierLockHook = nil + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} +func TestFrozenDetachForcedFinalCommitsSamePoint(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x36) + seedFrozenSamples(l, 6*time.Second) + stops := 0 + r, err := l.PrecopyDetach(frozenContext(t, 6*time.Second, true), func() bool { stops++; return true }) + if err != nil || !r.Precopy.OverBudget || !r.Precopy.GuestFrozen || !r.Precopy.Frozen || r.Precopy.Reason != "over_budget" || len(r.Precopy.Rounds) != 1 || stops != 1 || r.Head.State != ChunkHeadDetached { + t.Fatalf("explicit final did not commit once: %+v %v", r, err) + } + if !r.Precopy.LatencyGateFailed || r.Precopy.FreezeElapsed < 6*time.Second { + t.Fatalf("external elapsed hidden: %+v", r.Precopy) + } + assertEveryHeadIsPrefixImage(t, f, w) + r2, err := l.PrecopyDetach(frozenContext(t, 7*time.Second, false), func() bool { t.Fatal("applied retry stopped again"); return true }) + if err != nil || r2.Head.Gen != r.Head.Gen { + t.Fatalf("applied retry budget-refused: %+v %v", r2, err) + } +} +func TestFrozenBudgetInputValidation(t *testing.T) { + for _, at := range []time.Time{{}, time.Now().Add(time.Hour)} { + if _, err := WithFrozenDetach(context.Background(), FrozenDetachOptions{StartedAt: at}); !errors.Is(err, ErrInvalidFreezeBudget) { + t.Fatalf("invalid origin accepted: %v", err) + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5c32d22aeb..93f9a20545 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -53,7 +53,7 @@ const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { // capMu serializes pre-copy admission and its recent measurements. - precopyFreeze func(uint64, time.Time) bool + precopyFreeze func(uint64, time.Time, chunkCutStats) bool precopyPrepare func(context.Context) (func(), error) precopySamples []precopySample precopyPause func(time.Duration) @@ -669,6 +669,16 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, err } + dropCapturedIntents := func(ctx context.Context, ids []string) { + start := time.Now() + l.dropIntents(ctx, ids) + st.IntentCleanupNs += time.Since(start).Nanoseconds() + } + finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { + start := time.Now() + l.finishCut(head, h, changed, keys) + st.CommitStateNs += time.Since(start).Nanoseconds() + } var pauseStart time.Time var payloadBeforeBarrier int64 defer func() { @@ -679,6 +689,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier l.samplePrecopy(st, fixed) } + res.CandidateTail = l.candidateTail() } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() @@ -690,7 +701,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.reusable = nil l.stMu.Unlock() - l.dropIntents(ctx, ids) + dropCapturedIntents(ctx, ids) } if observe := l.precopyPause; observe != nil { observe(time.Duration(st.BarrierPauseNs)) @@ -742,17 +753,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Pre-copy large native dirty sets outside the barrier, bounded by the // remaining COW exposure rather than a fixed candidate count. stageStart := time.Now() - staged, intents, err := l.stage(ctx, &st) + var staged map[uint64]stagedChunk + var intents []string + _, guestFrozen := FrozenDetachFromContext(ctx) + if !guestFrozen { + staged, intents, err = l.stage(ctx, &st) + } if st.UploadedBytes > 0 { st.PayloadNs += time.Since(stageStart).Nanoseconds() } if err != nil { - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } if cause := context.Cause(ctx); cause != nil { - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } @@ -777,7 +793,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch releasePrecopy() releasePrecopy = nil } - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } // Resume rejected tentative admission before any ordinary COW upload. @@ -802,9 +818,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if err != nil { unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() - l.dropIntents(ctx, intents) // a clean abort: staged keys are released + dropCapturedIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) } + candidateStart := time.Now() candidates := map[uint64]bool{} for idx := range l.captureCandidates() { candidates[idx] = true @@ -851,12 +868,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Candidates, mutation versions and births belong to the same barrier. // Do not sample the owned map after COW writers are admitted again. births := l.captureBirths(candidates, h) + st.CandidateNs += time.Since(candidateStart).Nanoseconds() // The authoritative candidate set is fixed with mutation admission closed. // The owner callback is nonblocking and may stop only an already drained // frontend; rejected attempts remain ordinary COW cuts. if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil { tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks - detach = freeze(tail, pauseStart) + detach = freeze(tail, pauseStart, st) + } + if guestFrozen && !detach { + unlockCapture() + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + l.abortCut(all) + dropCapturedIntents(ctx, intents) + return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit()) } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { @@ -866,7 +891,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // reached: publishing would move remote_lsn backwards. Refused // before any upload. (A HEAD of a newer holder fences below.) l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN) } @@ -876,11 +901,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch bytesBeforeCopy := st.UploadedBytes { var w *cutCOWWindow + windowStart := time.Now() w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) if copyErr == nil { w.budget = budget } unlockCapture() + st.WindowSetupNs += time.Since(windowStart).Nanoseconds() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() copyStart = time.Now() if copyErr == nil { @@ -904,11 +931,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { st.PayloadNs += st.CopyNs + } else { + st.NonPayloadCopyNs += st.CopyNs } st.UploadNs = st.CopyNs if copyErr != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } if b := l.cfg.BarrierBound; b > 0 && st.BarrierCopyChunks > b { @@ -916,6 +945,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } // Upload only what changed against HEAD. + prepareStart := time.Now() next := copyHead(baseHead) next.Epoch, next.Holder, next.RemoteLSN = l.cfg.Epoch, l.cfg.Holder, h next.State, next.DetachedBy = chunkHeadActive, nil @@ -965,23 +995,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: baseHead.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) } intents = append(intents, id) } + st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() payloadStart := time.Now() if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] return l.putCaptured(ctx, u.key, u.c.data) }); err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { st.PayloadNs += time.Since(payloadStart).Nanoseconds() } + prepareStart = time.Now() for _, u := range uploads { next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key @@ -989,16 +1021,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.UploadedChunks++ st.UploadedBytes += int64(max(len(u.c.data), u.c.size)) } + st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() upgrade := false if builder, ok := l.remote.(ChunkManifestBuilder); ok { upgrade = baseHead.Segments == nil var ids []string var err error + manifestStart := time.Now() next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks) + st.ManifestNs += time.Since(manifestStart).Nanoseconds() intents = append(intents, ids...) if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } } @@ -1009,7 +1044,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch cur, err := readCapturedHead() if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) } if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) { @@ -1020,19 +1055,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } - l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS + finishCapturedCut(baseHead, h, nil, nil) // nothing new: no CAS persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) // superseded staged uploads only + dropCapturedIntents(ctx, intents) // superseded staged uploads only return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } if l.supersededBy(baseHead) { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) l.stMu.Lock() l.fenced = true l.stMu.Unlock() @@ -1051,9 +1086,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if casErr == nil { next.Gen = gen - l.finishCut(next, h, changed, newKeys) + finishCapturedCut(next, h, changed, newKeys) persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by @@ -1091,14 +1126,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if sameProposal(cur, next) { st.CASResult = "resolved-by-reread" - l.finishCut(cur, h, changed, newKeys) + finishCapturedCut(cur, h, changed, newKeys) persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } // HEAD moved past the CAS's base without it: it can never land. l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) if l.supersededBy(cur) { l.stMu.Lock() l.fenced = true diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index fdb1c142ed..e05f71c265 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -25,6 +25,14 @@ const ( // PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample. type PrecopyFixedParts struct { + Candidate time.Duration `json:"candidateNs"` + WindowSetup time.Duration `json:"windowSetupNs"` + PublishPrepare time.Duration `json:"publishPrepareNs"` + Manifest time.Duration `json:"manifestNs"` + CommitState time.Duration `json:"commitStateNs"` + IntentCleanup time.Duration `json:"intentCleanupNs"` + NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"` + Drain time.Duration `json:"drainNs"` StoreLock time.Duration `json:"storeLockNs"` DataSync time.Duration `json:"dataSyncNs"` @@ -35,8 +43,8 @@ type PrecopyFixedParts struct { } func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts { - p := PrecopyFixedParts{Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} - p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist) + p := PrecopyFixedParts{Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} + p.Other = max(time.Duration(0), fixed-p.measured()) return p } @@ -48,6 +56,8 @@ type precopySample struct { } type PrecopyAttempt struct { + BarrierParts PrecopyFixedParts `json:"barrierParts"` + BarrierOverage time.Duration `json:"barrierOverageNs"` // Attempt is the physical round ordinal, including measurement rounds. Attempt int `json:"attempt"` Drain time.Duration `json:"drainNs"` @@ -68,6 +78,13 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + // Live barrier prefix is diagnostic, not additive to the selected forecast. + BarrierParts PrecopyFixedParts `json:"barrierParts"` + BarrierOverage time.Duration `json:"barrierOverageNs"` + GuestFrozen bool `json:"guestFrozen,omitempty"` + GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs,omitempty"` + RemainingFreeze time.Duration `json:"remainingFreezeNs,omitempty"` + OverBudget bool `json:"overBudget,omitempty"` Rounds []PrecopyAttempt `json:"rounds,omitempty"` Drain time.Duration `json:"drainNs"` DrainTimedOut bool `json:"drainTimedOut"` @@ -103,7 +120,10 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo r.CASFailureTimeout = chunkHeadOperationTimeout r.DeclaredWorst = r.Estimate + time.Duration(extraCAS)*chunkHeadOperationTimeout limit := precopyAllowance - if r.Reason == "no_progress" || r.Reason == "final_attempt" { + if r.GuestFrozen { + r.DeclaredWorst = r.DeclaredFreeze + time.Duration(extraCAS)*chunkHeadOperationTimeout + limit = precopyFreezeLimit + } else if r.Reason == "no_progress" || r.Reason == "final_attempt" { limit = min(r.DeclaredFreeze, precopyFreezeLimit) } r.LatencyGateFailed = failed || elapsed > limit @@ -136,6 +156,8 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return ChunkCutResult{}, err } defer l.capMu.Unlock() + guestFreeze, externallyFrozen := FrozenDetachFromContext(ctx) + if err := ctx.Err(); err != nil { return ChunkCutResult{}, err } @@ -143,6 +165,19 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context r.Precopy.Frozen = true return r, nil } + l.stMu.Lock() + pending := l.pending != nil + l.stMu.Unlock() + if externallyFrozen && !pending { + if err := l.admit(); err != nil { + return ChunkCutResult{}, err + } + tail := l.candidateTail() + r := l.precopyEstimate(tail.Bytes, 0) + if !r.admitFrozen(guestFreeze) { + return ChunkCutResult{Precopy: r}, frozenRefusal(r) + } + } ctx, countCAS := WithChunkCASAccounting(ctx) var report PrecopyReport var frozenAt time.Time @@ -171,7 +206,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context longestPause = pause } } - l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool { + l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool { report = l.precopyEstimate(tail, report.Attempts) report.Drain = drain report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) @@ -183,8 +218,10 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return false } spent := time.Since(barrierStart) + report.BarrierParts = precopyFixedParts(current, spent) if spent > report.Fixed { extra := spent - report.Fixed + report.BarrierOverage = extra report.Estimate += extra report.FixedParts.Other += extra report.Fixed = spent @@ -196,10 +233,18 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if len(rounds) > 0 { previous = &rounds[len(rounds)-1] } - if !report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) { + admitted := false + if externallyFrozen { + admitted = report.admitFrozen(guestFreeze) + } else { + admitted = report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) + } + if !admitted { return false } - report.DeclaredFreeze = report.Estimate + if !externallyFrozen { + report.DeclaredFreeze = report.Estimate + } if !stopIO() { report.Reason = "admitted_io" return false @@ -210,7 +255,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return true } defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() - for attempt := 1; attempt <= precopyAttempts; attempt++ { + maxAttempts := precopyAttempts + if externallyFrozen { + maxAttempts = 1 + } + for attempt := 1; attempt <= maxAttempts; attempt++ { // Measurement rounds still consume the same five-round/60s budget. // Count an admission attempt only with a warm rate window at entry. if l.precopyEstimate(0, 0).RateSamples >= 3 { @@ -227,7 +276,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context r, err := l.captureLocked(ctx, false) report.SamplesAtStart, report.MeasurementRounds = samplesAtStart, measurementRounds a := PrecopyAttempt{ - Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, + Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, BarrierParts: report.BarrierParts, BarrierOverage: report.BarrierOverage, TailBytes: report.TailBytes, RateSamples: report.RateSamples, Estimate: report.Estimate, Reason: report.Reason, Frozen: report.Frozen, Fixed: report.Fixed, FixedParts: report.FixedParts, TailEstimate: report.TailEstimate, DeclaredFreeze: report.DeclaredFreeze, PreviousEstimate: report.PreviousEstimate, @@ -243,6 +292,9 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context report.Rounds = rounds report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause r.Precopy = report + if errors.Is(err, ErrFrozenTailTooLarge) { + return r, errors.Join(err, frozenRefusal(report)) + } if errors.Is(err, errChunkLayerDetached) { if previous, ok := l.storedDetach(); ok { previous.Precopy = report @@ -257,7 +309,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if attempts > 0 { extra = attempts - 1 } - r.Precopy.Finish(time.Since(frozenAt), extra, err != nil) + elapsed := time.Since(frozenAt) + if externallyFrozen { + elapsed = time.Since(guestFreeze.StartedAt) + } + r.Precopy.Finish(elapsed, extra, err != nil) return r, err } if err != nil { @@ -370,7 +426,7 @@ func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt, final bool) bool func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts { p := s.parts - p.Other = max(time.Duration(0), s.fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist) + p.Other = max(time.Duration(0), s.fixed-p.measured()) return p } @@ -426,3 +482,28 @@ func comparablePrecopyAttempt(a *PrecopyAttempt) bool { return false } } + +func (p PrecopyFixedParts) measured() time.Duration { + return p.Drain + p.StoreLock + p.DataSync + p.HeadCAS + p.HeadReadback + p.MapPersist + p.Candidate + p.WindowSetup + p.PublishPrepare + p.Manifest + p.CommitState + p.IntentCleanup + p.NonPayloadCopy +} + +// Candidate count is conservative and advisory while guest writes continue. +// The same immutable rate observation supplies both the estimate and its rate. +func (l *chunkLayerImpl) candidateTail() *ChunkCandidateTail { + candidates := l.captureCandidates() + l.stMu.Lock() + for idx := range l.dirty { + candidates[idx] = true + } + if l.allDirty { + for idx := uint64(0); idx < l.numChunks; idx++ { + if !l.absent[idx] || l.chunkHasLocalLocked(idx) { + candidates[idx] = true + } + } + } + l.stMu.Unlock() + bytes := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks + r := l.precopyEstimate(bytes, 0) + return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 2fda490f07..0db087612c 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -397,6 +397,15 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". type chunkCutStats struct { + // Disjoint non-payload intervals within barrier-to-settlement fixed cost. + CandidateNs int64 + WindowSetupNs int64 + PublishPrepareNs int64 + ManifestNs int64 + CommitStateNs int64 + IntentCleanupNs int64 + NonPayloadCopyNs int64 + PayloadNs int64 // disjoint streaming/copy/upload wall intervals // Local validated WAL attempts and local copy duration, including savers. @@ -487,13 +496,27 @@ type chunkLayerStats struct { // the current HEAD when the cut had nothing new (Noop: no CAS). // - FullHash says the cut compared every chunk by hash (no usable bitmap, // or the first cut after a BASE install). +// +// ChunkCandidateTail is advisory pending work sampled after a successful cut. +// Bytes and rate/estimate belong to one sampler observation; Known=false must +// never be interpreted as a zero-cost tail. Admission rechecks at its barrier. +type ChunkCandidateTail struct { + Bytes uint64 `json:"bytes"` + Estimate time.Duration `json:"estimateNs"` + BytesPerSecond float64 `json:"bytesPerSecond"` + RateSamples int `json:"rateSamples"` + SampleAge time.Duration `json:"sampleAgeNs"` + Known bool `json:"known"` +} + type chunkCutResult struct { - Precopy PrecopyReport - H uint64 - Head chunkHead - Noop bool - FullHash bool - Stats chunkCutStats + CandidateTail *ChunkCandidateTail + Precopy PrecopyReport + H uint64 + Head chunkHead + Noop bool + FullHash bool + Stats chunkCutStats } // chunkLayer is what the store owner drives. From 9c3cad238f747cb53aa18cd51505321638dc641a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:49:25 -0800 Subject: [PATCH 10/15] feat(cli): expose frozen detach budget options --- seaweed-block/cmd/sw-block/chunk.go | 22 ++++++++++++++++--- .../cmd/sw-block/chunk_frozen_test.go | 19 ++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_frozen_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index ec9ac529ab..80cc5f67ad 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -226,19 +226,35 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { func chunkDetach(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("detach", stderr) var ( - volumeID, statusAddr string - timeout time.Duration + volumeID, statusAddr string + timeout time.Duration + frozen, allowOverBudget bool + freezeStartedAtNs int64 ) fs.StringVar(&volumeID, "volume", "", "volume id") fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)") + fs.BoolVar(&frozen, "frozen", false, "guest is already frozen; use one cut within its remaining five-second budget") + fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "guest freeze start in Unix nanoseconds on the serving host clock") + fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "explicit final frozen attempt; record over_budget rather than refuse its estimate") if err := fs.Parse(args); err != nil { return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } if volumeID == "" || statusAddr == "" { return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) } - return chunkPost("detach", statusAddr, "/chunk/detach", timeout, map[string]any{"volumeID": volumeID}, stdout, stderr) + if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false) + } + body := map[string]any{"volumeID": volumeID} + if frozen { + body["frozen"] = true + body["freezeStartedAtNs"] = freezeStartedAtNs + if allowOverBudget { + body["allowOverBudget"] = true + } + } + return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr) } // chunkCatalog opens the catalog under --chunk-path on --chunk-filer. diff --git a/seaweed-block/cmd/sw-block/chunk_frozen_test.go b/seaweed-block/cmd/sw-block/chunk_frozen_test.go new file mode 100644 index 0000000000..f2e30173b1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_frozen_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" +) + +func TestOpsChunkFrozenDetachFlags(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1"}`) + code, _, errs := runChunk("detach", "--volume=v1", "--status-addr="+srv.URL, "--frozen", "--freeze-started-at-ns=1234567", "--allow-over-budget") + if code != 0 || len(*got) != 1 || (*got)[0].body["frozen"] != true || (*got)[0].body["freezeStartedAtNs"] != float64(1234567) || (*got)[0].body["allowOverBudget"] != true { + t.Fatalf("frozen request lost budget: %d %s %+v", code, errs, *got) + } + for _, flags := range [][]string{{"--frozen"}, {"--allow-over-budget"}, {"--freeze-started-at-ns=123"}} { + args := append([]string{"detach", "--volume=v1", "--status-addr=" + srv.URL}, flags...) + if code, _, _ := runChunk(args...); code == 0 || len(*got) != 1 { + t.Fatalf("invalid flags sent request: %v", flags) + } + } +} From 361676c6894e965326f623ef987db970d5e1848c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:50:51 -0800 Subject: [PATCH 11/15] fix(storage): make final freeze override explicit in results --- seaweed-block/core/storage/chunk_frozen_budget.go | 9 ++++----- seaweed-block/core/storage/chunk_frozen_budget_test.go | 7 +++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index 9f81e4de31..cfd8c6fc30 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -37,13 +37,12 @@ func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { r.GuestFreezeElapsed = time.Since(opts.StartedAt) r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) known := r.Reason != "samples_unknown" && r.Estimate > 0 - if !known || r.Estimate > r.RemainingFreeze { - r.Reason = "frozen_tail_too_large" - if !opts.AllowOverBudget { - return false - } + if opts.AllowOverBudget { r.Reason = "over_budget" r.OverBudget = true + } else if !known || r.Estimate > r.RemainingFreeze { + r.Reason = "frozen_tail_too_large" + return false } else { r.Reason = "fit" } diff --git a/seaweed-block/core/storage/chunk_frozen_budget_test.go b/seaweed-block/core/storage/chunk_frozen_budget_test.go index 174324318a..70153a75f7 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget_test.go +++ b/seaweed-block/core/storage/chunk_frozen_budget_test.go @@ -86,3 +86,10 @@ func TestFrozenBudgetInputValidation(t *testing.T) { } } } + +func TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits(t *testing.T) { + r := PrecopyReport{Estimate: time.Second, Reason: "fit"} + if !r.admitFrozen(FrozenDetachOptions{StartedAt: time.Now(), AllowOverBudget: true}) || !r.OverBudget || r.Reason != "over_budget" { + t.Fatalf("explicit override hidden: %+v", r) + } +} From 91a9356ea41780ccac1083002cfadac9c9c5cc4a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:48:19 -0800 Subject: [PATCH 12/15] durable: witness the stale periodic decision and the restarted interval; ledger row Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/export_chunk_test.go | 7 + .../core/frontend/durable/provider.go | 4 + .../core/frontend/durable/provider_chunk.go | 13 +- .../durable/provider_chunk_sched_test.go | 138 ++++++++++++++---- seaweed-block/docs/design/invariants.md | 3 +- 5 files changed, 132 insertions(+), 33 deletions(-) diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 7c74e579b7..93158f44c0 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -21,6 +21,13 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T p.testDetachTrace = f } +// SetTestChunkLoopTrace observes the cut loop's periodic cuts: "due" with the +// last cut it decided from, then "cut" with whether it was skipped +// (test-only; set before the volume opens). +func SetTestChunkLoopTrace(p *DurableProvider, f func(event string, lastCutNs int64, skipped bool)) { + p.testChunkLoopTrace = f +} + // SetTestBeforeIOLock runs f in the backend's admission, right before the I/O // lock (test-only). func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 5aa210bce9..c394aed3d5 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -228,6 +228,10 @@ type DurableProvider struct { // observes the detach's stages and their deadlines ("cut", "settle"). testDetachStopIO func(ctx context.Context) error testDetachTrace func(stage string, deadline time.Time) + // testChunkLoopTrace, test-only, observes the cut loop's periodic cuts: + // "due" when it decides one from lastCutNs, then "cut" with whether it + // was skipped. + testChunkLoopTrace func(event string, lastCutNs int64, skipped bool) // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. testBeforeChunkFreshRetire func() error diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index b540dcd889..7a4a2170e1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -760,16 +760,27 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer if !ok { continue } + trace := p.testChunkLoopTrace + if trace != nil { + trace("due", ls.LastCutNs, false) + } var err error if pc, ok := layer.(storage.ChunkPeriodicCutter); ok { // A cut that completed after this decision (an explicit one // running meanwhile) restarted the timer: no cut now. var skipped bool - if _, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs); skipped { + _, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs) + if trace != nil { + trace("cut", ls.LastCutNs, skipped) + } + if skipped { continue } } else { _, err = layer.Cut(ctx) + if trace != nil { + trace("cut", ls.LastCutNs, false) + } } s = pol.after(s, start, time.Now(), err) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 7171e17de6..d39d1ea1be 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -4,6 +4,7 @@ package durable_test import ( "context" + "sync" "sync/atomic" "testing" "time" @@ -164,65 +165,140 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { } } -// slowCASRemote delays the next HEAD CAS once, by the armed duration. -type slowCASRemote struct { +// gatedCASRemote holds the next HEAD CAS, once armed, until it is released +// (or its context ends), and reports when that CAS started. +type gatedCASRemote struct { *storage.MemChunkRemote - delay atomic.Int64 // ns; taken by the next CAS + armed atomic.Bool + entered chan struct{} + release chan struct{} } -func (r *slowCASRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - if d := time.Duration(r.delay.Swap(0)); d > 0 { - t := time.NewTimer(d) +func (r *gatedCASRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if r.armed.CompareAndSwap(true, false) { + close(r.entered) select { - case <-t.C: + case <-r.release: case <-ctx.Done(): - t.Stop() return 0, ctx.Err() } } return r.MemChunkRemote.CASHead(ctx, expected, next) } +type loopEvent struct { + event string + lastCutNs int64 + skipped bool + at time.Time +} + // An explicit cut still running when the loop's timer comes due restarts the -// timer all the same: the automatic cut the loop decided on meanwhile does -// not follow the explicit one; the next one comes an interval after it. +// timer all the same. Witnessed: the loop decides "due" from the old last +// cut while the explicit cut's CAS is held; once the explicit cut completes, +// that periodic cut is skipped (not taken as a no-op); and the next periodic +// decision is made from the explicit cut, a whole interval after it. func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { const interval = 3 * time.Second - remote := &slowCASRemote{MemChunkRemote: storage.NewMemChunkRemote()} + remote := &gatedCASRemote{MemChunkRemote: storage.NewMemChunkRemote(), entered: make(chan struct{}), release: make(chan struct{})} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(remote.release) }) } + t.Cleanup(release) p := schedProvider(t, remote, interval, 0) + events := make(chan loopEvent, 64) + durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) { + select { + case events <- loopEvent{event, lastCutNs, skipped, time.Now()}: + default: + } + }) + next := func(what string) loopEvent { + t.Helper() + select { + case e := <-events: + return e + case <-time.After(30 * time.Second): + t.Fatalf("timed out waiting for the loop's %s", what) + } + return loopEvent{} + } s := openRecovered(t, p) - begin := time.Now() - - time.Sleep(2 * time.Second) + begin := time.Now() // the loop started during open: its first deadline is at most begin + interval if _, err := s.Write(1, block(0x01)); err != nil { t.Fatal(err) } - // The explicit cut's CAS waits until well past the loop's first - // deadline (at most begin + interval): the loop comes due mid-cut. - remote.delay.Store(int64(1500 * time.Millisecond)) // below the CAS operation timeout - if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { - t.Fatal(err) + // Hold the explicit cut's CAS from a second before that deadline: the + // CAS's own 2 s operation deadline outlasts it. + time.Sleep(time.Until(begin.Add(interval - time.Second))) + remote.armed.Store(true) + explicitDone := make(chan error, 1) + go func() { _, err := p.CaptureVolume(context.Background(), "v1"); explicitDone <- err }() + t.Cleanup(func() { + release() + select { + case <-explicitDone: + case <-time.After(30 * time.Second): + t.Error("the explicit cut never returned") + } + explicitDone <- nil + }) + select { + case <-remote.entered: + case <-time.After(30 * time.Second): + t.Fatal("the explicit cut never reached its CAS") } - explicit := time.Now() - if !explicit.After(begin.Add(interval)) { - t.Fatalf("explicit cut ended %v after the start; want past the loop's first deadline", explicit.Sub(begin)) + // The loop comes due while the explicit cut holds its CAS: it decides + // from the old last cut (none yet). + due := next("due decision") + if due.event != "due" || due.lastCutNs != 0 { + t.Fatalf("loop event %+v; want a due decision from no cut yet", due) } + select { + case err := <-explicitDone: + explicitDone <- err + t.Fatal("the explicit cut finished before the loop's decision") + default: + } + release() + select { + case err := <-explicitDone: + explicitDone <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(30 * time.Second): + t.Fatal("the explicit cut did not finish") + } + explicitAt := 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) } - // Well inside explicit + interval: no automatic cut. - time.Sleep(time.Until(explicit.Add(interval / 2))) - if time.Now().After(explicit.Add(interval - 300*time.Millisecond)) { - t.Skip("scheduling too slow to separate the deadlines on this host") + // The stale periodic cut is skipped, not run as a no-op. + cut := next("stale periodic cut") + if cut.event != "cut" || cut.lastCutNs != 0 || !cut.skipped { + t.Fatalf("loop event %+v; want the stale periodic cut skipped", cut) } - 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) + // The next periodic decision is made from the explicit cut, a whole + // interval after it, and publishes the later write. + due2 := next("next due decision") + if due2.event != "due" || due2.lastCutNs == 0 { + t.Fatalf("loop event %+v; want a due decision from the explicit cut", due2) } - // The timer still runs: the automatic cut follows. - for headGen(t, remote).Gen < 2 { - time.Sleep(50 * time.Millisecond) + last := time.Unix(0, due2.lastCutNs) + if last.After(explicitAt) { + t.Fatalf("decided from a cut at %v, after the explicit cut returned (%v)", last, explicitAt) + } + if due2.at.Before(last.Add(interval)) { + t.Fatalf("next periodic cut decided %v after the explicit cut; want a whole %v interval", due2.at.Sub(last), interval) + } + cut2 := next("next periodic cut") + if cut2.event != "cut" || cut2.skipped { + t.Fatalf("loop event %+v; want the next periodic cut taken", cut2) + } + if h := headGen(t, remote); h.Gen != 2 { + t.Fatalf("after the next periodic cut: HEAD gen %d, want 2", h.Gen) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0133a48f39..82cfce7274 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -196,6 +196,7 @@ stateDiagram-v2 | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | +| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -341,7 +342,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 new. +118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. From 0430ff4a33fcec88c8796c33f12a380081638362 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:00:58 -0800 Subject: [PATCH 13/15] test: qualify frozen detach budget and fixed phase attribution --- .../core/frontend/durable/provider_chunk.go | 2 +- .../core/host/volume/chunk_control.go | 16 +++--- .../host/volume/chunk_control_adapter_test.go | 7 +++ .../core/storage/chunk_fixed_spans_test.go | 8 +++ .../core/storage/chunk_frozen_budget_test.go | 46 +++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 2 +- seaweed-block/core/storage/chunk_precopy.go | 18 +++--- seaweed-block/core/storage/chunk_seam.go | 9 +++ seaweed-block/core/storage/walstore.go | 35 +++++++++++- seaweed-block/docs/design/invariants.md | 12 +++- .../docs/spec/FrozenDetachBudget.tla | 56 +++++++++++++++++++ seaweed-block/docs/spec/README.md | 27 +++++++++ .../docs/spec/cfg/FrozenDetachBudget.cfg | 8 +++ .../FrozenDetachBudget_hidden_override.cfg | 8 +++ .../cfg/FrozenDetachBudget_no_authority.cfg | 8 +++ .../cfg/FrozenDetachBudget_no_barrier.cfg | 8 +++ .../cfg/FrozenDetachBudget_no_elapsed.cfg | 8 +++ .../cfg/FrozenDetachBudget_staging_upload.cfg | 8 +++ 18 files changed, 265 insertions(+), 21 deletions(-) create mode 100644 seaweed-block/docs/spec/FrozenDetachBudget.tla create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg create mode 100644 seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 8d6886a95d..a4a9c7432f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1015,7 +1015,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // Log only after capture releases its barrier; at most five records. for _, a := range r.Precopy.Rounds { p := a.FixedParts - log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_store_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond)) + log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_capture_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f live_sync_lifecycle_wait_ms=%.3f live_sync_store_wait_ms=%.3f live_sync_group_commit_ms=%.3f live_sync_completion_wait_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.LifecycleWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.StoreWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.GroupCommitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.CompletionWaitNs)/float64(time.Millisecond)) log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f map_persist_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.MapPersist)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), a.Error) } log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 1321668cba..c3ad60dd8b 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -57,13 +57,14 @@ type ChunkCutResponse struct { // mirrors storage.ChunkCutStats field for field (a test keeps the two in // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { - CandidateNs int64 `json:"candidateNs"` - WindowSetupNs int64 `json:"windowSetupNs"` - PublishPrepareNs int64 `json:"publishPrepareNs"` - ManifestNs int64 `json:"manifestNs"` - CommitStateNs int64 `json:"commitStateNs"` - IntentCleanupNs int64 `json:"intentCleanupNs"` - NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` + SyncPhases storage.SyncPhaseStats `json:"syncPhases"` + CandidateNs int64 `json:"candidateNs"` + WindowSetupNs int64 `json:"windowSetupNs"` + PublishPrepareNs int64 `json:"publishPrepareNs"` + ManifestNs int64 `json:"manifestNs"` + CommitStateNs int64 `json:"commitStateNs"` + IntentCleanupNs int64 `json:"intentCleanupNs"` + NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` PayloadNs int64 `json:"payloadNs"` COWWALReadAttempts uint64 `json:"cowWALReadAttempts"` @@ -97,6 +98,7 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ + SyncPhases: s.SyncPhases, CandidateNs: s.CandidateNs, WindowSetupNs: s.WindowSetupNs, PublishPrepareNs: s.PublishPrepareNs, diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 2f26ba2509..51f9a57876 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -182,6 +182,13 @@ func TestChunkCutStatsBody_MirrorsTheLayerStats(t *testing.T) { f.SetString("s") case reflect.Bool: f.SetBool(true) + case reflect.Struct: + for j := 0; j < f.NumField(); j++ { + if f.Field(j).Kind() != reflect.Int64 { + t.Fatalf("nested field %s.%s is not a duration counter", v.Type().Field(i).Name, f.Type().Field(j).Name) + } + f.Field(j).SetInt(int64(100*(i+1) + j + 1)) + } default: t.Fatalf("field %s: unhandled kind %s", v.Type().Field(i).Name, f.Kind()) } diff --git a/seaweed-block/core/storage/chunk_fixed_spans_test.go b/seaweed-block/core/storage/chunk_fixed_spans_test.go index 4d19b7011e..bde57521e0 100644 --- a/seaweed-block/core/storage/chunk_fixed_spans_test.go +++ b/seaweed-block/core/storage/chunk_fixed_spans_test.go @@ -66,3 +66,11 @@ func TestPrecopyLiveBarrierSpansExplainOverage(t *testing.T) { t.Fatalf("live lock overage hidden as retained other: %+v", r.Precopy) } } + +func TestPrecopyFixedPartsDoNotDoubleCountSyncPhases(t *testing.T) { + st := chunkCutStats{SyncNs: int64(100 * time.Millisecond), SyncPhases: SyncPhaseStats{StoreWaitNs: int64(30 * time.Millisecond), GroupCommitNs: int64(70 * time.Millisecond)}} + p := precopyFixedParts(st, 150*time.Millisecond) + if p.DataSync != 100*time.Millisecond || p.Other != 50*time.Millisecond || p.SyncPhases != st.SyncPhases { + t.Fatalf("nested Sync cost counted twice or dropped: %+v", p) + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget_test.go b/seaweed-block/core/storage/chunk_frozen_budget_test.go index 70153a75f7..63497096c4 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget_test.go +++ b/seaweed-block/core/storage/chunk_frozen_budget_test.go @@ -93,3 +93,49 @@ func TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits(t *testing.T) { t.Fatalf("explicit override hidden: %+v", r) } } + +func TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards(t *testing.T) { + for _, closed := range []bool{false, true} { + t.Run(map[bool]string{false: "fenced", true: "closed"}[closed], func(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x4a) + before := f.stats() + want := ErrChunkLayerFenced + if closed { + if err := l.Close(); err != nil { + t.Fatal(err) + } + want = ErrChunkLayerClosed + } else { + l.cfg.CaptureAllowed = func() error { return ErrChunkLayerFenced } + } + _, err := l.PrecopyDetach(frozenContext(t, time.Minute, true), func() bool { t.Fatal("override bypassed gate"); return true }) + after := f.stats() + if !errors.Is(err, want) || after.puts != before.puts || after.cas != before.cas { + t.Fatalf("override bypassed %v: %v", want, err) + } + }) + } +} +func TestFrozenRetryDoesNotHideUnknownPublication(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x5b) + seedFrozenSamples(l, time.Millisecond) + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } + r, err := l.PrecopyDetach(frozenContext(t, 0, true), func() bool { return true }) + if !r.Precopy.Frozen || !errors.Is(err, ErrChunkCASOutcomeUnknown) { + t.Fatalf("missing unknown publication: %+v %v", r.Precopy, err) + } + before := f.stats() + _, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("unknown retry stopped again"); return true }) + if !errors.Is(err, ErrChunkCASOutcomeUnknown) || errors.Is(err, ErrFrozenTailTooLarge) || f.stats().puts != before.puts { + t.Fatalf("budget hid uncertainty: %v", err) + } + f.failGet = nil + r, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("applied retry stopped again"); return true }) + if err != nil || r.Head.Gen != before.head.Gen || r.Head.State != ChunkHeadDetached { + t.Fatalf("applied same-point result budget-refused: %+v %v", r, err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 93f9a20545..6450f2c277 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -810,7 +810,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.s.captureMu.Lock() barrier := time.Now() st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds() - h, err := l.s.Sync() + h, err := l.s.syncWithPhases(&st.SyncPhases) st.SyncNs = time.Since(barrier).Nanoseconds() if hook := l.testAfterBarrierSyncHook; hook != nil && err == nil { hook(h) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index e05f71c265..da53e10fa3 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -25,13 +25,15 @@ const ( // PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample. type PrecopyFixedParts struct { - Candidate time.Duration `json:"candidateNs"` - WindowSetup time.Duration `json:"windowSetupNs"` - PublishPrepare time.Duration `json:"publishPrepareNs"` - Manifest time.Duration `json:"manifestNs"` - CommitState time.Duration `json:"commitStateNs"` - IntentCleanup time.Duration `json:"intentCleanupNs"` - NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"` + // Nested DataSync details, excluded from the additive measured sum. + SyncPhases SyncPhaseStats `json:"syncPhases"` + Candidate time.Duration `json:"candidateNs"` + WindowSetup time.Duration `json:"windowSetupNs"` + PublishPrepare time.Duration `json:"publishPrepareNs"` + Manifest time.Duration `json:"manifestNs"` + CommitState time.Duration `json:"commitStateNs"` + IntentCleanup time.Duration `json:"intentCleanupNs"` + NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"` Drain time.Duration `json:"drainNs"` StoreLock time.Duration `json:"storeLockNs"` @@ -43,7 +45,7 @@ type PrecopyFixedParts struct { } func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts { - p := PrecopyFixedParts{Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} + p := PrecopyFixedParts{SyncPhases: st.SyncPhases, Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} p.Other = max(time.Duration(0), fixed-p.measured()) return p } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 0db087612c..ca42de1f14 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -396,7 +396,16 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". +// SyncPhaseStats are nested details of SyncNs; never add them to SyncNs. +type SyncPhaseStats struct { + LifecycleWaitNs int64 `json:"lifecycleWaitNs"` + StoreWaitNs int64 `json:"storeWaitNs"` + GroupCommitNs int64 `json:"groupCommitNs"` + CompletionWaitNs int64 `json:"completionWaitNs"` +} + type chunkCutStats struct { + SyncPhases SyncPhaseStats // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 3898345e91..250a6bfa45 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -752,10 +752,25 @@ func (s *WALStore) readExtentBlock(lba uint32) ([]byte, error) { // becomes crash-survivable only when a Sync that covers its LSN // returns nil. Group commit batches concurrent Sync callers into one // fsync. -func (s *WALStore) Sync() (uint64, error) { +func (s *WALStore) Sync() (uint64, error) { return s.syncWithPhases(nil) } + +// Optional capture telemetry leaves the ordinary Sync contract and lock order +// unchanged. Only the requesting goroutine updates these nested phase costs. +func (s *WALStore) syncWithPhases(phases *SyncPhaseStats) (uint64, error) { + var at time.Time + if phases != nil { + at = time.Now() + } s.lifecycleMu.RLock() + if phases != nil { + phases.LifecycleWaitNs += time.Since(at).Nanoseconds() + at = time.Now() + } defer s.lifecycleMu.RUnlock() s.mu.RLock() + if phases != nil { + phases.StoreWaitNs += time.Since(at).Nanoseconds() + } if s.closed { s.mu.RUnlock() return 0, errors.New("storage: Sync after Close") @@ -778,6 +793,9 @@ func (s *WALStore) Sync() (uint64, error) { s.mu.RUnlock() + if phases != nil { + at = time.Now() + } if s.walSyncCovered() { // Preserve shutdown refusal even when no file I/O is necessary. select { @@ -788,6 +806,9 @@ func (s *WALStore) Sync() (uint64, error) { } else if err := s.syncCache(); err != nil { return 0, fmt.Errorf("storage: group commit fsync: %w", err) } + if phases != nil { + phases.GroupCommitNs += time.Since(at).Nanoseconds() + } s.syncs.Add(1) { @@ -797,7 +818,13 @@ func (s *WALStore) Sync() (uint64, error) { } // The completion is validated against the recovery generation under // the leader role: a recovery since the capture refuses the ack. + if phases != nil { + at = time.Now() + } v.syncMu.Lock() + if phases != nil { + phases.CompletionWaitNs += time.Since(at).Nanoseconds() + } defer v.syncMu.Unlock() if v.recoverGen.Load() != targetGen { return 0, errV3RecoveredMeanwhile @@ -807,7 +834,13 @@ func (s *WALStore) Sync() (uint64, error) { } } + if phases != nil { + at = time.Now() + } s.mu.Lock() + if phases != nil { + phases.StoreWaitNs += time.Since(at).Nanoseconds() + } // A fault latched while this Sync waited (another caller's fsync or // append, or a flusher fsync) refuses it: nothing is acknowledged. if err := s.stickyIOFault(); err != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9749f085ec..0bbe234b83 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -208,9 +208,13 @@ stateDiagram-v2 Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid Admit --> PlainStop: plain detach and idle frontend lock acquired PlainStop --> Quiesce: frontend stopped; ordinary detached cut - Admit --> Stage: budget admitted, earlier unknown CAS settled + Admit --> FrozenForecast: guest already frozen with an explicit origin + FrozenForecast --> Refused: unknown or non-fitting remaining budget + FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging + Admit --> Stage: ordinary cut; budget admitted, earlier unknown CAS settled Stage --> Quiesce: spill-budget remainder reached or no shrink - Quiesce --> FinalFreeze: opt-in measured tail fits after bounded admission drain + Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload + Quiesce --> FinalFreeze: measured admission or explicit frozen final override FinalFreeze --> OpenWindow: admission stays closed through detached settlement Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier OpenWindow --> Copy: release barrier @@ -241,6 +245,8 @@ stateDiagram-v2 | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | +| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001` | +| Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | @@ -481,7 +487,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Unknown samples never admit. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | diff --git a/seaweed-block/docs/spec/FrozenDetachBudget.tla b/seaweed-block/docs/spec/FrozenDetachBudget.tla new file mode 100644 index 0000000000..e8f83cb8ee --- /dev/null +++ b/seaweed-block/docs/spec/FrozenDetachBudget.tla @@ -0,0 +1,56 @@ +------------------------ MODULE FrozenDetachBudget ------------------------ +\* One externally frozen attempt; physical latency and orchestrator retries +\* are outside this model. Authority is stable during the modeled attempt; +\* mid-cut authority/CAS races remain CutCOW2/publication proof obligations. +EXTENDS Integers, TLC +CONSTANTS OmitElapsed, OmitBarrierGuard, OmitStageGuard, + OmitOverrideRecord, OmitAuthority +Limit == 50 +VARIABLES phase, elapsed, estimate, known, force, authority, admitted, + uploaded, published, overBudget, atElapsed, atEstimate, atKnown +vars == <> +Init == /\ phase = "forecast" /\ elapsed \in {0,30,60} + /\ estimate \in {5,30,60} /\ known \in BOOLEAN + /\ force \in BOOLEAN /\ authority \in BOOLEAN + /\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE + /\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0 + /\ atKnown = FALSE +AuthorityOK == authority \/ OmitAuthority +Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit +Eligible == AuthorityOK /\ (force \/ Fits) +Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage" + /\ UNCHANGED <> +RefuseForecast == /\ phase = "forecast" /\ ~Eligible /\ phase' = "refused" + /\ UNCHANGED <> +Barrier == /\ phase = "stage" /\ phase' = "barrier" + /\ elapsed' \in {elapsed,elapsed+20} + /\ estimate' \in {estimate,estimate+30} /\ known' \in BOOLEAN + /\ uploaded' = (uploaded \/ OmitStageGuard) + /\ UNCHANGED <> +Admit == /\ phase = "barrier" /\ (Eligible \/ (OmitBarrierGuard /\ AuthorityOK)) + /\ phase' = "admitted" /\ admitted' = TRUE + /\ atElapsed' = elapsed /\ atEstimate' = estimate /\ atKnown' = known + /\ overBudget' = (force /\ ~OmitOverrideRecord) + /\ UNCHANGED <> +RefuseBarrier == /\ phase = "barrier" /\ ~Eligible /\ ~OmitBarrierGuard + /\ phase' = "refused" + /\ UNCHANGED <> +Upload == /\ phase = "admitted" /\ phase' = "uploaded" /\ uploaded' = TRUE + /\ UNCHANGED <> +Publish == /\ phase = "uploaded" /\ AuthorityOK /\ phase' = "done" + /\ published' = TRUE + /\ UNCHANGED <> +Done == /\ phase \in {"done","refused"} /\ UNCHANGED vars +Next == Forecast \/ RefuseForecast \/ Barrier \/ Admit \/ RefuseBarrier \/ Upload \/ Publish \/ Done +Spec == Init /\ [][Next]_vars +NoUploadBeforeAdmission == uploaded => admitted +BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit +OverrideVisible == admitted /\ force => overBudget +AuthorityAtPublication == published => authority +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0e2834003b..0fb0a0bd28 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -381,3 +381,30 @@ From `docs/spec`, SANY `PlainDetach.tla` exited 0; TLC with `cfg/PlainDetach_no_idle.cfg` exited 12: `IdleAtStop` fails on BeginIO -> Plain (7 generated / 5 distinct, depth 3). The negative uses a distinct `-metadir` to avoid timestamp-directory collisions between short runs. + + +## Guest-frozen detach admission + +`FrozenDetachBudget.tla` models one externally frozen attempt: a forecast, +skipped staging, changed time/estimate/knowledge at the barrier, explicit +admission, upload and publication. Time units are tenths of a second. It checks +`NoUploadBeforeAdmission`, `BudgetAtAdmission`, `OverrideVisible` and +`AuthorityAtPublication`. Authority is stable within this finite model; mid-cut +fencing and CAS races remain covered by the publication/COW contracts. It does +not prove physical latency or the external controller's two-re-freeze limit. + +Local run 2026-11-21 02:53 UTC, TLC2.19, tools SHA-256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: + +```sh +java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/FrozenDetachBudget.cfg FrozenDetachBudget +``` + +Positive exited0:667 generated/439 distinct states, queue empty, complete depth6. +The same command with each negative config exited12 at its intended invariant: +`no_elapsed`410/267 depth4; `no_barrier`386/237 depth4; +`staging_upload`151/145 depth3; `hidden_override`367/229 depth4; +`no_authority`951/603 depth6. The first two violate `BudgetAtAdmission`, the +third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last +`AuthorityAtPublication`. Source tests separately check time/metadata handling, +no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch. diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg new file mode 100644 index 0000000000..7992b80dde --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg new file mode 100644 index 0000000000..39d18fdaf3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = TRUE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg new file mode 100644 index 0000000000..0efc975f94 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = TRUE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg new file mode 100644 index 0000000000..668dc2795c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = TRUE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg new file mode 100644 index 0000000000..1c570f2a9c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = TRUE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg new file mode 100644 index 0000000000..61689d8b61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = TRUE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication From efc01c045f2914d4a93fad8f7cbd0ea8eef7a991 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:01:16 -0800 Subject: [PATCH 14/15] durable: timer test cleanup consumes once; ledger row in Part B Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_chunk_sched_test.go | 1 - seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index d39d1ea1be..795a399f9b 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -240,7 +240,6 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { case <-time.After(30 * time.Second): t.Error("the explicit cut never returned") } - explicitDone <- nil }) select { case <-remote.entered: diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 82cfce7274..a5d04f630b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -196,7 +196,6 @@ stateDiagram-v2 | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | -| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -501,6 +500,7 @@ Notes: | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. From 5fb50607d914bb30ddaa7f19e27b1abcb1e81974 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:14:52 -0800 Subject: [PATCH 15/15] fix: retain freeze reports and account for tail scan work --- .../core/frontend/durable/provider_chunk.go | 8 ++++- .../durable/provider_frozen_budget_test.go | 10 ++++++ .../core/storage/chunk_candidate_tail_test.go | 14 ++++++++ .../core/storage/chunk_fixed_spans_test.go | 20 +++++++++++ .../core/storage/chunk_frozen_budget.go | 34 ++++++++++++++++++- .../core/storage/chunk_frozen_budget_test.go | 32 ++++++++++++++++- seaweed-block/core/storage/chunk_layer.go | 10 +++++- seaweed-block/core/storage/chunk_precopy.go | 29 ++++++++++++---- seaweed-block/docs/design/invariants.md | 2 +- 9 files changed, 148 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a4a9c7432f..c96a1d64e8 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1020,12 +1020,15 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { - if !start.IsZero() { + if !start.IsZero() && !r.Precopy.IsReplay() { elapsed := time.Since(start) if !guestFrozen { elapsed += r.Precopy.BarrierBeforeFreeze } r.Precopy.Finish(elapsed, 0, false) + if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok { + recorder.RememberDetachReport(r.Precopy) + } } return r, h.storage.NextLSN() - 1, nil } @@ -1095,6 +1098,9 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla r.Precopy.Finish(elapsed, extra, true) log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr) dr.Precopy = r.Precopy + if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok { + recorder.RememberDetachReport(r.Precopy) + } } switch { case serr != nil: diff --git a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go index a721c9a3aa..2f9e9ef024 100644 --- a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go +++ b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go @@ -1,7 +1,9 @@ package durable_test import ( + "bytes" "context" + "encoding/json" "errors" "github.com/seaweedfs/seaweed-block/core/storage" "sync/atomic" @@ -44,6 +46,14 @@ func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) if err != nil || !r.Precopy.GuestFrozen || !r.Precopy.OverBudget || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 1 || r.Precopy.FreezeElapsed < time.Minute || r.Precopy.DeclaredWorst < time.Minute || !r.Precopy.LatencyGateFailed { t.Fatalf("explicit final failed/underreported total freeze: %+v %v", r, err) } + original, _ := json.Marshal(r.Precopy) + originalHead := r.Head.Gen + puts = remote.puts.Load() + replay, _, replayErr := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now()}) + replayJSON, _ := json.Marshal(replay.Precopy) + if replayErr != nil || replay.Head.Gen != originalHead || !bytes.Equal(original, replayJSON) || remote.puts.Load() != puts { + t.Fatalf("provider replay changed original freeze report or re-uploaded: original=%s replay=%s err=%v", original, replayJSON, replayErr) + } if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 { t.Fatal("final detached point lost writes") } diff --git a/seaweed-block/core/storage/chunk_candidate_tail_test.go b/seaweed-block/core/storage/chunk_candidate_tail_test.go index 4bdd9648ff..1e467e429e 100644 --- a/seaweed-block/core/storage/chunk_candidate_tail_test.go +++ b/seaweed-block/core/storage/chunk_candidate_tail_test.go @@ -45,3 +45,17 @@ func TestCheckpointTailUnknownRateIsNotZeroCost(t *testing.T) { t.Fatalf("partial rate window misreported ready: %+v", tail) } } + +func TestCheckpointTailUsesLiteralLatestThreeConservativeRate(t *testing.T) { + s, _, l, w := precopyLayer(t, 1024, 0) + w.write(t, s, 1, 0x51) + // Old slow rate must be excluded; latest three min is 2 chunks/s, + // conservative divisor is 2 => exactly one chunk/s and one second. + for _, multiplier := range []float64{0.25, 2, 6, 4} { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: multiplier * float64(ctChunkBytes)}) + } + tail := l.candidateTail() + if tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond != float64(ctChunkBytes) || tail.Estimate != time.Second || tail.RateSamples != 4 { + t.Fatalf("literal latest-three rate/estimate mismatch: %+v", tail) + } +} diff --git a/seaweed-block/core/storage/chunk_fixed_spans_test.go b/seaweed-block/core/storage/chunk_fixed_spans_test.go index bde57521e0..1576aae80c 100644 --- a/seaweed-block/core/storage/chunk_fixed_spans_test.go +++ b/seaweed-block/core/storage/chunk_fixed_spans_test.go @@ -74,3 +74,23 @@ func TestPrecopyFixedPartsDoNotDoubleCountSyncPhases(t *testing.T) { t.Fatalf("nested Sync cost counted twice or dropped: %+v", p) } } + +func TestCheckpointTailScanIncludedInTotalAndFixedCosts(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: time.Millisecond} + w.write(t, s, 1, 0x6a) + delay := 20 * time.Millisecond + scans := 0 + l.testBeforeTailScanHook = func() { scans++; time.Sleep(delay) } + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if scans != 1 || result.Stats.CandidateNs < int64(delay) || result.Stats.TotalNs < int64(delay) { + t.Fatalf("scan missing from returned costs: scans=%d stats=%+v", scans, result.Stats) + } + sample := l.precopySamples[len(l.precopySamples)-1] + if sample.fixed < delay || sample.parts.Candidate < delay { + t.Fatalf("scan omitted from fixed observation: %+v", sample) + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index cfd8c6fc30..4f6ce4090e 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -33,8 +33,11 @@ func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { return v, ok } func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { + return r.admitFrozenAt(opts, time.Now()) +} +func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { r.GuestFrozen = true - r.GuestFreezeElapsed = time.Since(opts.StartedAt) + r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) known := r.Reason != "samples_unknown" && r.Estimate > 0 if opts.AllowOverBudget { @@ -55,3 +58,32 @@ func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { func frozenRefusal(r PrecopyReport) error { return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) } + +// IsReplay distinguishes a replayed applied point from a newly completed freeze. +// The original report remains unchanged on the wire. +func (r PrecopyReport) IsReplay() bool { return r.replayed } + +func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { + now := time.Now() + if hook := l.testFrozenNow; hook != nil { + now = hook() + } + return r.admitFrozenAt(opts, now) +} + +// RememberDetachReport completes the telemetry kept with an applied or still +// pending point. The durable provider calls it after its final settlement spans. +// It changes no publication identity or authority state. +func (l *chunkLayerImpl) RememberDetachReport(report PrecopyReport) { + if report.IsReplay() { + return + } + l.stMu.Lock() + defer l.stMu.Unlock() + if l.detached != nil { + l.detached.Precopy = report + } + if l.pendingDetach { + l.pendingCut.Precopy = report + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget_test.go b/seaweed-block/core/storage/chunk_frozen_budget_test.go index 63497096c4..d9313d872a 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget_test.go +++ b/seaweed-block/core/storage/chunk_frozen_budget_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "reflect" "testing" "time" ) @@ -75,7 +76,9 @@ func TestFrozenDetachForcedFinalCommitsSamePoint(t *testing.T) { } assertEveryHeadIsPrefixImage(t, f, w) r2, err := l.PrecopyDetach(frozenContext(t, 7*time.Second, false), func() bool { t.Fatal("applied retry stopped again"); return true }) - if err != nil || r2.Head.Gen != r.Head.Gen { + want := r.Precopy + want.replayed = true + if err != nil || r2.Head.Gen != r.Head.Gen || !reflect.DeepEqual(r2.Precopy, want) { t.Fatalf("applied retry budget-refused: %+v %v", r2, err) } } @@ -139,3 +142,30 @@ func TestFrozenRetryDoesNotHideUnknownPublication(t *testing.T) { } assertEveryHeadIsPrefixImage(t, f, w) } + +func TestFrozenBarrierConsumesElapsedWithoutNewAllowance(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x61) + seedFrozenSamples(l, 1300*time.Millisecond) + origin := time.Now() + now := origin + l.testFrozenNow = func() time.Time { return now } + reached := false + l.testBeforeBarrierLockHook = func() { reached = true; now = origin.Add(4 * time.Second) } + before := f.stats() + ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: origin}) + if err != nil { + t.Fatal(err) + } + stops := 0 + result, err := l.PrecopyDetach(ctx, func() bool { stops++; return true }) + after := f.stats() + if !reached || stops != 0 || !errors.Is(err, ErrFrozenTailTooLarge) || result.Precopy.Estimate >= 5*time.Second || result.Precopy.RemainingFreeze > 1100*time.Millisecond || result.Precopy.Estimate <= result.Precopy.RemainingFreeze || after.puts != before.puts || after.cas != before.cas { + t.Fatalf("elapsed barrier budget not enforced without upload: %+v %v", result.Precopy, err) + } + l.testBeforeBarrierLockHook = nil + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6450f2c277..dc8beddfa9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -133,6 +133,8 @@ type chunkLayerImpl struct { testCOWSave func() error testPresenceSnapshotHook func() // after a presence snapshot, before it is written testBaseTransitionBeforeLock func() // test handshake before capMu drain + testBeforeTailScanHook func() // diagnostic tail scan cost witness + testFrozenNow func() time.Time // controlled guest elapsed at admission testAfterAdmitHook func() // right after a capture is admitted testAfterStageHook func(round int) // after each pre-copy staging round testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept @@ -682,6 +684,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch var pauseStart time.Time var payloadBeforeBarrier int64 defer func() { + var tailBytes uint64 + if err == nil { + scanStart := time.Now() + tailBytes = l.candidateTailBytes() + st.CandidateNs += time.Since(scanStart).Nanoseconds() + } st.TotalNs = time.Since(start).Nanoseconds() if err == nil { res.Stats = st @@ -689,7 +697,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier l.samplePrecopy(st, fixed) } - res.CandidateTail = l.candidateTail() + res.CandidateTail = l.estimateCandidateTail(tailBytes) } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index da53e10fa3..da22b9a1a9 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -80,6 +80,8 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + replayed bool // transport-local marker; never replaces the original freeze telemetry. + // Live barrier prefix is diagnostic, not additive to the selected forecast. BarrierParts PrecopyFixedParts `json:"barrierParts"` BarrierOverage time.Duration `json:"barrierOverageNs"` @@ -148,7 +150,7 @@ func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare return l.precopyDetach(ctx, prepare, stopIO) } -func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { +func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (result ChunkCutResult, resultErr error) { if stopIO == nil { return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) } @@ -158,6 +160,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return ChunkCutResult{}, err } defer l.capMu.Unlock() + defer func() { + if result.Precopy.Frozen && !result.Precopy.IsReplay() { + l.RememberDetachReport(result.Precopy) + } + }() guestFreeze, externallyFrozen := FrozenDetachFromContext(ctx) if err := ctx.Err(); err != nil { @@ -165,6 +172,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } if r, ok := l.storedDetach(); ok { r.Precopy.Frozen = true + r.Precopy.replayed = true return r, nil } l.stMu.Lock() @@ -176,7 +184,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } tail := l.candidateTail() r := l.precopyEstimate(tail.Bytes, 0) - if !r.admitFrozen(guestFreeze) { + if !l.admitFrozen(&r, guestFreeze) { return ChunkCutResult{Precopy: r}, frozenRefusal(r) } } @@ -237,7 +245,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } admitted := false if externallyFrozen { - admitted = report.admitFrozen(guestFreeze) + admitted = l.admitFrozen(&report, guestFreeze) } else { admitted = report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) } @@ -299,9 +307,8 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } if errors.Is(err, errChunkLayerDetached) { if previous, ok := l.storedDetach(); ok { - previous.Precopy = report previous.Precopy.Frozen = true - previous.Precopy.Reason = "previous_detach_applied" + previous.Precopy.replayed = true return previous, nil } } @@ -492,6 +499,13 @@ func (p PrecopyFixedParts) measured() time.Duration { // Candidate count is conservative and advisory while guest writes continue. // The same immutable rate observation supplies both the estimate and its rate. func (l *chunkLayerImpl) candidateTail() *ChunkCandidateTail { + return l.estimateCandidateTail(l.candidateTailBytes()) +} + +func (l *chunkLayerImpl) candidateTailBytes() uint64 { + if hook := l.testBeforeTailScanHook; hook != nil { + hook() + } candidates := l.captureCandidates() l.stMu.Lock() for idx := range l.dirty { @@ -505,7 +519,10 @@ func (l *chunkLayerImpl) candidateTail() *ChunkCandidateTail { } } l.stMu.Unlock() - bytes := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks + return uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks +} + +func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail { r := l.precopyEstimate(bytes, 0) return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0bbe234b83..ca99e35d51 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -487,7 +487,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |