durable, volume: one owned drain, one handle lookup, one JSON object per request

- StopIO keeps one pending drain per backend; every StopIO waits on it,
  so timed-out detach retries behind a held I/O no longer each leave a
  goroutine waiting for the admission lock.
- CutVolume resolves the volume's handle and layer in one critical section
  (chunkHandle) and keeps that handle: a Close that empties the volume map
  mid-call no longer leaves the minLSN check reading a missing handle.
- A /chunk/* request body must be exactly one JSON object: trailing data
  is bad_request before any operation runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 05:34:42 -08:00
1 parent 410efb6d03
commit f94b20724b
7 files changed
+173 -23

No files matched your search

@@ -0,0 +1,5 @@
package durable
// SetTestAfterChunkResolve installs the test-only hook CutVolume runs right
// after it resolves the volume's handle and layer.
func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f }
@@ -153,6 +153,10 @@ type DurableProvider struct {
opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create
closed bool
// testAfterChunkResolve, test-only, runs in CutVolume right after the
// volume's handle and layer are resolved.
testAfterChunkResolve func()
// walstore-chunk: closeCtx ends with Close and cancels in-flight
// remote attachment; inflight counts RecoverVolume calls admitted
// before Close, which Close waits for before closing any store.
@@ -416,22 +416,31 @@ func (p *DurableProvider) stopChunkLoop(h *volHandle) {
}
func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) {
_, layer, err := p.chunkHandle(volumeID)
return layer, err
}
// chunkHandle resolves volumeID's handle and its attached layer in one
// critical section; the caller keeps using that handle even if Close
// removes it from the map afterwards.
func (p *DurableProvider) chunkHandle(volumeID string) (*volHandle, storage.ChunkLayer, error) {
p.mu.Lock()
h, ok := p.volumes[volumeID]
var layer storage.ChunkLayer
awaiting := false
if ok {
layer, awaiting = h.chunk, h.waitGen != 0
}
p.mu.Unlock()
if !ok {
return nil, ErrVolumeNotOpen
switch {
case !ok:
return nil, nil, ErrVolumeNotOpen
case layer == nil && awaiting:
return nil, nil, ErrChunkAwaitingAuthority
case layer == nil:
return nil, nil, ErrNotChunkVolume
}
p.mu.Lock()
layer, awaiting := h.chunk, h.waitGen != 0
p.mu.Unlock()
if layer == nil && awaiting {
return nil, ErrChunkAwaitingAuthority
}
if layer == nil {
return nil, ErrNotChunkVolume
}
return layer, nil
return h, layer, nil
}
// CaptureVolume takes one quiesced cut of volumeID and publishes it to the
@@ -460,14 +469,14 @@ func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID
// MakeRemoteDurable(minLSN) returning the cut: an LSN never written is
// refused before anything is published, and the cut must reach minLSN.
func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) {
layer, err := p.chunkLayer(volumeID)
h, layer, err := p.chunkHandle(volumeID)
if err != nil {
return storage.ChunkCutResult{}, err
}
if hook := p.testAfterChunkResolve; hook != nil {
hook()
}
if minLSN > 0 {
p.mu.Lock()
h := p.volumes[volumeID]
p.mu.Unlock()
if last := h.storage.NextLSN() - 1; minLSN > last {
return storage.ChunkCutResult{}, fmt.Errorf("durable: cut of %s to LSN %d: that LSN was never written (last %d)", volumeID, minLSN, last)
}
@@ -0,0 +1,80 @@
package durable_test
// Bounds of the chunk control surface (second review of #115): timed-out
// detach retries share one drain instead of each leaving a waiter behind,
// and a cut whose volume is closed right after it was resolved fails
// cleanly instead of reading a handle Close removed.
import (
"context"
"errors"
"runtime"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestWALStoreChunk_TimedOutDetachRetriesShareOneDrain(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
p, view := parkedProvider(t, remote)
openRecovered(t, p)
b, err := p.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
view.arm()
t.Cleanup(view.unpark)
werr := make(chan error, 1)
go func() { _, err := b.Write(ctx, 4096, block(4)); werr <- err }()
<-view.entered // an admitted write holds the drain
timedOut := func() {
t.Helper()
dctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
defer cancel()
if _, _, err := p.DetachVolume(dctx, "v1"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("detach behind a held write: %v; want the context's deadline", err)
}
}
timedOut()
base := runtime.NumGoroutine()
for i := 0; i < 20; i++ {
timedOut()
}
if n := runtime.NumGoroutine() - base; n > 3 {
t.Fatalf("20 timed-out detach retries left %d more goroutines; want them to share one drain", n)
}
view.unpark()
acked := <-werr == nil
r, _, err := p.DetachVolume(ctx, "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached {
t.Fatalf("detach once the write finished: %+v %v", r, err)
}
if acked && !bytesEqual(headBlock(t, remote, 1), block(4)) {
t.Fatal("the held write was acknowledged but is not in the detached HEAD")
}
}
func TestWALStoreChunk_CutVolumeSurvivesCloseAfterResolve(t *testing.T) {
p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), 0)
s := openRecovered(t, p)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
durable.SetTestAfterChunkResolve(p, func() { _ = p.Close() })
var err error
func() {
defer func() {
if r := recover(); r != nil {
t.Fatalf("CutVolume panicked after Close removed the volume it had resolved: %v", r)
}
}()
_, err = p.CutVolume(context.Background(), "v1", 1)
}()
if err == nil {
t.Fatal("a cut of a volume closed during the call succeeded")
}
}
@@ -156,6 +156,11 @@ type StorageBackend struct {
// admit checks the gate once before the read lock too, so I/O arriving
// while a drain waits fails at once instead of queueing behind it.
ioMu sync.RWMutex
// drain, under drainMu, is closed once the pending StopIO drain has
// taken and released ioMu; nil when none is pending. Every StopIO
// waits on the same drain, so timed-out retries never pile up waiters.
drainMu sync.Mutex
drain chan struct{}
mu sync.Mutex
closed bool
@@ -364,15 +369,25 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
// ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted
// before the stop to finish. After a nil return no I/O admitted before the
// stop is still running, so nothing can be acknowledged after a cut taken
// next. On a ctx error I/O stays refused and admitted I/O may still run.
// next. On a ctx error I/O stays refused and admitted I/O may still run;
// a later StopIO waits on the same pending drain.
func (b *StorageBackend) StopIO(ctx context.Context, evidence string) error {
b.SetOperational(false, evidence)
drained := make(chan struct{})
go func() {
b.ioMu.Lock()
b.ioMu.Unlock() //nolint:staticcheck // an empty critical section: waiting is the point
close(drained)
}()
b.drainMu.Lock()
drained := b.drain
if drained == nil {
drained = make(chan struct{})
b.drain = drained
go func() {
b.ioMu.Lock()
b.ioMu.Unlock() //nolint:staticcheck // an empty critical section: waiting is the point
b.drainMu.Lock()
b.drain = nil
b.drainMu.Unlock()
close(drained)
}()
}
b.drainMu.Unlock()
select {
case <-drained:
return nil
@@ -12,6 +12,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"time"
@@ -271,6 +272,11 @@ func decodeChunkBody(w http.ResponseWriter, r *http.Request, v any) bool {
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "decode %s request: %v", r.URL.Path, err)
return false
}
// Exactly one JSON value: trailing data refuses the whole request.
if err := dec.Decode(&struct{}{}); err != io.EOF {
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "decode %s request: trailing data after the JSON object", r.URL.Path)
return false
}
return true
}
@@ -31,6 +31,7 @@ type fakeChunkControl struct {
lastSnap ChunkSnapshotRequest
lastMin uint64
deadline time.Duration
calls int
}
func (f *fakeChunkControl) remember(ctx context.Context) {
@@ -40,23 +41,28 @@ func (f *fakeChunkControl) remember(ctx context.Context) {
}
func (f *fakeChunkControl) Cut(ctx context.Context, vol string, minLSN uint64) (ChunkCutResponse, error) {
f.calls++
f.remember(ctx)
f.lastMin = minLSN
return f.cut, f.err
}
func (f *fakeChunkControl) Snapshot(ctx context.Context, vol string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) {
f.calls++
f.remember(ctx)
f.lastSnap = req
return f.snap, f.err
}
func (f *fakeChunkControl) ListSnapshots(ctx context.Context, vol string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) {
f.calls++
f.lastOpts = opts
return f.list, f.next, f.err
}
func (f *fakeChunkControl) DeleteSnapshot(ctx context.Context, vol, name string) (string, error) {
f.calls++
return f.state, f.err
}
func (f *fakeChunkControl) Detach(ctx context.Context, vol string) (ChunkDetachResponse, error) {
f.calls++
f.remember(ctx)
return f.detach, f.err
}
@@ -267,3 +273,28 @@ func TestStatusServer_ChunkRequestGuards(t *testing.T) {
t.Fatalf("no chunk control wired: %d %s", w.Code, w.Body)
}
}
// A request body is exactly one JSON object: trailing data refuses the
// request with bad_request before any operation runs.
func TestStatusServer_ChunkBodyIsOneJSONObject(t *testing.T) {
code := func(w *httptest.ResponseRecorder) string {
var b struct {
Code string `json:"code"`
}
_ = json.Unmarshal(w.Body.Bytes(), &b)
return b.Code
}
for _, body := range []string{`{"volumeID":"v1"} {"volumeID":"v1"}`, `{"volumeID":"v1"}garbage`, `{"volumeID":"v1"}{}`} {
for _, route := range []string{"/chunk/cut", "/chunk/detach"} {
ctl := &fakeChunkControl{}
w := serve(t, chunkServer(t, ctl, true), http.MethodPost, route, body, "")
if w.Code != http.StatusBadRequest || code(w) != "bad_request" || ctl.calls != 0 {
t.Fatalf("%s with body %q: %d %s, %d operations called; want bad_request and none", route, body, w.Code, w.Body, ctl.calls)
}
}
}
ctl := &fakeChunkControl{}
if w := serve(t, chunkServer(t, ctl, true), http.MethodPost, "/chunk/cut", "{\"volumeID\":\"v1\"}\n", ""); w.Code != 200 || ctl.calls != 1 {
t.Fatalf("one object and a newline: %d %s", w.Code, w.Body)
}
}