volume: snapshot replay before the cut, minLSN in the provider, JSON transport errors

- Snapshot resolves its request with Catalog.SnapshotReplay first: a retry
  of a recorded request returns it and another request gets
  snapshot_exists, both without cutting (so a replay survives a detached,
  fenced or unreachable cut path).
- Cut passes minLSN to the provider, which refuses an LSN never written
  before publishing.
- outcome_unknown is reported whenever an unresolved CAS is in the error,
  also when the re-proposal was refused for authority.
- Transport errors are JSON like every /chunk/* response (ruling of
  2026-11-15): bad_request (400), method_not_allowed (405), forbidden (403).
- timeoutMs is compared with OpDeadline in milliseconds before converting,
  so a huge value selects OpDeadline instead of overflowing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 05:22:27 -08:00
1 parent 861855a021
commit 410efb6d03
4 files changed
+158 -50

No files matched your search

+37 -34
View File
@@ -118,7 +118,8 @@ type chunkErrorBody struct {
}
// The codes the routes add to the catalog's (B9 §2.2 plus the 2026-11-15
// rulings: awaiting_assignment, internal).
// rulings: awaiting_assignment, internal, and the transport errors
// bad_request, method_not_allowed, forbidden).
const (
codeVolumeNotServed = "volume_not_served"
codeNotPrimary = "not_primary"
@@ -129,6 +130,9 @@ const (
codeHeadConflict = "head_conflict"
codeClosing = "closing"
codeInternal = "internal"
codeBadRequest = "bad_request"
codeMethodNotAllowed = "method_not_allowed"
codeForbidden = "forbidden"
)
const chunkBodyLimit = 64 << 10
@@ -177,9 +181,9 @@ func writeChunkFailure(w http.ResponseWriter, err error) {
}
// chunkErrorCode maps an operation's error to (HTTP status, code,
// retryable). The most specific cause wins: a refused capture reports why
// it was refused, an unresolved CAS reports outcome_unknown even when the
// re-read failed on the remote.
// retryable). An unresolved CAS reports outcome_unknown even when the
// attempt was also refused or the re-read failed on the remote; otherwise
// a refused capture reports why it was refused.
func chunkErrorCode(err error) (int, string, bool) {
var ce *chunkstore.CatalogError
switch {
@@ -187,6 +191,10 @@ func chunkErrorCode(err error) (int, string, bool) {
return catalogStatus(ce.Code), ce.Code, ce.Retryable
case errors.Is(err, storage.ErrChunkLayerFenced):
return http.StatusConflict, codeFenced, false
case errors.Is(err, storage.ErrChunkCASOutcomeUnknown):
// An earlier CAS may still land: report that even when this
// attempt was also refused (the re-proposal re-checks admission).
return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true
case errors.Is(err, durable.ErrChunkAwaitingAuthority):
return http.StatusConflict, codeAwaitingAssignment, true
case errors.Is(err, durable.ErrChunkNotPrimary):
@@ -195,8 +203,6 @@ func chunkErrorCode(err error) (int, string, bool) {
return http.StatusConflict, codeEpochStale, false
case errors.Is(err, storage.ErrChunkBaseInstalling):
return http.StatusConflict, codeBaseInstalling, true
case errors.Is(err, storage.ErrChunkCASOutcomeUnknown):
return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true
case errors.Is(err, storage.ErrChunkHeadPrecondition):
return http.StatusConflict, codeHeadConflict, true
case errors.Is(err, storage.ErrChunkRemoteUnavailable):
@@ -226,17 +232,16 @@ func catalogStatus(code string) int {
}
// chunkAdmit runs the transport checks every route shares: method, then
// client. Like a malformed request, these are answered in plain text as
// on the rest of the listener; the typed JSON body is for the operation's
// own outcome (B9 §2.2 has no codes for them).
// client. Like every /chunk/* response, they answer in JSON (ruling of
// 2026-11-15); the rest of the listener keeps plain text.
func (s *StatusServer) chunkAdmit(w http.ResponseWriter, r *http.Request, method string) bool {
if r.Method != method {
w.Header().Set("Allow", method)
http.Error(w, r.URL.Path+" requires "+method, http.StatusMethodNotAllowed)
writeChunkErr(w, http.StatusMethodNotAllowed, codeMethodNotAllowed, false, "%s requires %s", r.URL.Path, method)
return false
}
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
http.Error(w, "chunk control restricted to loopback", http.StatusForbidden)
writeChunkErr(w, http.StatusForbidden, codeForbidden, false, "chunk control restricted to loopback")
return false
}
return true
@@ -263,7 +268,7 @@ func decodeChunkBody(w http.ResponseWriter, r *http.Request, v any) bool {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, chunkBodyLimit))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
http.Error(w, "decode "+r.URL.Path+" request: "+err.Error(), http.StatusBadRequest)
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "decode %s request: %v", r.URL.Path, err)
return false
}
return true
@@ -272,8 +277,8 @@ func decodeChunkBody(w http.ResponseWriter, r *http.Request, v any) bool {
// chunkContext bounds a long operation by min(timeoutMs, OpDeadline).
func chunkContext(r *http.Request, timeoutMs int64) (context.Context, context.CancelFunc) {
d := chunkstore.DefaultOpDeadline
if t := time.Duration(timeoutMs) * time.Millisecond; timeoutMs > 0 && t < d {
d = t
if timeoutMs > 0 && timeoutMs < d.Milliseconds() { // compare before converting: no overflow
d = time.Duration(timeoutMs) * time.Millisecond
}
return context.WithTimeout(r.Context(), d)
}
@@ -346,7 +351,7 @@ func (s *StatusServer) handleChunkSnapshots(w http.ResponseWriter, r *http.Reque
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
http.Error(w, fmt.Sprintf("limit=%q: a non-negative integer", v), http.StatusBadRequest)
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "limit=%q: a non-negative integer", v)
return
}
opts.Limit = n
@@ -354,7 +359,7 @@ func (s *StatusServer) handleChunkSnapshots(w http.ResponseWriter, r *http.Reque
if v := q.Get("includeDeleting"); v != "" {
b, err := strconv.ParseBool(v)
if err != nil {
http.Error(w, fmt.Sprintf("includeDeleting=%q: true or false", v), http.StatusBadRequest)
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "includeDeleting=%q: true or false", v)
return
}
opts.IncludeDeleting = b
@@ -430,8 +435,10 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request)
// ChunkProvider is the durable provider's chunk surface the control uses.
type ChunkProvider interface {
// CutVolume takes one quiesced cut and returns what it installed.
CutVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, error)
// CutVolume takes one quiesced cut and returns what it installed; with
// minLSN > 0 it refuses an LSN never written before publishing, and
// fails unless the cut reaches minLSN.
CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error)
// DetachVolume stops the volume's I/O and periodic cuts and publishes
// the detached final cut; it also returns the last written LSN.
DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error)
@@ -449,13 +456,10 @@ func NewChunkControl(p ChunkProvider, cat *chunkstore.Catalog) ChunkControl {
}
func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) (ChunkCutResponse, error) {
r, err := c.p.CutVolume(ctx, volumeID)
r, err := c.p.CutVolume(ctx, volumeID, minLSN)
if err != nil {
return ChunkCutResponse{}, err
}
if r.H < minLSN {
return ChunkCutResponse{}, fmt.Errorf("chunk cut of %s reached LSN %d, below minLSN %d (never written)", volumeID, r.H, minLSN)
}
st := r.Stats
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, CandidateChunks: st.CandidateChunks, UploadedChunks: st.UploadedChunks,
@@ -463,23 +467,22 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64)
UploadNs: st.UploadNs, CasNs: st.CASNs, TotalNs: st.TotalNs}, nil
}
// Snapshot validates the request, cuts, and stores the HEAD that cut
// installed (§3.2). A retry with the same request id returns the first
// snapshot even though it cut again.
// Snapshot resolves the request against the catalog first (§3.2 step 1):
// a retry of a recorded request returns that snapshot and another request
// for the name gets snapshot_exists, both without cutting. Only a free name
// is cut, and the HEAD that cut installed is stored.
func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) {
if err := chunkstore.CheckSnapshotName(req.Name); err != nil {
return chunkstore.SnapshotInfo{}, err
sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels,
Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume"}
if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed {
return info, err
}
if req.RequestID == "" {
return chunkstore.SnapshotInfo{}, &chunkstore.CatalogError{Code: chunkstore.CodeInvalidName, Message: "a request id is required"}
}
r, err := c.p.CutVolume(ctx, volumeID)
r, err := c.p.CutVolume(ctx, volumeID, 0)
if err != nil {
return chunkstore.SnapshotInfo{}, err
}
return c.cat.CreateSnapshot(ctx, volumeID, chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID,
Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume",
SourceReadAt: time.Now()}, r.Head)
sreq.SourceReadAt = time.Now()
return c.cat.CreateSnapshot(ctx, volumeID, sreq, r.Head)
}
func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) {
@@ -9,14 +9,20 @@ import (
)
type fakeChunkProvider struct {
cut storage.ChunkCutResult
detach storage.ChunkCutResult
last uint64
cuts int
cut storage.ChunkCutResult
cutErr error
detach storage.ChunkCutResult
last uint64
cuts int
lastMin uint64
}
func (f *fakeChunkProvider) CutVolume(context.Context, string) (storage.ChunkCutResult, error) {
func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) {
f.cuts++
f.lastMin = minLSN
if f.cutErr != nil {
return storage.ChunkCutResult{}, f.cutErr
}
return f.cut, nil
}
@@ -76,12 +82,9 @@ func TestChunkControl_SnapshotStoresTheCutHead(t *testing.T) {
func TestChunkControl_CutMinLSNAndDetach(t *testing.T) {
ctx := context.Background()
fp, ctl := adapterFixture(t)
if _, err := ctl.Cut(ctx, "v1", 10); err == nil {
t.Fatal("a cut that reached LSN 9 satisfied minLSN 10")
}
r, err := ctl.Cut(ctx, "v1", 9)
if err != nil || r != (ChunkCutResponse{VolumeID: "v1", CutLSN: 9, HeadGen: 3, HeadEpoch: 2, Holder: "r1"}) {
t.Fatalf("cut: %+v %v", r, err)
if err != nil || fp.lastMin != 9 || r != (ChunkCutResponse{VolumeID: "v1", CutLSN: 9, HeadGen: 3, HeadEpoch: 2, Holder: "r1"}) {
t.Fatalf("cut: %+v %v (provider got minLSN %d)", r, err, fp.lastMin)
}
fp.detach = storage.ChunkCutResult{H: 12, Head: storage.ChunkHead{Gen: 4, Epoch: 2, State: storage.ChunkHeadDetached}}
fp.last = 12
@@ -0,0 +1,88 @@
package volume
// Operation order in the control adapter (review of #115): a snapshot
// resolves its request before it cuts (§3.2 step 1), and a cut to a minLSN
// never written publishes nothing (§3.1, MakeRemoteDurable's refusal).
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// After a recorded snapshot, the cut path fails (detached layer): a retry of
// the same request still returns the snapshot and another request gets
// snapshot_exists, neither cutting; only a free name reaches the cut.
func TestChunkControl_SnapshotResolvesRequestBeforeCutting(t *testing.T) {
ctx := context.Background()
fp, ctl := adapterFixture(t)
first, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"})
if err != nil || fp.cuts != 1 {
t.Fatalf("first snapshot: %+v %v (cuts %d)", first, err, fp.cuts)
}
fp.cutErr = storage.ErrChunkLayerDetached
again, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"})
if err != nil || !again.Replayed || again.HeadGen != first.HeadGen || fp.cuts != 1 {
t.Fatalf("retry after the cut path failed: %+v %v (cuts %d); want the recorded snapshot without a cut", again, err, fp.cuts)
}
if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "other"}); chunkstore.CodeOf(err) != chunkstore.CodeSnapshotExists || fp.cuts != 1 {
t.Fatalf("another request for the name: %v (cuts %d); want snapshot_exists without a cut", err, fp.cuts)
}
if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s2", RequestID: "r2"}); err == nil || fp.cuts != 2 {
t.Fatalf("a free name with the cut path failing: %v (cuts %d); want the cut's error", err, fp.cuts)
}
}
type healthyView struct{}
func (healthyView) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true}
}
// Through the real provider: a minLSN never written is refused with no
// upload and no new HEAD; a written one cuts.
func TestChunkControl_CutToUnwrittenMinLSNPublishesNothing(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
dp, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk,
StorageRoot: t.TempDir(),
BlockSize: 4096,
NumBlocks: 256,
ChunkBlocks: 16,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, healthyView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = dp.Close() })
s, err := dp.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
if _, err := dp.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if _, err := s.Write(1, make([]byte, 4096)); err != nil {
t.Fatal(err)
}
cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks")
if err != nil {
t.Fatal(err)
}
ctl := NewChunkControl(dp, cat)
last := s.NextLSN() - 1
if _, err := ctl.Cut(ctx, "v1", last+5); err == nil {
t.Fatal("a cut to an LSN never written succeeded")
}
if head, _ := remote.GetHead(ctx); head.Gen != 0 || remote.Puts() != 0 {
t.Fatalf("a refused minLSN published: HEAD gen %d, %d chunks stored", head.Gen, remote.Puts())
}
if r, err := ctl.Cut(ctx, "v1", last); err != nil || r.CutLSN != last || r.HeadGen != 1 {
t.Fatalf("cut to the last written LSN: %+v %v", r, err)
}
}
@@ -141,6 +141,11 @@ func TestStatusServer_ChunkSuccessBodiesUseSpecFields(t *testing.T) {
if w.Code != 200 || ctl.lastMin != 7 || ctl.deadline <= 0 || ctl.deadline > time.Second {
t.Fatalf("cut: %d %s (minLSN %d, deadline %v)", w.Code, w.Body, ctl.lastMin, ctl.deadline)
}
// A timeoutMs too large for a Duration is clamped to OpDeadline, not overflowed.
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1","timeoutMs":9223372036855}`, ""); w.Code != 200 ||
ctl.deadline < chunkstore.DefaultOpDeadline-time.Minute || ctl.deadline > chunkstore.DefaultOpDeadline {
t.Fatalf("cut with a huge timeoutMs: %d (deadline %v), want OpDeadline", w.Code, ctl.deadline)
}
wantKeys(t, "cut", jsonKeys(t, w.Body.Bytes()), "volumeID", "cutLSN", "headGen", "headEpoch", "holder", "noop", "fullHash",
"candidateChunks", "uploadedChunks", "uploadedBytes", "zeroedChunks", "barrierPauseNs", "uploadNs", "casNs", "totalNs")
@@ -208,6 +213,11 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) {
{&chunkstore.CatalogError{Code: chunkstore.CodeDeadlineExceeded, Message: "m", Retryable: true}, "deadline_exceeded", 503, true},
{context.DeadlineExceeded, "deadline_exceeded", 503, true},
{errors.New("something else"), "internal", 500, false},
// A held CAS whose re-proposal was refused: the uncertainty is reported.
{fmt.Errorf("x (%w); re-proposal refused: %w", storage.ErrChunkCASOutcomeUnknown,
fmt.Errorf("%w: %w", storage.ErrChunkCaptureRefused, durable.ErrChunkNotPrimary)), "outcome_unknown", 503, true},
{fmt.Errorf("x (%w); re-proposal refused: %w", storage.ErrChunkCASOutcomeUnknown,
fmt.Errorf("%w: %w", storage.ErrChunkCaptureRefused, durable.ErrChunkEpochStale)), "outcome_unknown", 503, true},
}
for _, c := range cases {
ctl := &fakeChunkControl{err: c.err}
@@ -239,14 +249,18 @@ func TestStatusServer_ChunkRequestGuards(t *testing.T) {
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v9"}`, ""); w.Code != 404 || code(w) != "volume_not_served" {
t.Fatalf("other volume: %d %s", w.Code, w.Body)
}
if w := serve(t, s, http.MethodGet, "/chunk/cut", "", ""); w.Code != http.StatusMethodNotAllowed {
t.Fatalf("GET on a POST route: %d", w.Code)
// Transport errors are JSON too (ruling of 2026-11-15).
if w := serve(t, s, http.MethodGet, "/chunk/cut", "", ""); w.Code != http.StatusMethodNotAllowed || code(w) != "method_not_allowed" {
t.Fatalf("GET on a POST route: %d %s", w.Code, w.Body)
}
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "10.0.0.9:4000"); w.Code != http.StatusForbidden {
t.Fatalf("non-loopback client: %d", w.Code)
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "10.0.0.9:4000"); w.Code != http.StatusForbidden || code(w) != "forbidden" {
t.Fatalf("non-loopback client: %d %s", w.Code, w.Body)
}
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{not json`, ""); w.Code != 400 {
t.Fatalf("bad body: %d", w.Code)
if w := serve(t, s, http.MethodPost, "/chunk/cut", `{not json`, ""); w.Code != 400 || code(w) != "bad_request" {
t.Fatalf("bad body: %d %s", w.Code, w.Body)
}
if w := serve(t, s, http.MethodGet, "/chunk/snapshots?volume=v1&limit=x", "", ""); w.Code != 400 || code(w) != "bad_request" {
t.Fatalf("bad limit: %d %s", w.Code, w.Body)
}
unwired := chunkServer(t, nil, true)
if w := serve(t, unwired, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, ""); w.Code != 409 || code(w) != "not_chunk_volume" {