fix(cli): align retry answers and snapshot replay reporting (#987)

Merge note (batch b3; pull_request_target spec-trace workflow has a startup_failure, so its checks run locally):
- One Test run (47182042028) succeeded (go test (linux), process-level tests (real binaries)) on the integration tree 4366f2cc = main a3362e32 + #987 #999  in this order; these squash merges reproduce that tree, verified after the last one.
- spec-trace-check.sh and public-text-check.sh, run with main's scripts against this head and body: both exit 0.
- Composition ACCEPT on 9c5b1d1e after rebasing onto the merged batch: asynchronous-only snapshot admission is kept, and replay changes no durable outcome or HEAD.
- Code review ACCEPT on 126c893a, no remaining findings: every failed single-filer census passes one classifier that reads the owned context once, so a caller's own cancel, deadline or custom cause is kept through every phase (configuration, master calls, retry pause, target lookup) and the direct catalog dial; only the internal window marker maps to unavailable. Exact advice and the partial verify result are pinned. A delete refused at reservation because a holder is live answers not_admitted, non-retryable, exit 1 ("stop the volume first"); only the final lease horizon after a recorded reservation answers retryable with exit 75.
This commit is contained in:
pingqiu-cpu authored and GitHub committed 2026-12-03 11:32:41 -08:00
1 parent a90160a1eb
commit 4a76882b32
27 files changed
+973 -53

No files matched your search

@@ -77,13 +77,17 @@ func (env *handoffEnv) deletePastPrintedHorizon(t *testing.T, volume, request st
// deleteLeaseHorizon accepts only the documented typed CLI refusal, never
// a matching stderr fragment or a successful exit with an error-shaped body.
// A signal stop does not retire the master lease: step 4 still returns the
// Reserve refusal still requires keeping the holder stopped (exit 1); after
// reservation commits, the final horizon refusal is temporary (exit 75).
func deleteLeaseHorizon(out string, code int) (time.Time, error) {
var body struct {
Code string `json:"code"`
Message string `json:"message"`
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
}
if code != 1 {
return time.Time{}, fmt.Errorf("exit %d is not refusal", code)
if code != 75 && code != 1 {
return time.Time{}, fmt.Errorf("exit %d is not temporary refusal", code)
}
if err := json.Unmarshal([]byte(out), &body); err != nil {
return time.Time{}, err
@@ -91,6 +95,12 @@ func deleteLeaseHorizon(out string, code int) (time.Time, error) {
if body.Code != "not_admitted" {
return time.Time{}, fmt.Errorf("code %q is not not_admitted", body.Code)
}
if code == 75 && !body.Retryable {
return time.Time{}, fmt.Errorf("final lease refusal is not retryable")
}
if code == 1 && (body.Retryable || !strings.HasPrefix(body.Message, "stop the volume first: ")) {
return time.Time{}, fmt.Errorf("Reserve refusal must require stopping the volume first")
}
_, rest, ok := strings.Cut(body.Message, "live until ")
if !ok {
return time.Time{}, fmt.Errorf("missing lease horizon")
@@ -105,20 +115,26 @@ func deleteLeaseHorizon(out string, code int) (time.Time, error) {
// The CLI error body, rather than a substring in combined output, is the
// authority for retry timing. Every refusal class stays distinguishable.
func TestDeleteLeaseHorizonRequiresTypedRefusal(t *testing.T) {
const valid = `{"code":"not_admitted","message":"workspace delete: live until 2026-11-26T13:00:00.125Z: lease expiry plus clock-skew margin has not elapsed"}`
const valid = `{"code":"not_admitted","retryable":true,"message":"workspace delete: live until 2026-11-26T13:00:00.125Z: lease expiry plus clock-skew margin has not elapsed"}`
for _, tc := range []struct {
name, out string
code int
ok bool
}{
{"typed horizon", valid, 1, true},
{"typed retryable horizon", valid, 75, true},
{"Reserve horizon after holder already stopped", strings.Replace(strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), `"message":"`, `"message":"stop the volume first: `, 1), 1, true},
{"Reserve without stop cure", strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), 1, false},
{"old refusal exit", valid, 1, false},
{"non-retryable refusal", strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), 75, false},
{"missing retryable", strings.Replace(valid, `"retryable":true,`, "", 1), 75, false},
{"wrong typed code", strings.Replace(valid, "not_admitted", "remote_unavailable", 1), 75, false},
{"successful exit cannot refuse", valid, 0, false},
{"usage failure", valid, 2, false},
{"plain stderr is not evidence", "not_admitted: live until 2026-11-26T13:00:00.125Z", 1, false},
{"plain stderr is not evidence", "not_admitted: live until 2026-11-26T13:00:00.125Z", 75, false},
{"dependent refusal", `{"code":"snapshot_has_dependents","message":"snapshot s1"}`, 1, false},
{"uncertain lease", `{"code":"not_admitted","message":"restart required"}`, 1, false},
{"missing time", `{"code":"not_admitted","message":"live until "}`, 1, false},
{"invalid time", `{"code":"not_admitted","message":"live until tomorrow: refused"}`, 1, false},
{"uncertain lease", `{"code":"not_admitted","retryable":true,"message":"restart required"}`, 75, false},
{"missing time", `{"code":"not_admitted","retryable":true,"message":"live until "}`, 75, false},
{"invalid time", `{"code":"not_admitted","retryable":true,"message":"live until tomorrow: refused"}`, 75, false},
} {
t.Run(tc.name, func(t *testing.T) {
until, err := deleteLeaseHorizon(tc.out, tc.code)
@@ -195,10 +211,11 @@ func TestProcedureDeleteAVolume(t *testing.T) {
state0, n0 := env.headShown(t)
out, errOut, code := env.deletePastPrintedHorizon(t, "v1", "del-v1", true)
var refusal struct {
Code string `json:"code"`
Message string `json:"message"`
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
}
if err := json.Unmarshal([]byte(out), &refusal); err != nil || code != 1 || refusal.Code != "snapshot_has_dependents" || !strings.Contains(refusal.Message, `snapshot "s1"`) {
if err := json.Unmarshal([]byte(out), &refusal); err != nil || code != 1 || refusal.Retryable || refusal.Code != "snapshot_has_dependents" || !strings.Contains(refusal.Message, `snapshot "s1"`) {
t.Fatalf("volume-delete with a dependent: exit %d %s %s; want typed snapshot_has_dependents naming s1", code, out, errOut)
}
if state, n := env.headShown(t); state != "detached" || state != state0 || n != n0 || n == 0 {
@@ -31,7 +31,7 @@ func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
for _, command := range []string{"snapshots", "show"} {
code, out, _ := runChunk(cliArgs(command, volArgs("volume", v))...)
e := chunkErrorOut(t, out)
if code != chunkExitFailed || e.Code != chunkstore.CodeRemoteUnavailable || !e.Retryable {
if code != 75 || e.Code != chunkstore.CodeRemoteUnavailable || !e.Retryable {
t.Fatalf("%s: exit=%d answer=%+v", command, code, e)
}
}
@@ -110,7 +110,11 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult("snapshots", nil, tc.err, &out, &diag)
e := chunkErrorOut(t, out.String())
if exit != chunkExitFailed || e.Code != tc.code || e.Retryable != tc.retry {
wantExit := chunkExitFailed
if tc.code == codeUnavailableCLI {
wantExit = 75
}
if exit != wantExit || e.Code != tc.code || e.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v", exit, e)
}
})
@@ -31,7 +31,7 @@ func chunkRunCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog
}
func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, op chunkstore.SnapshotOperation, work chunkstore.SnapshotDeleteWork, noWait bool, stderr io.Writer) (any, error) {
fmt.Fprintf(stderr, "snapshot-delete %s request id %s instance %s sequence %d; repeat with the same --request-id to resume\n", snapshotIncarnation(op), op.ID, op.Instance, op.Sequence)
fmt.Fprintf(stderr, "snapshot-delete %s request id %s instance %s sequence %d; keep the same --request-id if resuming\n", snapshotIncarnation(op), op.ID, op.Instance, op.Sequence)
if op.State == "refused" {
return nil, catalogSnapshotDeleteRefusal(op)
}
@@ -64,6 +64,12 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata
if errors.Is(err, layout.ErrBusy) {
return nil, err // A caller without a window must not start endless retries.
}
if errors.Is(err, layout.ErrHasDependents) {
return nil, &chunkstore.CatalogError{Code: "snapshot_has_dependents", Message: "remove dependent volumes or release their dependency before resuming the same --request-id", Err: err}
}
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if err != nil {
return nil, &chunkstore.CatalogError{Code: "no_progress", Message: err.Error() + "; resume with --request-id " + op.ID, Retryable: true, Err: err}
}
+29 -6
View File
@@ -65,10 +65,10 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
// too (a caller's whole-pass deadline or cancellation); a refusal names the
// parent's cancellation cause.
func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int {
ctx, cancel := context.WithTimeout(parent, timeout)
ctx, cancel := context.WithTimeoutCause(parent, timeout, chunkstore.ErrSingleFilerWindowExpired)
defer cancel()
err := checkSingleFiler(ctx, f)
if err != nil && parent.Err() != nil {
if err != nil && !errors.Is(err, chunkstore.ErrSingleFilerWindowExpired) && parent.Err() != nil {
if c := context.Cause(parent); c != nil && !errors.Is(err, c) {
err = fmt.Errorf("%w (%w)", err, c)
}
@@ -219,11 +219,12 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
}
// The route's error body is already the CLI's error body: relay it.
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, e.Message)
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
if err := writeAll(stdout, out); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the error: %v\n", name, err)
return chunkExitFailed
}
return chunkExitFailed
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
}
func chunkCut(args []string, stdout, stderr io.Writer) int {
@@ -366,13 +367,19 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
var ce *chunkstore.CatalogError
switch {
case errors.As(err, &ce):
return chunkFail(name, stdout, stderr, chunkExitFailed, ce.Code, ce.Detail(), ce.Retryable)
exit := chunkExitFailed
if name == "volume-delete" && ce.Code == "not_admitted" && ce.Retryable {
exit = 75 // temporary admission refusal; retry the same request ID
}
return chunkFail(name, stdout, stderr, exit, ce.Code, ce.Detail(), ce.Retryable)
case chunkCanceled(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeCanceledCLI, "operation interrupted by its caller", false)
case errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
case errors.Is(err, context.DeadlineExceeded):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case chunkTransportFailure(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
case errors.Is(err, errVerifyStalled):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case layoutCode(err) != "":
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrBusy))
default:
@@ -410,6 +417,8 @@ type chunkErrBody struct {
// {code,message,retryable} on stdout, as the routes answer it, a log line on
// stderr, and the exit code. The message does not repeat the code.
func chunkFail(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
exit = chunkErrorExit(exit, code, retryable)
message = chunkErrorAdvice(code, retryable, message)
prefix := "sw-block ops chunk"
if name != "" {
prefix += " " + name
@@ -433,3 +442,17 @@ func writeAll(w io.Writer, p []byte) error {
}
return err
}
// CLI temporary remote failures use EX_TEMPFAIL consistently across commands.
func chunkErrorExit(exit int, code string, retryable bool) int {
if code == codeUnavailableCLI && retryable {
return 75
}
return exit
}
func chunkErrorAdvice(code string, retryable bool, message string) string {
if code == codeUnavailableCLI && retryable {
return message + "; retry the same operation when the remote is reachable"
}
return message
}
+29 -2
View File
@@ -204,6 +204,7 @@ type fakeLifecycle struct {
control.UnimplementedLifecycleServiceServer
mu sync.Mutex
held bool
datedHorizon bool
leaseAfterReserve bool
reserved, leased bool
calls []string
@@ -218,6 +219,9 @@ func (f *fakeLifecycle) record(name string) {
func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
f.record("reserve")
if f.held {
if f.datedHorizon {
return nil, status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")
}
return nil, status.Error(codes.FailedPrecondition, "volume has a live authority line")
}
f.reserved = true
@@ -230,6 +234,9 @@ func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.Mark
func (f *fakeLifecycle) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
f.record("check")
if !f.reserved || f.leased {
if f.datedHorizon {
return nil, status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")
}
return nil, status.Error(codes.FailedPrecondition, "a line of the volume holds a live lease")
}
return &control.MarkVolumeDeletingResponse{Known: true}, nil
@@ -274,13 +281,33 @@ func TestOpsChunk_VolumeDeleteOnTheLayout(t *testing.T) {
return u.OwnChunks + u.ForeignChunks
}
held := &fakeLifecycle{held: true}
if code, out := del(held, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(held.calls, ",") != "reserve" {
if code, out := del(held, tgt); code != 1 || chunkErrorOut(t, out).Code != "not_admitted" || chunkErrorOut(t, out).Retryable || strings.Join(held.calls, ",") != "reserve" {
t.Fatalf("delete of a held volume: %d %q calls %v", code, out, held.calls)
}
for _, tc := range []struct {
name string
before bool
exit int
retry bool
calls, advice string
}{
{"Reserve live holder with dated horizon", true, 1, false, "reserve", "stop the volume first"},
{"committed reservation final dated barrier", false, 75, true, "reserve,check", "retry the same --request-id after 2026-12-03T13:00:00Z"},
} {
t.Run(tc.name, func(t *testing.T) {
lc := &fakeLifecycle{held: tc.before, leaseAfterReserve: !tc.before, datedHorizon: true}
code, out := del(lc, tgt)
answer := chunkErrorOut(t, out)
if code != tc.exit || answer.Code != "not_admitted" || answer.Retryable != tc.retry || !strings.HasPrefix(answer.Message, tc.advice+": ") || strings.Join(lc.calls, ",") != tc.calls || objects(tgt) != 1 {
t.Fatalf("exit=%d answer=%+v calls=%v objects=%d", code, answer, lc.calls, objects(tgt))
}
})
}
// A grant racing the reservation: the master's check between the HEAD
// read and the update refuses, and nothing is deleted.
race := &fakeLifecycle{leaseAfterReserve: true}
if code, out := del(race, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 {
if code, out := del(race, tgt); code != 1 || chunkErrorOut(t, out).Code != "not_admitted" || chunkErrorOut(t, out).Retryable || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 {
t.Fatalf("delete with a lease granted after the reservation: %d %q calls %v objects %d; want refused by the check, nothing deleted", code, out, race.calls, objects(tgt))
}
if h, _, _ := func() (layout.Head, bool, error) {
@@ -7,6 +7,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net"
"testing"
"time"
@@ -67,3 +68,34 @@ func TestChunkCensusKeepsItsParentCancellationCause(t *testing.T) {
})
}
}
func TestChunkCensusInternalWinnerSurvivesLaterCallerDeadline(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr})
if err != nil {
t.Fatal(err)
}
defer client.Close()
parent, stop := context.WithCancelCause(context.Background())
defer stop(nil)
previous := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previous })
checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error {
err := previous(ctx, f)
stop(context.DeadlineExceeded) // after the internal window's classified result
return err
}
var out, diag bytes.Buffer
exit := refuseUnlessSingleFilerWithin(parent, "verify", client, time.Millisecond, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("late caller overrode first internal expiry: %d %+v", exit, answer)
}
}
@@ -0,0 +1,183 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// One output contract across every chunk command: a transport outage is a
// temporary failure, while a caller timeout or permanent refusal stays distinct.
func TestChunkErrorFamilyAnswerTable(t *testing.T) {
for _, command := range []string{"snapshots", "show", "usage", "snapshot-delete", "retain", "release", "volume-delete", "verify", "restore", "snapshot", "cut", "detach"} {
for _, tc := range []struct {
name string
err error
code string
exit int
retry bool
advice string
only string
}{
{"remote", status.Error(codes.Unavailable, "connection refused"), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"caller timeout", context.DeadlineExceeded, "deadline_exceeded", 1, true, context.DeadlineExceeded.Error(), ""},
{"caller cancel", context.Canceled, "canceled", 1, false, "operation interrupted by its caller", ""},
{"dependents", layout.ErrHasDependents, "snapshot_has_dependents", 1, false, layout.ErrHasDependents.Error(), ""},
{"committed reservation final barrier", finalLeaseBarrierErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), "not_admitted", 75, true, "retry the same --request-id after 2026-12-03T13:00:00Z: " + chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed", "volume-delete"},
{"Reserve live holder with moving horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), "not_admitted", 1, false, "stop the volume first: " + chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed", "volume-delete"},
{"restart required", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: lease persistence uncertain; restart required")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: lease persistence uncertain; restart required", "volume-delete"},
{"skipped authority", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: authority records were skipped during recovery; lease absence is unknown")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: authority records were skipped during recovery; lease absence is unknown", "volume-delete"},
{"live holder", authorityErr(status.Error(codes.FailedPrecondition, "volume has a live authority line; stop the holder before deleting")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = volume has a live authority line; stop the holder before deleting", "volume-delete"},
{"invalid horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until tomorrow: lease expiry unknown")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until tomorrow: lease expiry unknown", "volume-delete"},
} {
if tc.only != "" && command != tc.only {
continue
}
t.Run(command+"/"+tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult(command, nil, tc.err, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != tc.exit || answer.Code != tc.code || answer.Retryable != tc.retry || answer.Message != tc.advice {
t.Fatalf("exit=%d answer=%+v; want %d/%s/retry=%v/advice=%q", exit, answer, tc.exit, tc.code, tc.retry, tc.advice)
}
})
}
}
}
func TestUnreachableFilerAtTheCommandWindowIsTemporary(t *testing.T) {
previousResolve := resolveVolumeID
t.Cleanup(func() { resolveVolumeID = previousResolve })
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{4}, nil }
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
for _, command := range []string{"snapshot-delete", "verify"} {
t.Run(command, func(t *testing.T) {
args := []string{command, "--volume", "v1", "--chunk-filer", addr, "--timeout", "100ms"}
if command == "snapshot-delete" {
args = append(args, "--master", "fixture:1", "--name", "daily", "--request-id", "offline-filer")
}
exit, out, diag := runChunk(args...)
answer := chunkErrorOut(t, out)
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v stderr=%s", exit, answer, diag)
}
})
}
}
func TestChunkHTTPRemoteAnswerKeepsItsBodyAndUsesTemporaryExit(t *testing.T) {
const body = `{"code":"remote_unavailable","message":"filer stopped","retryable":true}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503); fmt.Fprint(w, body) }))
defer server.Close()
for _, command := range []string{"snapshot", "detach"} {
t.Run(command, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkPost(command, server.URL, "/chunk/"+command, time.Second, map[string]any{"volumeID": "v1"}, &out, &diag)
if exit != 75 || out.String() != body || !strings.Contains(diag.String(), "retry") {
t.Fatalf("exit=%d out=%s stderr=%s", exit, &out, &diag)
}
})
}
}
func TestSnapshotDeleteDependentsIsNotAutomaticRetry(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "dependent-source", "daily")
cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI)
st, _ := cat.Store(v)
h, _, err := st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
s := h.Snapshots["daily"]
s.Gen = h.Gen + 1
s.Dependents = []layout.Dependent{{Target: "target", TargetID: layout.VolumeID{2}, Root: s.Root}}
h.Version, h.Snapshots["daily"] = layout.HeadVersion1, s
if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--request-id", "dependent-delete"})
for i := 0; i < 2; i++ {
exit, out, diag := runChunk(args...)
answer := chunkErrorOut(t, out)
if exit != 1 || answer.Code != "snapshot_has_dependents" || answer.Retryable || !strings.Contains(answer.Message, "dependent") {
t.Fatalf("attempt%d exit=%d answer=%+v stderr=%s", i, exit, answer, diag)
}
}
op, found, err := st.ReadSnapshotOperation(ctx, "dependent-delete", "delete")
if err != nil || !found || op.State != "stalled" {
t.Fatalf("receipt lost resumability: %+v %v", op, err)
}
if _, err := layout.RunReleaseDependent(ctx, st, layout.VolumeID{2}); err != nil {
t.Fatal(err)
}
if exit, out, diag := runChunk(args...); exit != 0 {
t.Fatalf("after releasing dependency: %d %s %s", exit, out, diag)
}
}
func TestSnapshotDeleteWorkTransportUsesSharedClassifier(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
cat, _ := chunkstore.NewBCatalog(mem, mem, "/blocks")
v := chunkstore.VolumeRef{Name: "work-failure", ID: layout.VolumeID{3}}
if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
st, _ := cat.Store(v)
op, err := st.AdmitSnapshotDeleteOperation(ctx, "work-remote", "daily", func(context.Context) (uint64, error) { return 2, nil })
if err != nil {
t.Fatal(err)
}
var out, diag bytes.Buffer
exit := chunkRunCatalogSnapshotDelete(ctx, cat, v, op, func(context.Context, *chunkstore.LayoutStore, chunkstore.SnapshotOperation) error {
return status.Error(codes.Unavailable, "filer stopped after admission")
}, false, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v", exit, answer)
}
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
if err != nil || retained.State != "stalled" {
t.Fatalf("lost resumability: %+v %v", retained, err)
}
}
func TestVerifyIncompleteTransportPreservesPartialProgress(t *testing.T) {
partial := layout.VerifyResult{Roots: 2, Segments: 3, Chunks: 7, ChunksZero: 1, Incomplete: "payload read interrupted", OrphansChecked: true, MasterIdentityChecked: true}
var out, diag bytes.Buffer
exit := verifyIncomplete(partial, status.Error(codes.Unavailable, "filer stopped"), &out, &diag)
var answer struct {
chunkErrBody
Verify layout.VerifyResult `json:"verify"`
}
if err := json.Unmarshal(out.Bytes(), &answer); err != nil {
t.Fatal(err)
}
const message = "rpc error: code = Unavailable desc = filer stopped; retry the same operation when the remote is reachable"
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: remote_unavailable: "+message+" (incomplete)\n" {
t.Fatalf("exit=%d answer=%+v stderr=%q", exit, answer, diag.String())
}
}
@@ -107,7 +107,7 @@ func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
return nil, status.Error(codes.Unavailable, "filer unreachable")
}
var out, errs bytes.Buffer
if code := run(args, &out, &errs); code != chunkExitFailed || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String())
}
}
@@ -6,6 +6,7 @@ import (
"fmt"
"google.golang.org/grpc"
"net"
"strings"
"sync/atomic"
"testing"
"time"
@@ -105,11 +106,11 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
var out, diag bytes.Buffer
exit := runOpsChunk(args, &out, &diag)
e := chunkErrorOut(t, out.String())
wantCode, wantRetry := "remote_unavailable", true
wantCode, wantRetry, wantExit := "remote_unavailable", true, 75
if failure.name == "rpc-canceled" {
wantCode, wantRetry = "canceled", false
wantCode, wantRetry, wantExit = "canceled", false, 1
}
if calls.Load() == 0 || exit != 1 || e.Code != wantCode || e.Retryable != wantRetry {
if calls.Load() == 0 || exit != wantExit || e.Code != wantCode || e.Retryable != wantRetry || (wantCode == codeUnavailableCLI && !strings.Contains(e.Message, "retry")) {
t.Errorf("calls=%d exit=%d answer=%+v", calls.Load(), exit, e)
}
})
@@ -134,13 +135,13 @@ func TestOpsChunkVerifyUnreachableCensusPreservesTransport(t *testing.T) {
previousCheck := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previousCheck })
checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error {
call, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
call, cancel := context.WithTimeoutCause(ctx, 50*time.Millisecond, chunkstore.ErrSingleFilerWindowExpired)
defer cancel()
return previousCheck(call, f)
}
code, out, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", addr, "--timeout", "5s")
e := chunkErrorOut(t, out)
if code != 1 || e.Code != "remote_unavailable" || !e.Retryable {
if code != 75 || e.Code != "remote_unavailable" || !e.Retryable {
t.Fatalf("exit=%d answer=%+v", code, e)
}
}
@@ -55,7 +55,7 @@ func TestOpsChunkTypedRefusalCodes(t *testing.T) {
code string
}{
{"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), chunkExitFailed, codeUnavailableCLI},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
} {
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
var out, errs bytes.Buffer
+15 -3
View File
@@ -159,7 +159,18 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
// errVerifyStalled is the cause of a verify pass ended by its no-progress
// window: a transient failure, answered like a deadline.
var errVerifyStalled = errors.New("verify: no object read completed within the --timeout no-progress window")
type verifyStallError struct{}
func (verifyStallError) Error() string {
return "verify: no object read completed within the --timeout no-progress window"
}
// During startup this is an internal window, not a caller deadline.
func (verifyStallError) Is(target error) bool {
return target == chunkstore.ErrSingleFilerWindowExpired
}
var errVerifyStalled error = verifyStallError{}
// verifyWatch is a pass's no-progress window. Renewal and expiry are decided
// under one lock on the clock's (monotonic) time: whichever of a read's
@@ -285,10 +296,11 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
} else if chunkTransportFailure(err) {
body.Code, body.Retryable = codeUnavailableCLI, true
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) {
if errors.Is(err, context.DeadlineExceeded) || (errors.Is(err, errVerifyStalled) && !chunkTransportFailure(err)) {
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
}
body.Message = chunkErrorAdvice(body.Code, body.Retryable, body.Message)
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
chunkResult("verify", body, nil, stdout, stderr)
return chunkExitFailed
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
}
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"strings"
"sync"
"time"
@@ -85,17 +86,43 @@ func (m *masterAuthority) Reserve(ctx context.Context) error {
func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
_, err := m.lc.CheckVolumeNoLiveLease(ctx, m.req)
return authorityErr(err)
return finalLeaseBarrierErr(err)
}
// authorityErr: FailedPrecondition and InvalidArgument are definite
// refusals; anything else (unavailable, deadline, a lost response) leaves
// authorityErr projects Reserve refusals before a reservation is committed.
// A dated live-holder refusal requires stopping the volume, not timed retry.
// Anything else (unavailable, deadline, a lost response) leaves
// the outcome unknown and a rerun decides.
func authorityErr(err error) error {
// Reserve has not committed authority to delete. A live holder can renew
// its horizon indefinitely, so waiting alone is not the cure.
result := finalLeaseBarrierErr(err)
var refusal *chunkstore.CatalogError
if errors.As(result, &refusal) && refusal.Code == "not_admitted" && refusal.Retryable {
refusal.Retryable = false
refusal.Message = "stop the volume first"
}
return result
}
// finalLeaseBarrierErr is only for NoLiveLease after Reserve committed.
// Grants are closed there, so the dated lease horizon can be waited out.
func finalLeaseBarrierErr(err error) error {
switch status.Code(err) {
case codes.OK:
return nil
case codes.FailedPrecondition, codes.InvalidArgument:
case codes.FailedPrecondition:
// The authority emits this exact horizon clause for its lease barrier.
// Other refusals need their own cure, not an automatic timed retry.
if _, rest, ok := strings.Cut(status.Convert(err).Message(), "workspace delete: live until "); ok {
if stamp, reason, ok := strings.Cut(rest, ": "); ok && reason != "" {
if until, parseErr := time.Parse(time.RFC3339Nano, stamp); parseErr == nil {
return &chunkstore.CatalogError{Code: "not_admitted", Message: "retry the same --request-id after " + until.UTC().Format(time.RFC3339Nano), Retryable: true, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
}
}
}
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)
case codes.InvalidArgument:
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)
}
return err
@@ -70,7 +70,7 @@ func TestVolumeDeleteContinuesAcrossTransientObjectFailures(t *testing.T) {
code, out, logs := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-progress", "--timeout", "150ms"})...)
if stuck {
e := chunkErrorOut(t, out)
if code != 1 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 0 of") || !strings.Contains(e.Message, "/") || !strings.Contains(e.Message, "object deadline") {
if code != 75 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 0 of") || !strings.Contains(e.Message, "/") || !strings.Contains(e.Message, "object deadline") {
t.Fatalf("stalled delete: code=%d out=%s logs=%s", code, out, logs)
}
if time.Since(started) > 3*time.Second {
@@ -151,7 +151,7 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
return
}
e := chunkErrorOut(t, out)
if code != 1 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 1 of 2") || !strings.Contains(e.Message, "stalled after first removal") {
if code != 75 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 1 of 2") || !strings.Contains(e.Message, "stalled after first removal") {
t.Fatalf("stall after progress: %d %s", code, out)
}
if elapsed := time.Since(f.removedAt); elapsed < bound || elapsed > bound+2*time.Second {
@@ -182,7 +182,7 @@ func TestVolumeDeleteReportsAStalledStoreWhileItWaits(t *testing.T) {
}
addr := startFakeLifecycle(t, &fakeLifecycle{})
code, out, logs := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "stalled", "--timeout", "800ms"})...)
if e := chunkErrorOut(t, out); code != 1 || e.Code != "remote_unavailable" {
if e := chunkErrorOut(t, out); code != 75 || e.Code != "remote_unavailable" {
t.Fatalf("stalled store: code=%d out=%s logs=%s; want the bounded remote_unavailable answer", code, out, logs)
}
var stall string
@@ -281,7 +281,7 @@ func TestVolumeDeleteAnswerDoesNotWaitOnAStuckStderr(t *testing.T) {
func TestVolumeDeleteNeverWritesStderrConcurrently(t *testing.T) {
slow := &overlapStderr{delay: time.Second}
code, out, _ := runVolumeDelete(t, "overlap-stderr", slow, 400*time.Millisecond, 10*time.Second)
if e := chunkErrorOut(t, out); code != 1 || e.Code != "remote_unavailable" {
if e := chunkErrorOut(t, out); code != 75 || e.Code != "remote_unavailable" {
t.Fatalf("answer %d %+v", code, e)
}
time.Sleep(1500 * time.Millisecond) // any write still in flight lands now
@@ -48,7 +48,8 @@ func TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted(t *testing.T) {
code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "live-lease"})...)
body := chunkErrorOut(t, out)
t.Logf("exit %d answer %+v", code, body)
if code != chunkExitFailed || body.Code != "not_admitted" ||
if code != 1 || body.Code != "not_admitted" || body.Retryable ||
!strings.Contains(body.Message, "stop the volume first") ||
!strings.Contains(body.Message, "deletion refused before persistence") {
t.Fatalf("volume-delete with a live lease: exit %d answer %+v stderr %s; want not_admitted saying it was refused before persistence", code, body, stderr)
}
@@ -59,7 +59,9 @@ func TestOpsChunkVolumeDeleteRefusedByDependentsLeavesTheVolumeReserved(t *testi
}
before := head()
code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "del-vol-f"})...)
if body := chunkErrorOut(t, out); code != chunkExitFailed || body.Code != c.wantCode {
wantExit := chunkExitFailed
if body := chunkErrorOut(t, out); code != wantExit || body.Code != c.wantCode || body.Retryable {
t.Fatalf("volume-delete: exit %d answer %+v stderr %s; want %s", code, body, stderr, c.wantCode)
}
if got := h.Lifecycle().Deletions.Reserved("vol-f"); got != c.reserved {
@@ -0,0 +1,37 @@
package main
import (
"bytes"
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestVolumeDeleteAdmissionRetryAnswer(t *testing.T) {
lease := finalLeaseBarrierErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed"))
for _, tc := range []struct {
name string
err error
exit int
code string
retry bool
}{
{"Reserve live-holder horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), 1, "not_admitted", false},
{"HEAD boundary horizon", fmt.Errorf("%w: %w", layout.ErrHolderActive, lease), 75, "not_admitted", true},
{"invalid admission", authorityErr(status.Error(codes.InvalidArgument, "invalid token")), 1, "not_admitted", false},
{"dependents", layout.ErrHasDependents, 1, "snapshot_has_dependents", false},
{"remote unknown", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult("volume-delete", nil, tc.err, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != tc.exit || answer.Code != tc.code || answer.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v; want exit=%d code=%s retry=%v", exit, answer, tc.exit, tc.code, tc.retry)
}
})
}
}
@@ -44,6 +44,15 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
}
return 0
}
if a.Answer.State == "succeeded" {
if len(a.Answer.Result) == 0 || !json.Valid(a.Answer.Result) {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
}
if err := writeAll(stdout, a.Answer.Result); err != nil {
return chunkExitFailed
}
return 0
}
base := addr
if !strings.Contains(base, "://") {
base = "http://" + base
@@ -0,0 +1,33 @@
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestSnapshotCLIUsesReplayedAdmissionAnswer(t *testing.T) {
polls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost && r.URL.Path == "/chunk/snapshot" {
w.Header().Set("Location", "/operations/replay")
w.WriteHeader(http.StatusAccepted)
fmt.Fprint(w, `{"operation_id":"same-id","state":"succeeded","result":{"name":"daily","replayed":true}}`)
return
}
if r.URL.Path == "/operations/replay" {
polls++
fmt.Fprint(w, `{"operation_id":"same-id","state":"succeeded","result":{"name":"daily","replayed":false}}`)
return
}
http.NotFound(w, r)
}))
defer server.Close()
exit, out, diag := runChunk("snapshot", "--volume", "v1", "--status-addr", server.URL, "--name", "daily", "--request-id", "same-id")
if exit != 0 || !strings.Contains(out, `"replayed":true`) || polls != 0 {
t.Fatalf("exit=%d out=%s stderr=%s polls=%d", exit, out, diag, polls)
}
}
@@ -11,6 +11,8 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
@@ -25,6 +27,10 @@ import (
// fence: a filer added to the group later is not detected.
var ErrNotSingleFiler = errors.New("chunkstore: block metadata needs exactly one filer")
// ErrSingleFilerWindowExpired labels an internal startup/progress budget.
// Callers must not use it for their own cancellation or absolute deadline.
var ErrSingleFilerWindowExpired = errors.New("chunkstore: single-filer internal window elapsed")
// singleFilerWait bounds the whole check; singleFilerRetry spaces the
// rounds; singleFilerAttempt bounds one master call within the remaining
// time (vars for tests). A filer registers with the master only some
@@ -42,8 +48,22 @@ var (
// disagreement and an empty leader listing retry within the startup bound.
// The leader listing another filer or several refuses immediately.
func (c *SWFS) CheckSingleFiler(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, singleFilerWait)
ctx, cancel := context.WithTimeoutCause(ctx, singleFilerWait, ErrSingleFilerWindowExpired)
defer cancel()
// Every failure phase uses the same owned-context winner, including
// retry pauses, master RPCs and a canceled target-address lookup.
err := c.checkSingleFiler(ctx)
if err == nil {
return nil
}
err = singleFilerContextError(ctx, err)
if !errors.Is(err, ErrNotSingleFiler) {
return fmt.Errorf("%w: %w", ErrNotSingleFiler, err)
}
return err
}
func (c *SWFS) checkSingleFiler(ctx context.Context) error {
// The dial is lazy and the filer may still be starting: wait for it, within the bound.
cfg, err := c.fc.GetFilerConfiguration(ctx, &filerpb.GetFilerConfigurationRequest{}, grpc.WaitForReady(true))
if err != nil {
@@ -52,6 +72,13 @@ func (c *SWFS) CheckSingleFiler(ctx context.Context) error {
if len(cfg.GetMasters()) == 0 {
return fmt.Errorf("%w: filer %s reports no master, cannot list its group", ErrNotSingleFiler, c.cfg.FilerGRPC)
}
// Validate the whole configured set before waiting for any master. A
// malformed address cannot recover by retrying a census round.
for _, master := range cfg.GetMasters() {
if _, err := grpcAddress(master); err != nil {
return fmt.Errorf("%w: master %s: %v; every master must answer, these did not: %s (rerun when they answer)", ErrNotSingleFiler, master, err, master)
}
}
var tried, unanswered []string
var observationErr error
for {
@@ -262,3 +289,17 @@ func grpcAddress(a string) (string, error) {
}
return net.JoinHostPort(host, strconv.Itoa(p+10000)), nil
}
// Inspect one owned context's completion before its immutable winning cause.
// Do not mix the parent's pre-expiry cause with the child's later Err.
func singleFilerContextError(ctx context.Context, err error) error {
done := ctx.Err()
if done == nil {
return err
}
cause := context.Cause(ctx)
if errors.Is(cause, ErrSingleFilerWindowExpired) {
return fmt.Errorf("%w: %w: %v", status.Error(codes.Unavailable, "filer transport unavailable"), cause, err)
}
return fmt.Errorf("%w: %w: %v", done, cause, err)
}
@@ -8,11 +8,14 @@ import (
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
@@ -45,6 +48,7 @@ type nodesMaster struct {
// early, with stall: answers DeadlineExceeded this long BEFORE its own
// deadline, as a gRPC server whose deadline (from the client's
// grpc-timeout) runs out ahead of the client's context does.
leaderCalls int
early time.Duration
calls int
got *masterpb.ListClusterNodesRequest
@@ -54,6 +58,7 @@ type nodesMaster struct {
func (m *nodesMaster) GetMasterConfiguration(ctx context.Context, _ *masterpb.GetMasterConfigurationRequest) (*masterpb.GetMasterConfigurationResponse, error) {
m.mu.Lock()
m.leaderCalls++
leader, stall, early := m.leader, m.stall, m.early
m.mu.Unlock()
if stall {
@@ -508,3 +513,310 @@ func TestCheckSingleFilerKeepsTransportCause(t *testing.T) {
}
})
}
// Use a real failed connection, not a health RPC returning a status code.
func TestCheckSingleFilerTransientFailureKeepsCallerCause(t *testing.T) {
for _, mode := range []string{"cancel", "deadline", "marked progress window", "internal window"} {
t.Run(mode, func(t *testing.T) {
c, err := DialSWFS(SWFSConfig{FilerGRPC: deadAddress(t)})
if err != nil {
t.Fatal(err)
}
defer c.Close()
wait, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
c.conn.Connect()
for {
state := c.conn.GetState()
if state == connectivity.TransientFailure {
break
}
if !c.conn.WaitForStateChange(wait, state) {
t.Fatalf("connection never failed: %v", wait.Err())
}
}
ctx := context.Background()
var want error
switch mode {
case "cancel":
next, cancel := context.WithCancel(ctx)
cancel()
ctx = next
want = context.Canceled
case "deadline":
next, cancel := context.WithDeadline(ctx, time.Now().Add(-time.Second))
defer cancel()
ctx = next
want = context.DeadlineExceeded
case "marked progress window":
next, cancel := context.WithCancelCause(ctx)
cancel(ErrSingleFilerWindowExpired)
ctx = next
case "internal window":
old := singleFilerWait
singleFilerWait = time.Millisecond
defer func() { singleFilerWait = old }()
}
err = c.CheckSingleFiler(ctx)
if !errors.Is(err, ErrNotSingleFiler) {
t.Fatalf("lost census refusal: %v", err)
}
if want != nil {
if !errors.Is(err, want) {
t.Fatalf("lost caller cause %v: %v", want, err)
}
} else if status.Code(err) != codes.Unavailable {
t.Fatalf("lost transport: %v", err)
}
})
}
}
func TestDialBCatalogKeepsCallerCause(t *testing.T) {
for _, deadline := range []bool{false, true} {
ctx, cancel := context.WithCancel(context.Background())
want := context.Canceled
if deadline {
cancel()
ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
want = context.DeadlineExceeded
} else {
cancel()
}
cat, client, err := DialBCatalog(ctx, SWFSConfig{FilerGRPC: deadAddress(t)})
cancel()
if cat != nil || client != nil || !errors.Is(err, want) {
t.Fatalf("deadline=%v cat=%v client=%v cause=%v want=%v", deadline, cat, client, err, want)
}
}
}
// Hold the actual gRPC dial in Connecting until after the configuration RPC
// ends. No TransientFailure transition can rescue the classification.
func TestCheckSingleFilerSlowDialOrdering(t *testing.T) {
old := singleFilerWait
singleFilerWait = 40 * time.Millisecond
defer func() { singleFilerWait = old }()
for _, mode := range []string{"internal window", "progress window", "caller cancel", "caller deadline", "caller custom deadline"} {
t.Run(mode, func(t *testing.T) {
started := make(chan struct{}, 1)
conn, err := grpc.NewClient("passthrough:///held-dial:1", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
select {
case started <- struct{}{}:
default:
}
<-ctx.Done()
return nil, ctx.Err()
}))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
c := &SWFS{cfg: SWFSConfig{FilerGRPC: "held-dial:1"}, conn: conn, fc: filerpb.NewSeaweedFilerClient(conn)}
bound, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
conn.Connect()
select {
case <-started:
case <-bound.Done():
t.Fatal("dial did not start")
}
ctx, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)
var want error
customDeadline := errors.New("caller-chosen absolute expiry")
if mode == "caller deadline" || mode == "caller custom deadline" {
cause := error(context.DeadlineExceeded)
if mode == "caller custom deadline" {
cause = customDeadline
}
next, stop := context.WithTimeoutCause(ctx, 20*time.Millisecond, cause)
defer stop()
ctx = next
want = context.DeadlineExceeded
}
result := make(chan error, 1)
go func() { result <- c.CheckSingleFiler(ctx) }()
switch mode {
case "progress window":
cancel(ErrSingleFilerWindowExpired)
case "caller cancel":
cancel(context.Canceled)
want = context.Canceled
}
select {
case err = <-result:
case <-bound.Done():
t.Fatal("configuration call did not end")
}
if state := conn.GetState(); state != connectivity.Connecting {
t.Fatalf("dial state=%v, want Connecting", state)
}
if !errors.Is(err, ErrNotSingleFiler) {
t.Fatalf("lost census refusal: %v", err)
}
if want != nil {
if !errors.Is(err, want) {
t.Fatalf("lost caller cause %v: %v", want, err)
}
} else if status.Code(err) != codes.Unavailable {
t.Fatalf("internal expiry lost remote provenance: %v", err)
}
if mode == "caller custom deadline" && !errors.Is(err, customDeadline) {
t.Fatalf("lost custom deadline cause: %v", err)
}
})
}
}
// Advancing the deadline at Err reproduces Cause=nil followed by Err=deadline
// without sleeps or a production hook. Both observations must not be mixed.
type deadlineAtErr struct {
context.Context
finish context.CancelCauseFunc
cause error
reads *int
}
func (c deadlineAtErr) Err() error {
if c.reads != nil {
*c.reads = *c.reads + 1
}
c.finish(c.cause)
return context.DeadlineExceeded
}
func TestSingleFilerConfigurationErrorDeadlineBetweenReads(t *testing.T) {
for _, phase := range []string{"configuration", "master observation"} {
t.Run(phase, func(t *testing.T) {
custom := errors.New("caller absolute deadline")
base, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)
reads := 0
ctx := deadlineAtErr{Context: base, finish: cancel, cause: custom, reads: &reads}
observation := status.Error(codes.Unavailable, phase+" failed before expiry")
err := singleFilerContextError(ctx, observation)
if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, custom) || !strings.Contains(err.Error(), observation.Error()) {
t.Fatalf("lost caller deadline/cause or %s diagnostics: %v", phase, err)
}
if reads != 1 {
t.Fatalf("completion read %d times, want one", reads)
}
})
}
}
func TestSingleFilerWindowWinsBeforeLaterCallerDeadline(t *testing.T) {
parent, stop := context.WithCancelCause(context.Background())
defer stop(nil)
ctx, cancel := context.WithTimeoutCause(parent, time.Millisecond, ErrSingleFilerWindowExpired)
defer cancel()
<-ctx.Done()
stop(context.DeadlineExceeded)
err := singleFilerContextError(ctx, status.Error(codes.DeadlineExceeded, "RPC ended"))
if status.Code(err) != codes.Unavailable || !errors.Is(err, ErrSingleFilerWindowExpired) || errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("late caller expiry overwrote internal winner: %v", err)
}
}
func TestDialBCatalogKeepsCustomCallerDeadline(t *testing.T) {
custom := errors.New("caller-chosen catalog deadline")
ctx, stop := context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), custom)
defer stop()
cat, client, err := DialBCatalog(ctx, SWFSConfig{FilerGRPC: deadAddress(t)})
if cat != nil || client != nil || !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, custom) {
t.Fatalf("lost direct caller deadline: cat=%v client=%v err=%v", cat, client, err)
}
}
type failedCensusMaster struct {
masterpb.UnimplementedSeaweedServer
stall bool
calls atomic.Int32
}
func (m *failedCensusMaster) GetMasterConfiguration(ctx context.Context, _ *masterpb.GetMasterConfigurationRequest) (*masterpb.GetMasterConfigurationResponse, error) {
m.calls.Add(1)
if m.stall {
<-ctx.Done()
return nil, status.Error(codes.Canceled, "master census call canceled")
}
return nil, status.Error(codes.Unavailable, "master census offline")
}
// Configuration succeeds. The caller then expires after a master observation,
// either in the retry pause or inside the master RPC, through both public APIs.
func TestMasterCensusKeepsCustomCallerDeadline(t *testing.T) {
old := singleFilerRetry
singleFilerRetry = time.Hour
defer func() { singleFilerRetry = old }()
for _, direct := range []bool{false, true} {
for _, stall := range []bool{false, true} {
t.Run(fmt.Sprintf("catalog=%v/inflight=%v", direct, stall), func(t *testing.T) {
m := &failedCensusMaster{stall: stall}
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
masterpb.RegisterSeaweedServer(server, m)
go func() { _ = server.Serve(lis) }()
t.Cleanup(server.Stop)
_, port, _ := net.SplitHostPort(lis.Addr().String())
c, _ := startConfigFiler(t, &configFiler{masters: []string{"127.0.0.1:9333." + port}})
warm, stopWarm := context.WithTimeout(context.Background(), 5*time.Second)
_, err = c.fc.GetFilerConfiguration(warm, &filerpb.GetFilerConfigurationRequest{})
stopWarm()
if err != nil {
t.Fatal(err)
}
custom := errors.New("caller-chosen master census deadline")
ctx, stop := context.WithTimeoutCause(context.Background(), 500*time.Millisecond, custom)
defer stop()
if direct {
cat, client, e := DialBCatalog(ctx, c.cfg)
err = e
if cat != nil || client != nil {
t.Fatal("incomplete census admitted a catalog")
}
} else {
err = c.CheckSingleFiler(ctx)
}
if m.calls.Load() != 1 || !errors.Is(err, ErrNotSingleFiler) || !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, custom) || !strings.Contains(err.Error(), "leader report") {
t.Fatalf("calls=%d caller deadline/cause or master diagnostics lost: %v", m.calls.Load(), err)
}
if !stall && !strings.Contains(err.Error(), "master census offline") {
t.Fatalf("lost stored Unavailable observation: %v", err)
}
})
}
}
}
// A malformed configured address is known before any census request. An
// earlier unavailable master must not hide it behind the startup window.
func TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus(t *testing.T) {
m := &nodesMaster{stall: true}
valid := startMaster(t, m)
f := &configFiler{masters: []string{valid, "m1:9333.notaport"}}
c, _ := startConfigFiler(t, f)
// Keep the cold gRPC handshake outside the check's short window.
setup, cancelSetup := context.WithTimeout(context.Background(), 5*time.Second)
_, setupErr := c.fc.GetFilerConfiguration(setup, &filerpb.GetFilerConfigurationRequest{}, grpc.WaitForReady(true))
cancelSetup()
if setupErr != nil {
t.Fatalf("warm filer configuration: %v", setupErr)
}
oldWait, oldAttempt := singleFilerWait, singleFilerAttempt
singleFilerWait, singleFilerAttempt = 100*time.Millisecond, 50*time.Millisecond
defer func() { singleFilerWait, singleFilerAttempt = oldWait, oldAttempt }()
err := c.CheckSingleFiler(context.Background())
m.mu.Lock()
calls := m.leaderCalls
m.mu.Unlock()
if calls != 0 {
t.Fatalf("invalid configured master reached census: %d master requests", calls)
}
if !errors.Is(err, ErrNotSingleFiler) || errors.Is(err, ErrSingleFilerWindowExpired) || status.Code(err) == codes.Unavailable || !strings.Contains(err.Error(), "m1:9333.notaport") || !strings.Contains(err.Error(), "rerun when they answer") {
t.Fatalf("invalid configured master must refuse before census: %v", err)
}
}
@@ -662,7 +662,7 @@ func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Reques
return
}
w.Header().Set("Location", snapshotOperationLocation(req.VolumeID, op))
writeChunkJSON(w, http.StatusAccepted, snapshotOperationPublicAnswer(req.VolumeID, op))
writeChunkJSON(w, http.StatusAccepted, snapshotOperationAdmissionAnswer(req.VolumeID, op))
}
func (s *StatusServer) handleChunkSnapshots(w http.ResponseWriter, r *http.Request) {
@@ -995,6 +995,7 @@ func (c *chunkControl) snapshotOperationAttempt(ctx context.Context, volumeID st
if err := json.Unmarshal(op.Result, &result); err != nil {
return result, err
}
result.Replayed = true
return result, nil
}
if op.State == "refused" {
@@ -25,6 +25,7 @@ func snapshotOperationTerminalAnswer(op chunkstore.SnapshotOperation) (chunkstor
}
var result chunkstore.SnapshotInfo
err := json.Unmarshal(op.Result, &result)
result.Replayed = true
return result, err, true
}
@@ -60,6 +61,20 @@ func snapshotOperationPublicAnswer(volume string, op chunkstore.SnapshotOperatio
return snapshotOperationAnswer{Handle: snapshotOperationLocation(volume, op), ID: op.ID, Target: op.VolumeID.String(), Verb: op.Verb, State: op.State, Result: result, Code: op.ErrorCode, Message: op.ErrorMessage, Status: op.ErrorStatus}
}
// Admission of an already succeeded create is a replay. Decorate only the
// response: the retained immutable outcome stays byte-identical.
func snapshotOperationAdmissionAnswer(volume string, op chunkstore.SnapshotOperation) snapshotOperationAnswer {
answer := snapshotOperationPublicAnswer(volume, op)
if op.Verb == "create" && op.State == "succeeded" {
var result map[string]json.RawMessage
if json.Unmarshal(op.Result, &result) == nil && result != nil {
result["replayed"] = json.RawMessage("true")
answer.Result = result
}
}
return answer
}
func snapshotOperationLocation(volume string, op chunkstore.SnapshotOperation) string {
q := url.Values{"volume": {volume}, "volume_id": {op.VolumeID.String()}, "request_id": {op.ID}, "verb": {op.Verb}, "instance": {op.Instance}, "sequence": {strconv.FormatUint(op.Sequence, 10)}}
return "/chunk/operations?" + q.Encode()
@@ -0,0 +1,95 @@
package volume
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
)
func TestSnapshotReplayFlagDoesNotRewriteOutcome(t *testing.T) {
ctx := context.Background()
dp, f, s, head := limitVolume(t)
if _, err := s.Write(0, bytes.Repeat([]byte{'X'}, 4096)); err != nil {
t.Fatal(err)
}
ctl := NewChunkControl(dp, f.Catalog, f.Ref).(*chunkControl)
defer ctl.closeSnapshotOperations(ctx)
server := chunkServer(t, ctl, true)
body := `{"volumeID":"v1","name":"daily","requestID":"replay-flag"}`
request := func() *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/chunk/snapshot", bytes.NewBufferString(body))
req.RemoteAddr = "127.0.0.1:5555"
req.Header.Set("Prefer", "respond-async")
w := httptest.NewRecorder()
server.chunkMux().ServeHTTP(w, req)
return w
}
first := request()
if first.Code != http.StatusAccepted {
t.Fatalf("first: %d %s", first.Code, first.Body)
}
var firstFields map[string]json.RawMessage
deadline := time.NewTimer(5 * time.Second)
defer deadline.Stop()
for {
poll := serve(t, server, http.MethodGet, first.Header().Get("Location"), "", "")
var answer struct {
State string `json:"state"`
Result json.RawMessage `json:"result"`
}
if err := json.Unmarshal(poll.Body.Bytes(), &answer); err != nil || poll.Code != http.StatusOK {
t.Fatalf("poll: %v %d %s", err, poll.Code, poll.Body)
}
if answer.State == "succeeded" {
raw := answer.Result
if err := json.Unmarshal(raw, &firstFields); err != nil {
t.Fatal(err)
}
if string(firstFields["replayed"]) != "false" {
t.Fatalf("first result: %s", raw)
}
break
}
if answer.State == "refused" || answer.State == "stalled" {
t.Fatalf("first: %+v", answer)
}
select {
case <-deadline.C:
t.Fatal("snapshot did not finish")
case <-time.After(time.Millisecond):
}
}
st, _ := f.Catalog.Store(f.Ref)
before, found, err := st.ReadSnapshotOperation(ctx, "replay-flag", "create")
if err != nil || !found {
t.Fatal(err)
}
beforeHead := head()
for i := 0; i < 2; i++ {
w := request()
var envelope struct {
Result map[string]json.RawMessage `json:"result"`
}
if err := json.Unmarshal(w.Body.Bytes(), &envelope); err != nil || w.Code != http.StatusAccepted {
t.Fatalf("replay: %v %d %s", err, w.Code, w.Body)
}
answer := envelope.Result
for key, value := range firstFields {
if key != "replayed" && !bytes.Equal(value, answer[key]) {
t.Errorf("replay changed %s: %s -> %s", key, value, answer[key])
}
}
if string(answer["replayed"]) != "true" {
t.Errorf("repeat %d has replayed=%s: %s", i, answer["replayed"], w.Body)
}
}
after, found, err := st.ReadSnapshotOperation(ctx, "replay-flag", "create")
if err != nil || !found || !reflect.DeepEqual(before, after) || !reflect.DeepEqual(beforeHead, head()) {
t.Fatalf("replay changed durable facts: before=%+v after=%+v err=%v", before, after, err)
}
}
+3 -1
View File
@@ -1196,7 +1196,9 @@ Notes:
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused for held host slots, pending urgent work or an earlier ticket is a wait, not a failure: no backoff or minimum spacing; it retries at the next poll in ticket order, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitEndsTheWait`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestCutPolicy_TicketOrderWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
| `INV-SNAPSHOT-ANSWER-COUNT-001` | Newly produced snapshot creation and listing answers omit the uncomputed chunk count; no manifest scan is added to answer a snapshot. | M9 snapshot answer projection (no transition change) | `core/frontend/chunkstore/control_types.go`, `api.go`; `core/host/volume/chunk_control.go` | `TestSnapshotAfter200MiBWritesOmitsUncomputedChunkCount` (`core/host/volume/snapshot_chunk_count_test.go`) | NONE (pure projection of the published snapshot; no authority or persisted format change) | STUB |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI reports filer/master transport failures as retryable remote_unavailable (exit 1), including census, dial, resolve and read failures; configuration refusals stay distinct. An absent v1.1 delete reports snapshot_not_found; its not_found receipt stays unchanged. | M9 client error projection; M4 census refusal, no transition change | `cmd/sw-block/chunk_transport.go` `chunkTransportFailure`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt` | SnapOps.Poll; r2.972 | STUB |
| `INV-CLI-DELETE-RETRY-001` | Only the final lease barrier after a committed volume-delete reservation permits retryable true/exit 75 at its horizon. A live-holder Reserve refusal requires stopping the volume first (not_admitted, non-retryable, exit 1). No lease guard is bypassed. | M9 delete admission result projection | `cmd/sw-block/chunk_volume_delete.go` `authorityErr`; `cmd/sw-block/chunk.go` `chunkResult` | `TestVolumeDeleteAdmissionRetryAnswer`; `TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted` | MoveAdmission.DelRead; MoveAdmission.DelMark (unchanged guards) | STUB |
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI reports filer/master transport failures as retryable remote_unavailable (exit 75), including census, dial, resolve and read failures; configuration refusals stay distinct. An absent v1.1 delete reports snapshot_not_found; its not_found receipt stays unchanged. | M9 client error projection; M4 census refusal, no transition change | `cmd/sw-block/chunk_transport.go` `chunkTransportFailure`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt` | SnapOps.Poll; r2.972 | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-003` | Non-plain detach and snapshot admission obey a positive total --timeout. Snapshot observation keeps the same ID with bounded calls and no total deadline. Manual cut and plain detach use the separate inactivity-window contract. | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkLoopEndsAtTheTimeout`, `TestChunkLoopHeldProgressReadSendsNoRequestAfterTheTimeout`, `TestChunkLoopSlowAnswersAreBoundedByTheTimeout`, `TestChunkNonPositiveTimeoutIsRefused` (`cmd/sw-block`) | — | ACTIVE |
@@ -11,3 +11,39 @@ v1.0.1 gives two refusals a code of their own:
for scripts that check the exit status: exit 2 now means only a malformed command or another resolve failure.
See [restore a snapshot into a new volume](../standalone-deployment.md#restoring-a-snapshot-into-a-new-volume).
## v1.1.1 corrections: retry advice and snapshot replay
For every `ops chunk` command, a remote transport outage answers
`remote_unavailable`, `retryable: true`, exit **75** (temporary failure).
The message advises repeating the same operation after the remote is reachable;
keep the same request ID when the operation has one. This includes a filer
that is unavailable during the single-filer check or after snapshot-delete
admission. An actual configuration refusal remains `bad_request`, exit 2.
A caller's own deadline is `deadline_exceeded`, retryable, exit 1; its explicit
cancellation is `canceled`, not a remote outage.
| Answer | Retryable | Exit | Action |
|---|---|---|---|
| `remote_unavailable` | true | 75 | Restore connectivity, then repeat the same operation/request ID. |
| volume-delete Reserve refused by a live holder, even with a dated horizon | false | 1 | Stop the volume first; a serving holder can keep renewing that horizon. |
| volume-delete final lease barrier after reservation committed, with a valid horizon | true | 75 | Retry the same `--request-id` after the printed horizon. |
| volume-delete `not_admitted`: restart required | false | 1 | Restart the authority to settle uncertain persistence; preserve the request ID when resuming. |
| volume-delete `not_admitted`: authority records skipped | false | 1 | Recover the skipped authority records before resuming; lease absence is unknown. |
| volume-delete `not_admitted`: live holder without a horizon | false | 1 | Stop the holder using the stated procedure before resuming. |
| snapshot-delete `snapshot_has_dependents` | false | 1 | Remove dependent volumes or release their dependency before resuming the same request ID. |
| caller `deadline_exceeded` | true | 1 | Inspect progress and the chosen bound; preserve the request ID before resuming. |
| caller `canceled` | false | 1 | The caller interrupted this attempt. |
A dependency refusal does not become an immutable delete outcome: the operation
remains resumable after the dependency is released, but automatic retries cannot
remove that prerequisite. A first snapshot creation reports `replayed: false`;
a repeat admission of the same successful request reports `replayed: true`.
The replay flag decorates the response only. The retained outcome, snapshot
identity, creation time and HEAD remain unchanged. Ordinary GET observation of
the original operation retains its original result; it is not a new admission.
The manual cut observation protocol keeps its own `outcome_unknown`, `cut_busy`
and `cut_stalled` answers; this correction does not change that admission or
observation protocol. HTTP snapshot/detach error bodies are relayed unchanged;
the temporary exit code and retry advice on stderr follow the same rule.
+3 -3
View File
@@ -34,7 +34,7 @@ cmd/sparrow/s5_bootstrap.go runS5Bootstrap context.WithTimeout 1 per-call NONE:
cmd/sparrow/s7_restart_smoke.go runS7RestartSmoke context.WithTimeout 1 per-call NONE: no model row maps this file yet test-harness binary: one bounded step
cmd/sparrow/s7_restart_smoke.go runS7RestartSmoke time.Now().Add 1 per-call NONE: no model row maps this file yet test-harness binary: one bounded wait
cmd/sw-block/catalog_snapshot_operation.go chunkCatalogSnapshotDeleteAnswer time.After 1 control-timer NONE: no model row maps this file yet retry pause inside the snapshot-delete command's window
cmd/sw-block/chunk.go refuseUnlessSingleFilerWithin context.WithTimeout 1 per-call CutTime.Poll the single-filer start check, bounded by --timeout and by its caller's pass
cmd/sw-block/chunk.go refuseUnlessSingleFilerWithin context.WithTimeoutCause 1 per-call CutTime.Poll the single-filer start check, bounded by --timeout and by its caller's pass
cmd/sw-block/chunk.go chunkPost time.Now().Add 1 pending-fix CutTime.Poll remaining snapshot/detach HTTP waiter bound; fix #979 (manual cuts use chunkObserveCut)
cmd/sw-block/chunk.go chunkPostUntil context.WithDeadline 1 pending-fix CutTime.Poll remaining snapshot/detach HTTP waiter bound; fix #979 (manual cuts use chunkObserveCut)
cmd/sw-block/chunk.go chunkSnapshot time.Now().Add 1 control-timer CutTime.Poll snapshot expiry: a timestamp (validity, expiry or due time), not a wait
@@ -142,8 +142,8 @@ core/frontend/chunkstore/layout_remote.go headStep context.WithTimeout 1 per-cal
core/frontend/chunkstore/maintenance_request.go maintenanceCall context.WithTimeout 1 per-call CutTime.CallTimeout one maintenance read request
core/frontend/chunkstore/maintenance_request.go maintenanceCall time.After 1 control-timer CutTime.CallTimeout retry pause after a timed-out maintenance read
core/frontend/chunkstore/maintenance_request.go maintenanceMutation context.WithTimeout 1 per-call CutTime.CallTimeout one maintenance mutation request
core/frontend/chunkstore/single_filer.go SWFS.CheckSingleFiler context.WithTimeout 1 per-call NONE: no model row maps this file yet one RPC or request
core/frontend/chunkstore/single_filer.go SWFS.CheckSingleFiler time.After 1 control-timer NONE: no model row maps this file yet single-filer check retry pause
core/frontend/chunkstore/single_filer.go SWFS.CheckSingleFiler context.WithTimeoutCause 1 per-call NONE: no model row maps this file yet one RPC or request
core/frontend/chunkstore/single_filer.go SWFS.checkSingleFiler time.After 1 control-timer NONE: no model row maps this file yet single-filer check retry pause
core/frontend/chunkstore/single_filer.go SWFS.singleFilerRound context.WithTimeout 1 per-call NONE: no model row maps this file yet one RPC or request
core/frontend/chunkstore/single_filer.go SWFS.singleFilerRound context.WithTimeout 2 per-call NONE: no model row maps this file yet one RPC or request
core/frontend/chunkstore/single_filer.go SWFS.singleFilerRound context.WithTimeout 3 per-call NONE: no model row maps this file yet one RPC or request
Can't render this file because it contains an unexpected character in line 47 and column 123.
+7 -3
View File
@@ -539,8 +539,11 @@ volume's object listing or verification report to check its remaining objects.
**If you sealed and then stopped `blockvolume` with a signal, keep it stopped**
and disable its unit so it cannot restart. Run step 4 without restarting,
revoking or waiting for an ACK. Before the lease horizon it exits 1 with typed
`code: not_admitted` and a message naming `live until <T>`; nothing is deleted.
revoking or waiting for an ACK. A Reserve refusal exits 1 with non-retryable
`code: not_admitted`, `stop the volume first` and `live until <T>`; nothing is
persisted or deleted. Because this recovery has already stopped the holder,
keep it stopped and wait until T. Only the final barrier after the reservation
is committed exits 75 with retryable `not_admitted` and the same-ID horizon advice.
Retry with the **same request id** at or after T until it completes, within the
original horizon plus a bounded margin. Do not issue a start or move during the
wait: a new lease starts a new wait. A restarted sealed holder is replay-only,
@@ -610,7 +613,8 @@ admission. Permanent and lineage errors are not converted to retryable errors.
| `sw-block ops chunk detach: plain_detach_busy: durable: plain detach requires idle frontend I/O` | I/O was in flight; nothing changed | Stop the writer, retry step 3 |
| detach answers `detach_aborted` | Nothing was published; the volume serves here again | Retry step 3 |
| detach answers `outcome_unknown` | The seal may have landed; I/O stays stopped | Retry step 3: it settles the outcome |
| volume-delete: `not_admitted: ... workspace: deletion refused before persistence: workspace delete: live until <time>: ...` | The volume's lease is still live: it was not revoked and acknowledged, or its lease horizon has not passed; nothing was persisted | "Delete a volume", step 2, then run it again after the horizon |
| volume-delete Reserve: `not_admitted` (non-retryable, exit 1): `stop the volume first: ... deletion refused before persistence: ... live until <time>: ...` | A live-holder reservation was refused; nothing was persisted. Waiting alone cannot stop a serving holder renewing its horizon. | "Delete a volume", stop procedure first. If the holder is already stopped, keep it stopped and resume the same request after the printed horizon. |
| volume-delete final barrier: `not_admitted` (retryable, exit 75), `retry the same --request-id after <time>` | The reservation is committed and blocks new grants; waiting out the remaining lease is sufficient. | Repeat the same request ID after the printed horizon. |
| volume-delete: `snapshot_has_dependents: ... layout: a snapshot has dependents: snapshot "s1" has 1` | A restored volume still depends on that snapshot (ordinary snapshots never refuse a delete: they are deleted with the volume). The delete had already reserved the volume: it does not serve again (`ops workspace show` answers `workspace: volume is being deleted`, exit 1), and nothing was deleted yet (`TestOpsChunkVolumeDeleteRefusedByDependentsLeavesTheVolumeReserved`) | Delete the restored volume, or release its dependence, then run the same volume-delete again with the same `--request-id` ("Delete a volume", step 3) |
| snapshot: `snapshot_exists ... this request's attempt was aborted; delete the name to reuse it` | An earlier attempt of this request did not finish and was swept | `snapshot-delete` the name, then take the snapshot again |
| snapshot: `snapshot_deleting ... is being deleted; wait for the delete to finish, then reuse the name` | The request was repeated while its snapshot is being deleted | Wait for the delete to finish; take the snapshot again if it is still wanted |