Merge main (#955) into the snapshot operations

The holder's maintenance now consumes a published delete intent, so a
delete behind an earlier one resumes once its intent is consumed. The
model-code trace keeps both sides' new rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-02 08:41:21 -08:00
commit fcf6b0ec41
80 files changed
+4447 -201

No files matched your search

+3
View File
@@ -140,3 +140,6 @@ cmd/sw-block/snapshot_operation.go SnapOps.Send
core/host/volume/snapshot_operation.go SnapOps.Start
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send
core/storage/wal_admission_fast.go WALHold.FastArrive
core/storage/wal_admission_fast.go WALHold.FastReEnter
core/storage/wal_admission_fast.go WALHold.FastResubmit
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
140 cmd/blockvolume/snapshot_operation_shutdown.go
141 core/frontend/chunkstore/snapshot_delete_operation.go
142 core/storage/wal_admission_fast.go
143 core/storage/wal_admission_fast.go
144 core/storage/wal_admission_fast.go
145
@@ -58,13 +58,13 @@ func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cle
diagnostic = "HEAD generation not read: HEAD absent"
}
defer func() {
durable.ReportMaintenance(ctx, durable.MaintenancePassStatus{SkipReason: head.ListRetirementSkipReason(), Planned: int64(res.Planned), Removed: int64(res.Removed), PlannedChunks: int64(res.PlannedChunks), PlannedRoots: int64(res.PlannedRoots), PlannedSegments: int64(res.PlannedSegments), RemovedChunks: int64(res.Removed - res.Roots - res.Segments), RemovedRoots: int64(res.Roots), RemovedSegments: int64(res.Segments), HeadGen: head.Gen, HeadGenError: diagnostic})
durable.ReportMaintenance(ctx, durable.MaintenancePassStatus{SkipReason: head.ListRetirementSkipReason(), Planned: int64(res.Planned), Removed: int64(res.Removed), PlannedChunks: int64(res.PlannedChunks), PlannedRoots: int64(res.PlannedRoots), PlannedSegments: int64(res.PlannedSegments), RemovedChunks: int64(res.Removed - res.Roots - res.Segments - res.Lists), RemovedRoots: int64(res.Roots), RemovedSegments: int64(res.Segments), PlannedLists: int64(res.PlannedLists), RemovedLists: int64(res.Lists), HeadGen: head.Gen, HeadGenError: diagnostic})
}()
var rerr error
res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s)
return rerr
})
log.Printf("blockvolume: maintenance volume=%s clean=%s shards=%d planned=%d removed=%d removedChunks=%d removedRoots=%d removedSegments=%d plannedChunks=%d plannedRoots=%d plannedSegments=%d", vol, session, res.Shards, res.Planned, res.Removed, res.Removed-res.Roots-res.Segments, res.Roots, res.Segments, res.PlannedChunks, res.PlannedRoots, res.PlannedSegments)
log.Printf("blockvolume: maintenance volume=%s clean=%s shards=%d planned=%d removed=%d removedChunks=%d removedRoots=%d removedSegments=%d plannedChunks=%d plannedRoots=%d plannedSegments=%d plannedLists=%d removedLists=%d", vol, session, res.Shards, res.Planned, res.Removed, res.Removed-res.Roots-res.Segments-res.Lists, res.Roots, res.Segments, res.PlannedChunks, res.PlannedRoots, res.PlannedSegments, res.PlannedLists, res.Lists)
// A cleaning refused because HEAD moved away from this holder is
// the same fence a cut would see: classified so the provider latches.
return chunkstore.LayoutErr(err)
+8
View File
@@ -44,6 +44,7 @@ import (
)
type flags struct {
walHold frontend.WALHoldConfig
logLevel string
cpuProfileDir string
memoryLimitMiB int64
@@ -193,6 +194,9 @@ func parseFlags(args []string) (flags, error) {
func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) (flags, error) {
var f flags
fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError)
writePolicy := frontend.DefaultWALHoldConfig()
fs.DurationVar(&f.walHold.MaxHold, "wal-hold-timeout", writePolicy.MaxHold, "maximum per-command WAL-pressure hold; positive and at least 5s below --host-io-timeout")
fs.DurationVar(&f.walHold.HostIOTimeout, "host-io-timeout", writePolicy.HostIOTimeout, "operator-declared host I/O timeout (host_io_timeout); set to match your hosts when changing io_timeout")
fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds")
fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit or when it cannot be derived (one WARN says why); 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set")
fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)")
@@ -286,6 +290,9 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error))
if err := fs.Parse(args); err != nil {
return flags{}, err
}
if err := f.walHold.Validate(); err != nil {
return flags{}, err
}
if err := logging.ValidateLevel(f.logLevel); err != nil {
return flags{}, err
}
@@ -734,6 +741,7 @@ func runVolume(f flags, exits *processExit) int {
blocks, blockSize, geometryErr := durableCreateGeometry(f)
var dp *durable.DurableProvider
cfg := durable.ProviderConfig{
WALHold: f.walHold,
RecoveryProgress: h.ReportRecoveryProgress,
AuthorityWait: h.ReportAuthorityWait,
Impl: durable.ImplName(f.durableImpl),
@@ -9,9 +9,11 @@
"plannedChunks": 0,
"plannedRoots": 0,
"plannedSegments": 0,
"plannedLists": 0,
"removedChunks": 0,
"removedRoots": 0,
"removedSegments": 0,
"removedLists": 0,
"error": "",
"headGenError": "",
"headGen": 0
@@ -0,0 +1,42 @@
package main
import (
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
func TestParseFlagsWALHoldHostTimeout(t *testing.T) {
for _, tc := range []struct {
name string
args []string
hold, host time.Duration
valid bool
}{
{"defaults", nil, 25 * time.Second, 30 * time.Second, true},
{"explicit equality", []string{"--wal-hold-timeout", "10s", "--host-io-timeout", "15s"}, 10 * time.Second, 15 * time.Second, true},
{"host lowered without hold", []string{"--host-io-timeout", "29s"}, 0, 0, false},
{"hold above margin", []string{"--wal-hold-timeout", "25.000000001s"}, 0, 0, false},
{"zero hold", []string{"--wal-hold-timeout", "0"}, 0, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
args := append(requiredBlockvolumeArgs(), tc.args...)
f, err := parseFlags(args)
if tc.valid {
if err != nil {
t.Fatal(err)
}
if f.walHold.MaxHold != tc.hold || f.walHold.HostIOTimeout != tc.host {
t.Fatalf("parsed policy: %+v", f.walHold)
}
} else {
var invalid *frontend.WALHoldConfigError
if !errors.As(err, &invalid) {
t.Fatalf("want typed startup refusal, got %v", err)
}
}
})
}
}
+1 -1
View File
@@ -333,7 +333,7 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
case errors.Is(err, context.DeadlineExceeded):
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))
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrQueueFull))
default:
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
}
+1
View File
@@ -438,6 +438,7 @@ func layoutCode(err error) string {
err error
code string
}{
{layout.ErrQueueFull, chunkstore.CodeQueueFull},
{layout.ErrNoSnapshot, "snapshot_not_found"},
{layout.ErrSnapshotDeleteNeedsOperation, "snapshot_delete_requires_operation"},
{layout.ErrHasDependents, "snapshot_has_dependents"},
@@ -0,0 +1,22 @@
package main
import (
"bytes"
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
func TestLayoutQueueFullHasItsOwnRetryableCode(t *testing.T) {
err := fmt.Errorf("publish: %w", layout.ErrQueueFull)
if got := layoutCode(err); got != "queue_full" {
t.Fatalf("code=%q, want queue_full", got)
}
var out, diag bytes.Buffer
exit := chunkResult("snapshot-delete", nil, err, &out, &diag)
body := chunkErrorOut(t, out.String())
if exit != chunkExitFailed || body.Code != "queue_full" || !body.Retryable {
t.Fatalf("exit=%d body=%+v", exit, body)
}
}
+74 -18
View File
@@ -113,7 +113,7 @@ type finalizeHost struct {
// back to v1.0.x works only before it: afterwards a v1.0.x master or holder
// refuses the store (an expected refusal, not damage). The master refuses
// it while any registered host does not read level 1, naming each one.
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int) {
fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
@@ -129,6 +129,9 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
if *jsonOut {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
@@ -223,40 +226,93 @@ func finalizeHosts(md map[string]string) []finalizeHost {
return hosts
}
// retireAnswer is retire-host's --json answer, one shape for every outcome.
// Result is retired, refused, unavailable or failed; Reason the master's
// typed reason (or the gRPC code, "" on success); Volumes the volumes the
// host still holds when the retire is refused for them (empty otherwise).
type retireAnswer struct {
Result string `json:"result"`
Reason string `json:"reason"`
Server string `json:"server"`
Volumes []string `json:"volumes"`
Message string `json:"message"`
}
// runClusterRetireHost removes a registered host from the node inventory.
// The master refuses it while the host holds a lease or an assignment.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
// The master refuses it while the host holds a lease or an assignment. Exit
// codes as finalize-format's: 0 retired, 2 refused, 75 the master could not
// be reached (EX_TEMPFAIL), 1 any other failure, a usage error included.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
server := fs.String("server", "", "the server id to retire (required)")
confirm := fs.String("confirm", "", "the same server id again (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s]")
return ops.VolumeStatusExitInvalid
// Declared for parsing and help only; the mode is read from the
// arguments as a whole, so a bad option in any position cannot half-parse it.
fs.Bool("json", false, "print the typed answer as JSON: result, reason, server, volumes, message")
jsonMode := jsonRequested(args)
answer := retireAnswer{Volumes: []string{}}
defer func() {
if jsonMode {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host: JSON output:", err)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
fail := func(result, reason, msg string, code int) int {
answer.Result, answer.Reason, answer.Message = result, reason, msg
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", msg)
return code
}
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s] [--json]")
answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master, --server and --confirm are required"
return finalizeExitFailed
}
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", err)
return ops.VolumeStatusExitUnhealthy
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", status.Convert(err).Message())
return clusterExit(err)
msg := status.Convert(err).Message()
reason, md := lifecycleclient.ReasonDetail(err)
if reason == "" {
reason = status.Code(err).String()
}
switch status.Code(err) {
case codes.FailedPrecondition:
answer.Volumes = retireVolumes(md)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
}
return fail("failed", reason, msg, finalizeExitFailed)
}
fmt.Fprintf(stdout, "host %s retired\n", *server)
return ops.VolumeStatusExitOK
answer.Result, answer.Message = "retired", "host retired from the node inventory"
if !jsonMode {
fmt.Fprintf(stdout, "host %s retired\n", *server)
}
return finalizeExitOK
}
// clusterExit maps a master error to the CLI's exit codes: a malformed
// request is 2 (as a usage error); a refusal or an unreachable master is 1.
func clusterExit(err error) int {
if status.Code(err) == codes.InvalidArgument {
return ops.VolumeStatusExitInvalid
// retireVolumes reads the held volumes from the refusal's typed metadata,
// sorted.
func retireVolumes(md map[string]string) []string {
vols := []string{}
for k := range md {
if v, ok := strings.CutPrefix(k, lifecycleclient.VolumeMetadataPrefix); ok {
vols = append(vols, v)
}
}
return ops.VolumeStatusExitUnhealthy
sort.Strings(vols)
return vols
}
@@ -142,3 +142,111 @@ func TestClusterFinalizeFormatBadOptionAnswersJSONWithoutAnRPC(t *testing.T) {
t.Fatalf("a malformed command sent %d finalize RPCs", calls)
}
}
// retire-host's answer is typed like finalize-format's: exit 0 retired, 2
// refused (the held volumes from the master's typed metadata, never its
// message text), 75 the master could not be reached, 1 any other failure or
// a usage error; --json prints the same keys for every outcome.
func TestClusterRetireHostTypedAnswer(t *testing.T) {
holds := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"),
lifecycleclient.ReasonHostHoldsWork, map[string]string{
lifecycleclient.VolumeMetadataPrefix + "v2": "busy",
lifecycleclient.VolumeMetadataPrefix + "v1": "busy",
}).Err()
for _, tc := range []struct {
name string
err error
dialErr error
args []string
exit int
result string
reason string
volumes []string
}{
{name: "retired", exit: 0, result: "retired"},
{name: "holds-work", err: holds, exit: 2, result: "refused", reason: lifecycleclient.ReasonHostHoldsWork, volumes: []string{"v1", "v2"}},
{name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"},
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"},
{name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"},
} {
t.Run(tc.name, func(t *testing.T) {
calls := 0
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
calls++
if tc.err != nil {
return nil, tc.err
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
withClusterMaster(t, f)
if tc.dialErr != nil {
clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr }
}
args := tc.args
if args == nil {
args = []string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy", "--json"}
}
var out, errOut bytes.Buffer
code := run(args, &out, &errOut)
if code != tc.exit {
t.Fatalf("exit %d, want %d (stderr %q)", code, tc.exit, errOut.String())
}
var keys map[string]json.RawMessage
if err := json.Unmarshal(out.Bytes(), &keys); err != nil {
t.Fatalf("--json output %q: %v", out.String(), err)
}
var names []string
for k := range keys {
names = append(names, k)
}
sort.Strings(names)
if want := []string{"message", "reason", "result", "server", "volumes"}; !reflect.DeepEqual(names, want) {
t.Fatalf("--json keys %v, want %v for every outcome", names, want)
}
var a retireAnswer
if err := json.Unmarshal(out.Bytes(), &a); err != nil {
t.Fatal(err)
}
if a.Result != tc.result || a.Reason != tc.reason {
t.Fatalf("answer %+v, want result %q reason %q", a, tc.result, tc.reason)
}
if want := tc.volumes; want == nil && len(a.Volumes) != 0 || want != nil && !reflect.DeepEqual(a.Volumes, want) {
t.Fatalf("volumes %v, want %v", a.Volumes, want)
}
if tc.name == "usage" && calls != 0 {
t.Fatalf("a usage error sent %d retire RPCs", calls)
}
})
}
}
// failingWriter refuses every write: a stdout the JSON answer cannot reach.
type failingWriter struct{}
func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") }
// A --json answer that cannot be written fails the command: a script that
// reads it must not see a successful exit without an answer.
func TestClusterJSONOutputFailureFailsTheCommand(t *testing.T) {
f := &fakeClusterMaster{
finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return &control.FinalizeFormatResponse{FormatLevel: 1}, nil
},
retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
},
}
withClusterMaster(t, f)
for _, args := range [][]string{
{"cluster", "finalize-format", "--master", "m:1", "--json"},
{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c", "--json"},
} {
var errOut bytes.Buffer
if code := run(args, failingWriter{}, &errOut); code != 1 {
t.Fatalf("%v with an unwritable stdout: exit %d, want 1 (stderr %q)", args, code, errOut.String())
}
}
}
@@ -76,7 +76,7 @@ func TestClusterFinalizeFormat(t *testing.T) {
}
}
// retire-host sends the server id and its confirm; a refusal exits 1.
// retire-host sends the server id and its confirm; a refusal exits 2.
func TestClusterRetireHost(t *testing.T) {
var got *control.RetireHostRequest
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
@@ -91,11 +91,11 @@ func TestClusterRetireHost(t *testing.T) {
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") {
t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 2 {
t.Fatalf("retire without --confirm: exit %d, want 2", code)
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 1 {
t.Fatalf("retire without --confirm: exit %d, want 1", code)
}
}
+1
View File
@@ -292,6 +292,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced
if answer != nil {
answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode()
if !p.GetAdmitted() {
answer.Reason = p.GetReasonCode()
if answer.Code == "" {
answer.Code = "Unknown"
} // older servers did not export a refusal code
@@ -173,3 +173,27 @@ func TestWorkspaceForceMoveJSONCarriesOnlyTheTypedReason(t *testing.T) {
})
}
}
// force-move --dry-run --json carries the preview's typed reason (the reason
// the move itself would carry); a refusal with only message text carries
// none.
func TestWorkspaceForceMovePreviewJSONCarriesTheTypedReason(t *testing.T) {
for _, tc := range []struct {
name string
preview *control.WorkspaceMovePreview
want string
}{
{"typed", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0", Code: "FailedPrecondition", ReasonCode: lifecycleclient.ReasonBinaryTooOld}, lifecycleclient.ReasonBinaryTooOld},
{"text-only", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0 (binary_too_old)", Code: "FailedPrecondition"}, ""},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeWorkspace{status: wsHolder(), preview: tc.preview}
addr, _ := startFakeWorkspace(t, f)
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run", "--json"))
var a workspaceForceMoveAnswer
if json.Unmarshal([]byte(out), &a) != nil || a.Admitted || a.Code != "FailedPrecondition" || a.Reason != tc.want {
t.Fatalf("exit=%d out=%q err=%q answer=%+v; want reason %q", code, out, errOut, a, tc.want)
}
})
}
}
@@ -20,9 +20,11 @@ type CleanResult struct {
PlannedChunks int
PlannedRoots int
PlannedSegments int
PlannedLists int
Removed int
Roots int
Segments int
Lists int
}
// The cursor is scheduling only: after a timeout a new session re-plans tags
@@ -35,6 +37,7 @@ type cleanCursor struct {
after string
segmentAfter string
poolAfter string
listAfter string
}
func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor {
@@ -51,8 +54,10 @@ func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor {
return cur
}
// RemoveUnreachableAll resumes a bounded cleaning. Roots are removed before
// segments, then chunks; interruptions leave only unnamed content behind.
// RemoveUnreachableAll resumes a paged full sweep. Roots are removed before
// segments, then chunks and unreachable list pages. This remains proportional
// to the namespace, not the number of changes; interruptions leave unnamed
// content for a later pass.
func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me layout.HolderID, session string) (res CleanResult, err error) {
cur := c.cleaningCursor(v)
if !cur.mu.TryLock() {
@@ -164,6 +169,39 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
}
}
}
cur.phase, cur.shard, cur.after, cur.poolAfter = 0, "", "", ""
// Retire metadata only after the data sweep. A current continuation is
// protected by Cleaner.Page's complete-chain reachability check; being in
// an abandoned producer's chain is never removal authority.
for {
if err := ctx.Err(); err != nil {
return res, err
}
entries, err := c.f.ListEntries(ctx, path.Join(c.base, v.Dir(), layout.ListDir), "", cur.listAfter, cleanPage)
if err != nil {
return res, err
}
names := make([]string, 0, len(entries))
for _, e := range entries {
if e == nil || e.IsDirectory || e.Name <= cur.listAfter {
return res, layout.ErrCorrupt
}
names = append(names, e.Name)
}
res.Planned += len(names)
res.PlannedLists += len(names)
out, err := cleaner.Page(ctx, layout.ListDir, 0, names)
res.Removed += len(out.Names)
res.Lists += len(out.Names)
if out.After != "" {
cur.listAfter = path.Base(out.After)
}
if err != nil {
return res, err
}
if uint32(len(names)) < cleanPage {
break
}
}
cur.phase, cur.shard, cur.after, cur.poolAfter, cur.listAfter = 0, "", "", "", ""
return res, nil
}
@@ -0,0 +1,22 @@
package chunkstore
import (
"context"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// CleanSnapshotDeletePage resumes one persisted snapshot-delete page. pending
// reports whether HEAD still names work, only when err is nil. The driver does
// not claim a holder, infer a target from a receipt, or enumerate the namespace.
func (c *BCatalog) CleanSnapshotDeletePage(ctx context.Context, v VolumeRef) (pending bool, err error) {
s, r, err := c.open(v)
if err != nil {
return false, err
}
h, err := layout.RunConsumeSnapshotDeleteIntent(ctx, s, r)
if err != nil {
return false, err
}
return h.List != nil, nil
}
@@ -0,0 +1,167 @@
package chunkstore
import (
"context"
"errors"
"path"
"sort"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
type intentNamespaceProbe struct {
Filer
calls int
}
var errIntentCursorInterrupted = errors.New("interrupted intent cursor update")
type intentCursorFault struct {
Filer
afterWrite bool
armed bool
deletes map[string]int
}
func (f *intentCursorFault) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
if e.Name == layout.HeadName && f.armed {
f.armed = false
if f.afterWrite {
if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil {
return err
}
}
return errIntentCursorInterrupted
}
return f.Filer.UpdateEntry(ctx, dir, e, expected)
}
func (f *intentCursorFault) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
if err == nil && path.Base(path.Dir(dir)) == layout.PoolDir {
f.deletes[name]++
}
return err
}
func TestCatalogIntentCursorInterruptAndLostReply(t *testing.T) {
for _, afterWrite := range []bool{false, true} {
name := "before cursor write"
if afterWrite {
name = "lost reply after cursor write"
}
t.Run(name, func(t *testing.T) {
ctx := context.Background()
c, v, s, orphans := pendingIntentCatalog(t)
before, _, err := s.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
fault := &intentCursorFault{Filer: c.f, armed: true, afterWrite: afterWrite, deletes: map[string]int{}}
c.f = fault
pending, err := c.CleanSnapshotDeletePage(ctx, v)
if afterWrite {
if err != nil || !pending {
t.Fatalf("lost reply not settled: pending=%v err=%v", pending, err)
}
} else if !errors.Is(err, errIntentCursorInterrupted) {
t.Fatalf("unfinished cursor update became success: pending=%v err=%v", pending, err)
}
current, _, readErr := s.ReadHead(ctx)
if readErr != nil || (!afterWrite && current.List.Ref != before.List.Ref) || (afterWrite && current.List.Ref == before.List.Ref) {
t.Fatalf("wrong persisted continuation: before=%+v after=%+v err=%v", before.List, current.List, readErr)
}
if present(t, s, orphans[0]) || !present(t, s, orphans[1]) {
t.Fatal("effects did not precede the cursor write, or the unread tail was executed")
}
restarted, err := NewBCatalog(fault, c.b, c.base)
if err != nil {
t.Fatal(err)
}
if !afterWrite {
if pending, err := restarted.CleanSnapshotDeletePage(ctx, v); err != nil || !pending {
t.Fatalf("unfinished page retry: pending=%v err=%v", pending, err)
}
}
if pending, err := restarted.CleanSnapshotDeletePage(ctx, v); err != nil || pending {
t.Fatalf("tail retry: pending=%v err=%v", pending, err)
}
for _, n := range orphans {
if present(t, s, n) || fault.deletes[n.String()] != 1 {
t.Fatalf("chunk %s: present=%v delete_effects=%d", n, present(t, s, n), fault.deletes[n.String()])
}
}
})
}
}
func (p *intentNamespaceProbe) ListEntries(context.Context, string, string, string, uint32) ([]*filerpb.Entry, error) {
p.calls++
return nil, errors.New("intent consumer must not enumerate unrelated namespace objects")
}
func pendingIntentCatalog(t *testing.T) (*BCatalog, VolumeRef, *LayoutStore, []layout.ChunkName) {
t.Helper()
ctx := context.Background()
c, v, s, orphans := cleanFixture(t)
h, _, err := s.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
stamped, _, err := h.StampSnapshotGenerations()
if err != nil {
t.Fatal(err)
}
if err := s.UpdateHead(ctx, h.Gen, stamped, layout.CauseSnapshotUnchanged); err != nil {
t.Fatal(err)
}
h, _, err = s.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
p := layout.ListPage{VolumeID: v.ID, Kind: layout.ListSnapshotDeleteIntent, Producer: "delete-s", Generation: h.Gen + 1, Pages: 1,
Target: &layout.SnapshotTarget{Name: "s", Gen: h.Snapshots["s"].Gen}, Entries: []string{orphans[1].Path()}}
tail, err := layout.StageSnapshotDeletePage(ctx, s, h.Gen, p)
if err != nil {
t.Fatal(err)
}
p.Pages, p.Next = 2, &tail
p.Entries = []string{h.Snapshots["s"].Root.Path(), orphans[0].Path()}
sort.Strings(p.Entries)
head, err := layout.StageSnapshotDeletePage(ctx, s, h.Gen, p)
if err != nil {
t.Fatal(err)
}
cursor := layout.ListCursor{Ref: head, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target}
if _, err := layout.RunDeleteSnapshotWithIntent(ctx, s, h.Gen, cursor); err != nil {
t.Fatal(err)
}
return c, v, s, orphans
}
func TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan(t *testing.T) {
ctx := context.Background()
c, v, s, orphans := pendingIntentCatalog(t)
probe := &intentNamespaceProbe{Filer: c.f}
c.f = probe
pending, err := c.CleanSnapshotDeletePage(ctx, v)
if err != nil || !pending || present(t, s, orphans[0]) || !present(t, s, orphans[1]) {
t.Fatalf("first page: pending=%v first=%v tail=%v err=%v", pending, present(t, s, orphans[0]), present(t, s, orphans[1]), err)
}
// Reconstruct the entire catalog; the next page comes only from HEAD, not
// from the previous process, a receipt, or a volatile scheduling cursor.
restarted, err := NewBCatalog(probe, c.b, c.base)
if err != nil {
t.Fatal(err)
}
pending, err = restarted.CleanSnapshotDeletePage(ctx, v)
if err != nil || pending || present(t, s, orphans[1]) || probe.calls != 0 {
t.Fatalf("resume: pending=%v tail=%v namespace_calls=%d err=%v", pending, present(t, s, orphans[1]), probe.calls, err)
}
h, _, err := s.ReadHead(ctx)
if err != nil || h.Current == nil || h.Holder != cleanHolder.Holder || h.ClaimID != cleanHolder.ClaimID {
t.Fatalf("consumer changed ownership/current root: %+v %v", h, err)
}
}
@@ -0,0 +1,116 @@
package chunkstore
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// Both consumers finish effects against the same cursor before either can
// publish. The second CAS is delivered only after the first has persisted.
type twoIntentConsumers struct {
Filer
mu sync.Mutex
calls, refused int
firstReady, secondReady, firstWritten chan struct{}
}
func (f *twoIntentConsumers) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
if e.Name != layout.HeadName {
return f.Filer.UpdateEntry(ctx, dir, e, expected)
}
f.mu.Lock()
f.calls++
call := f.calls
f.mu.Unlock()
if call == 1 {
close(f.firstReady)
defer close(f.firstWritten)
select {
case <-f.secondReady:
case <-ctx.Done():
return ctx.Err()
}
} else if call == 2 {
close(f.secondReady)
select {
case <-f.firstWritten:
case <-ctx.Done():
return ctx.Err()
}
}
err := f.Filer.UpdateEntry(ctx, dir, e, expected)
if errors.Is(err, ErrPrecondition) {
f.mu.Lock()
f.refused++
f.mu.Unlock()
}
return err
}
func TestCatalogTwoIntentConsumersSettleARefusedCursorCAS(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
c, v, cost := largeIntentCatalog(t, 1024)
f := &twoIntentConsumers{Filer: c.f, firstReady: make(chan struct{}), secondReady: make(chan struct{}), firstWritten: make(chan struct{})}
type result struct {
pending bool
err error
}
results := make(chan result, 2)
for i := range 2 {
consumer, err := NewBCatalog(f, c.b, c.base)
if err != nil {
t.Fatal(err)
}
go func() {
pending, err := consumer.CleanSnapshotDeletePage(ctx, v)
results <- result{pending, err}
}()
if i == 0 {
// Deliver the second consumer after the first's effects, while its
// cursor update is held. This exercises a duplicate application
// followed by a real refused CAS, without a Mark conflict first.
select {
case <-f.firstReady:
case <-ctx.Done():
t.Fatal("first consumer never reached its cursor CAS")
}
}
}
for range 2 {
select {
case r := <-results:
if r.err != nil || !r.pending {
t.Errorf("same-page cursor settlement: pending=%v err=%v", r.pending, r.err)
}
case <-ctx.Done():
t.Fatal("two consumers did not finish within the control deadline")
}
}
// The losing CAS really reached the conditional store and was refused.
// Its prior effects cannot authorize skipping the still-unread tail.
if f.calls != 2 || f.refused != 1 || cost.headWrites != 1 || len(cost.deletes) != 3 {
t.Fatalf("contended first page: attempts=%d refused=%d writes=%d deletes=%v", f.calls, f.refused, cost.headWrites, cost.deletes)
}
restarted, err := NewBCatalog(f, c.b, c.base)
if err != nil {
t.Fatal(err)
}
if pending, err := restarted.CleanSnapshotDeletePage(ctx, v); err != nil || pending {
t.Fatalf("unread tail lost after refused CAS: pending=%v err=%v", pending, err)
}
if cost.lists != 0 || cost.headWrites != 2 || len(cost.deletes) != 4 {
t.Fatalf("completion changed outcome: lists=%d writes=%d deletes=%v", cost.lists, cost.headWrites, cost.deletes)
}
for object, count := range cost.deletes {
if count != 1 {
t.Errorf("effect changed outcome twice: object=%s count=%d", object, count)
}
}
}
@@ -0,0 +1,344 @@
package chunkstore
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"path"
"sort"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
type intentCost struct {
rootEntries, segmentEntries, pageEntries int
mu sync.Mutex
lists, roots, segments, pages, data, headWrites int
rootBytes, segmentBytes, pageBytes int
deletes map[string]int
segmentShards map[uint64]bool
}
type intentCostFiler struct {
Filer
cost *intentCost
}
func (f *intentCostFiler) ListEntries(context.Context, string, string, string, uint32) ([]*filerpb.Entry, error) {
f.cost.mu.Lock()
f.cost.lists++
f.cost.mu.Unlock()
return nil, errors.New("counting control: intent driver enumerated the namespace")
}
func (f *intentCostFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
err := f.Filer.UpdateEntry(ctx, dir, e, expected)
if err == nil && e.Name == layout.HeadName {
f.cost.mu.Lock()
f.cost.headWrites++
f.cost.mu.Unlock()
}
return err
}
func (f *intentCostFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
if err == nil {
f.cost.mu.Lock()
f.cost.deletes[path.Join(dir, name)]++
f.cost.mu.Unlock()
}
return err
}
type intentCostBlobs struct {
Blobs
cost *intentCost
}
func (b *intentCostBlobs) Get(ctx context.Context, fid string) ([]byte, error) {
raw, err := b.Blobs.Get(ctx, fid)
if err != nil {
return nil, err
}
b.cost.mu.Lock()
defer b.cost.mu.Unlock()
switch {
case bytes.HasPrefix(raw, []byte("SWBROOT")):
root, err := layout.DecodeRoot(raw)
if err != nil {
return nil, err
}
b.cost.rootEntries += len(root.Segments)
b.cost.roots++
b.cost.rootBytes += len(raw)
case bytes.HasPrefix(raw, []byte("SWBSEG")):
seg, err := layout.DecodeSegment(raw)
if err != nil {
return nil, err
}
if b.cost.segmentShards == nil {
b.cost.segmentShards = map[uint64]bool{}
}
b.cost.segmentShards[seg.Shard] = true
b.cost.segmentEntries += len(seg.Chunks)
b.cost.segments++
b.cost.segmentBytes += len(raw)
case bytes.HasPrefix(raw, []byte(`{"version":1,"volume_id":`)):
var page struct {
Entries []string `json:"entries"`
}
if err := json.Unmarshal(raw, &page); err != nil {
return nil, err
}
b.cost.pageEntries += len(page.Entries)
b.cost.pages++
b.cost.pageBytes += len(raw)
default:
b.cost.data++
}
return raw, nil
}
// This is a counting fake, not a payload durability fixture. It materializes
// all N canonical current references and their root/segments, but no live data
// payloads. Only the deleted snapshot's two candidate payloads are necessary.
func largeIntentCatalog(t *testing.T, n int) (*BCatalog, VolumeRef, *intentCost) {
t.Helper()
ctx := context.Background()
c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks")
if err != nil {
t.Fatal(err)
}
v := newRef(t, "scale")
if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: uint64(n) * (4 << 20), BlockSize: 4096, ChunkBytes: 4 << 20}); err != nil {
t.Fatal(err)
}
s, err := c.Store(v)
if err != nil {
t.Fatal(err)
}
putManifest := func(refs map[uint64]layout.Ref) (layout.RootName, []layout.SegName) {
t.Helper()
root, segs, err := layout.Build(refs)
if err != nil {
t.Fatal(err)
}
var names []layout.SegName
for name, raw := range segs {
if err := layout.EnsureObject(ctx, s, name.Path(), raw, "fixture"); err != nil {
t.Fatal(err)
}
names = append(names, name)
}
rn, raw, err := layout.NameRoot(root)
if err != nil {
t.Fatal(err)
}
if err := layout.EnsureObject(ctx, s, rn.Path(), raw, "fixture"); err != nil {
t.Fatal(err)
}
return rn, names
}
refs := make(map[uint64]layout.Ref, n)
for i := range n {
n := layout.NameChunk(uint64(i), []byte("live payload not materialized"))
refs[uint64(i)] = layout.Ref{Owner: v.Name, OwnerID: v.ID, Chunk: n}
}
current, _ := putManifest(refs)
old := map[uint64]layout.Ref{}
var chunks []layout.ChunkName
for _, i := range []uint64{2, 3} {
raw := []byte(fmt.Sprintf("old chunk %d", i))
n := layout.NameChunk(i, raw)
if err := layout.EnsureObject(ctx, s, n.Path(), raw, "fixture"); err != nil {
t.Fatal(err)
}
old[i] = layout.Ref{Owner: v.Name, OwnerID: v.ID, Chunk: n}
chunks = append(chunks, n)
}
snapshot, oldSegments := putManifest(old)
h, _, err := s.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
h.Version, h.Epoch, h.Holder, h.ClaimID = layout.HeadVersion1, cleanHolder.Epoch, cleanHolder.Holder, cleanHolder.ClaimID
h.Current = &current
h.Snapshots = map[string]layout.Snapshot{"old": {Root: snapshot, Gen: h.Gen + 1}}
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
h, _, err = s.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
p := layout.ListPage{VolumeID: v.ID, Kind: layout.ListSnapshotDeleteIntent, Producer: "delete-old", Generation: h.Gen + 1, Pages: 1,
Target: &layout.SnapshotTarget{Name: "old", Gen: h.Snapshots["old"].Gen}, Entries: []string{chunks[1].Path()}}
tail, err := layout.StageSnapshotDeletePage(ctx, s, h.Gen, p)
if err != nil {
t.Fatal(err)
}
p.Pages, p.Next = 2, &tail
p.Entries = []string{snapshot.Path(), oldSegments[0].Path(), chunks[0].Path()}
sort.Strings(p.Entries)
head, err := layout.StageSnapshotDeletePage(ctx, s, h.Gen, p)
if err != nil {
t.Fatal(err)
}
if _, err := layout.RunDeleteSnapshotWithIntent(ctx, s, h.Gen, layout.ListCursor{Ref: head, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target}); err != nil {
t.Fatal(err)
}
cost := &intentCost{deletes: map[string]int{}}
c.f, c.b = &intentCostFiler{Filer: c.f, cost: cost}, &intentCostBlobs{Blobs: c.b, cost: cost}
return c, v, cost
}
// Prediction before measurement: fixed two-page work needs at most three root
// GETs, two candidate-shard GETs and two page GETs, independent of N. Root bytes
// still grow with ceil(N/ShardSize); the existing format cost is reported, not
// hidden by constant request counts. All four candidate deletions occur once.
func TestCatalogIntentCountingAt262144Entries(t *testing.T) {
for _, n := range []int{1024, 16384, 262144} {
t.Run(fmt.Sprintf("entries_%d", n), func(t *testing.T) {
c, v, cost := largeIntentCatalog(t, n)
for page := 0; page < 2; page++ {
if pending, err := c.CleanSnapshotDeletePage(context.Background(), v); err != nil || pending != (page == 0) {
t.Fatalf("page %d: pending=%v err=%v", page, pending, err)
}
var err error
c, err = NewBCatalog(c.f, c.b, c.base)
if err != nil {
t.Fatal(err)
}
}
t.Logf("entries=%d list_calls=%d roots=%d root_bytes=%d segments=%d segment_bytes=%d pages=%d page_bytes=%d payload_gets=%d deletes=%d cursor_writes=%d", n, cost.lists, cost.roots, cost.rootBytes, cost.segments, cost.segmentBytes, cost.pages, cost.pageBytes, cost.data, len(cost.deletes), cost.headWrites)
if cost.lists != 0 || cost.roots > 3 || cost.segments > 2 || cost.pages != 2 || cost.data != 0 || len(cost.deletes) != 4 || cost.headWrites != 2 {
t.Fatalf("counting prediction violated: %+v", cost)
}
for object, count := range cost.deletes {
if count != 1 {
t.Fatalf("completed deletion repeated: %s count=%d", object, count)
}
}
})
}
}
func TestCatalogIntentInterruptedCountingAt262144Entries(t *testing.T) {
for _, afterWrite := range []bool{false, true} {
t.Run(fmt.Sprintf("lost_reply_%v", afterWrite), func(t *testing.T) {
ctx := context.Background()
c, v, cost := largeIntentCatalog(t, 262144)
fault := &intentCursorFault{Filer: c.f, armed: true, afterWrite: afterWrite, deletes: map[string]int{}}
c.f = fault
pending, err := c.CleanSnapshotDeletePage(ctx, v)
if afterWrite {
if err != nil || !pending {
t.Fatalf("lost cursor reply: pending=%v err=%v", pending, err)
}
} else if !errors.Is(err, errIntentCursorInterrupted) {
t.Fatalf("cursor interruption not reported: %v", err)
}
// Root, segment and first chunk must be deleted before any cursor
// advance, including an update whose reply is lost.
if len(cost.deletes) != 3 || cost.headWrites != map[bool]int{false: 0, true: 1}[afterWrite] {
t.Fatalf("effects/cursor order: deletes=%v writes=%d", cost.deletes, cost.headWrites)
}
c, err = NewBCatalog(fault, c.b, c.base)
if err != nil {
t.Fatal(err)
}
if !afterWrite {
if pending, err := c.CleanSnapshotDeletePage(ctx, v); err != nil || !pending {
t.Fatalf("retry unfinished page: pending=%v err=%v", pending, err)
}
}
if pending, err := c.CleanSnapshotDeletePage(ctx, v); err != nil || pending {
t.Fatalf("finish tail: pending=%v err=%v", pending, err)
}
t.Logf("lost_reply=%v roots=%d segments=%d pages=%d deletes=%d cursor_writes=%d", afterWrite, cost.roots, cost.segments, cost.pages, len(cost.deletes), cost.headWrites)
if cost.lists != 0 || cost.roots > 5 || cost.segments > 3 || cost.pages > 3 || cost.data != 0 || len(cost.deletes) != 4 || cost.headWrites != 2 {
t.Fatalf("interrupted counting prediction violated: %+v", cost)
}
for object, count := range cost.deletes {
if count != 1 {
t.Fatalf("completed deletion repeated: %s count=%d", object, count)
}
}
})
}
}
// The current format decodes the selected shard once for each of the two
// chunk candidates. ShardSize is fixed at 10000 (layout/layout.go), and
// DecodeSegment refuses a larger shard. Root bytes remain a separate term.
func intentShardBudget(cost *intentCost, owner string) error {
// This fixture's candidate indexes are 2 and 3, hence shard zero. Its
// encoded indexes use at most two varint bytes; owner length uses one.
const candidateReads = 2
maxBytes := candidateReads * (7 + 10 + 10 + int(layout.ShardSize)*(2+1+len(owner)+16+32))
if len(cost.segmentShards) > 1 || (len(cost.segmentShards) == 1 && !cost.segmentShards[0]) || cost.segments > candidateReads || cost.segmentEntries > candidateReads*int(layout.ShardSize) || cost.segmentBytes > maxBytes {
return fmt.Errorf("candidate shard bound exceeded: shards=%v gets=%d refs=%d bytes=%d limit=%d", cost.segmentShards, cost.segments, cost.segmentEntries, cost.segmentBytes, maxBytes)
}
return nil
}
func TestCatalogIntentDecodedWorkIsBoundedByTheCandidateShard(t *testing.T) {
var plateau *intentCost
for _, n := range []int{1024, 16384, 262144, 1048576} {
c, v, cost := largeIntentCatalog(t, n)
for page := range 2 {
pending, err := c.CleanSnapshotDeletePage(t.Context(), v)
if err != nil || pending != (page == 0) {
t.Fatalf("entries=%d page=%d pending=%v err=%v", n, page, pending, err)
}
}
t.Logf("entries=%d requests=%d root_descriptors=%d root_bytes=%d segment_refs=%d segment_bytes=%d page_candidates=%d page_bytes=%d shards=%v", n, cost.roots+cost.segments+cost.pages, cost.rootEntries, cost.rootBytes, cost.segmentEntries, cost.segmentBytes, cost.pageEntries, cost.pageBytes, cost.segmentShards)
if err := intentShardBudget(cost, v.Name); err != nil {
t.Fatal(err)
}
if cost.roots != 3 || cost.pages != 2 || cost.pageEntries != 4 || cost.pageBytes != 760 || cost.lists != 0 {
t.Fatalf("fixed candidate work changed: %+v", cost)
}
if n >= 16384 {
if plateau != nil && (cost.segmentEntries != plateau.segmentEntries || cost.segmentBytes != plateau.segmentBytes) {
t.Fatal("decoded segment work grew beyond the saturated candidate shard")
}
plateau = cost
}
}
}
// A second shard is refused even if two partial shards fit the aggregate
// byte/ref ceiling. Exercise the real reader so the observer sees both.
func TestIntentShardBudgetRefusesTwoDecodedShards(t *testing.T) {
c, v, cost := largeIntentCatalog(t, 16384)
s, r, err := c.open(v)
if err != nil {
t.Fatal(err)
}
h, _, err := s.ReadHead(t.Context())
if err != nil {
t.Fatal(err)
}
img, err := r.Open(t.Context(), *h.Current)
if err != nil {
t.Fatal(err)
}
for _, shard := range []uint64{0, 1} {
if _, found, err := img.Segment(t.Context(), shard); err != nil || !found {
t.Fatalf("shard=%d found=%v err=%v", shard, found, err)
}
}
if cost.segmentEntries > 2*int(layout.ShardSize) {
t.Fatal("control did not isolate the distinct-shard guard")
}
if err := intentShardBudget(cost, v.Name); err == nil {
t.Fatal("two decoded shards passed the one-candidate-shard budget")
}
}
@@ -0,0 +1,188 @@
package chunkstore
import (
"context"
"errors"
"path"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// The compatibility sweep must retire abandoned list metadata too. Otherwise
// retrying publication can leave an unbounded metadata backlog even when no
// candidate data objects remain.
func TestBCatalogFullSweepRetiresUnreachableListPages(t *testing.T) {
ctx := context.Background()
c, v, s, _ := cleanFixture(t)
p := layout.ListPage{VolumeID: v.ID, Kind: layout.ListDrop, Producer: "abandoned", Generation: 1, Pages: 1,
Entries: []string{(layout.RootName{Hash: layout.Sum([]byte("unpublished root"))}).Path()}}
raw, err := p.Encode()
if err != nil {
t.Fatal(err)
}
ref, err := p.Ref()
if err != nil {
t.Fatal(err)
}
rel, _ := ref.Path()
if err := layout.EnsureObject(ctx, s, rel, raw, p.Producer); err != nil {
t.Fatal(err)
}
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
t.Fatal(err)
}
if _, found, err := s.ReadListPage(ctx, ref); err != nil || found {
t.Fatalf("abandoned page survived the compatibility sweep: found=%v err=%v", found, err)
}
}
type listSweepProbe struct {
Filer
listCalls int
failAt int
limits []uint32
deletes map[string]int
}
var errListSweepInterrupted = errors.New("list sweep interrupted after a completed page")
func (p *listSweepProbe) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) {
if path.Base(dir) == layout.ListDir {
p.listCalls++
p.limits = append(p.limits, limit)
if p.failAt == p.listCalls {
return nil, errListSweepInterrupted
}
}
return p.Filer.ListEntries(ctx, dir, prefix, after, limit)
}
func (p *listSweepProbe) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
err := p.Filer.DeleteEntry(ctx, dir, name, expected)
if err == nil && path.Base(dir) == layout.ListDir {
p.deletes[name]++
}
return err
}
func TestBCatalogListRetirementResumesAfterRestart(t *testing.T) {
ctx := context.Background()
previousPage := cleanPage
cleanPage = 1
t.Cleanup(func() { cleanPage = previousPage })
c, v, s, _ := cleanFixture(t)
probe := &listSweepProbe{Filer: c.f, failAt: 2, deletes: map[string]int{}}
c.f = probe
var refs []layout.ListRef
for _, producer := range []string{"abandoned-a", "abandoned-b", "abandoned-c"} {
p := layout.ListPage{VolumeID: v.ID, Kind: layout.ListDrop, Producer: producer, Generation: 1, Pages: 1,
Entries: []string{(layout.RootName{Hash: layout.Sum([]byte(producer))}).Path()}}
raw, err := p.Encode()
if err != nil {
t.Fatal(err)
}
ref, err := p.Ref()
if err != nil {
t.Fatal(err)
}
rel, _ := ref.Path()
if err := layout.EnsureObject(ctx, s, rel, raw, producer); err != nil {
t.Fatal(err)
}
refs = append(refs, ref)
}
res, _, err := cleanVia(ctx, c, v, cleanHolder)
if !errors.Is(err, errListSweepInterrupted) || res.Lists != 1 || len(probe.deletes) != 1 {
t.Fatalf("first page was not durably reclaimed before interruption: result=%+v deletes=%v err=%v", res, probe.deletes, err)
}
// No scheduling cursor survives: a new catalog must still finish from the
// same filer state, without deleting a completed page a second time.
restarted, err := NewBCatalog(probe, c.b, c.base)
if err != nil {
t.Fatal(err)
}
probe.failAt = 0
res, _, err = cleanVia(ctx, restarted, v, cleanHolder)
if err != nil || res.Lists != 2 || res.PlannedLists != 2 {
t.Fatalf("restart: result=%+v err=%v", res, err)
}
for _, ref := range refs {
if probe.deletes[ref.Hash] != 1 {
t.Fatalf("page %s deleted %d times", ref.Hash, probe.deletes[ref.Hash])
}
}
for _, limit := range probe.limits {
if limit != 1 {
t.Fatalf("unbounded list enumeration: limit=%d", limit)
}
}
}
func TestBCatalogFullSweepKeepsTheEntireCurrentList(t *testing.T) {
for _, missingTail := range []bool{false, true} {
name := "current chain"
if missingTail {
name = "missing continuation"
}
t.Run(name, func(t *testing.T) {
ctx := context.Background()
c, v, s, _ := cleanFixture(t)
h, found, err := s.ReadHead(ctx)
if err != nil || !found {
t.Fatalf("HEAD: %v %v", found, err)
}
put := func(p layout.ListPage) layout.ListRef {
t.Helper()
raw, err := p.Encode()
if err != nil {
t.Fatal(err)
}
ref, err := p.Ref()
if err != nil {
t.Fatal(err)
}
rel, _ := ref.Path()
if err := layout.EnsureObject(ctx, s, rel, raw, p.Producer); err != nil {
t.Fatal(err)
}
return ref
}
page := layout.ListPage{VolumeID: v.ID, Kind: layout.ListDrop, Producer: "current", Generation: h.Gen + 1, Pages: 1,
Entries: []string{(layout.RootName{Hash: layout.Sum([]byte("tail candidate"))}).Path()}}
tail := put(page)
page.Pages, page.Next = 2, &tail
page.Entries = []string{(layout.RootName{Hash: layout.Sum([]byte("head candidate"))}).Path()}
head := put(page)
h.Version = layout.HeadVersion1
h.List = &layout.ListCursor{Ref: head, Kind: page.Kind, Producer: page.Producer, Generation: page.Generation}
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseListPublish); err != nil {
t.Fatal(err)
}
page.Pages, page.Next, page.Producer = 1, nil, "abandoned"
orphan := put(page)
if missingTail {
rel, _ := tail.Path()
if err := c.f.DeleteEntry(ctx, s.root+"/"+layout.ListDir, rel[len(layout.ListDir)+1:], nil); err != nil {
t.Fatal(err)
}
}
_, _, err = cleanVia(ctx, c, v, cleanHolder)
if missingTail {
if !errors.Is(err, layout.ErrListPageMissing) {
t.Fatalf("missing continuation completed the sweep: %v", err)
}
} else if err != nil {
t.Fatal(err)
}
for _, ref := range []layout.ListRef{head, tail, orphan} {
_, found, err := s.ReadListPage(ctx, ref)
want := ref != orphan && (!missingTail || ref != tail) || missingTail && ref == orphan
if err != nil || found != want {
t.Fatalf("page %s: found=%v want=%v err=%v", ref.Hash, found, want, err)
}
}
})
}
}
@@ -50,6 +50,7 @@ const (
CodeDeadlineExceeded = "deadline_exceeded"
CodeRemoteUnavailable = "remote_unavailable"
CodeRemoteFull = "remote_full" // the chunk store has no space; retry after adding capacity
CodeQueueFull = "queue_full" // pending reclamation work must drain before another producer publishes
CodeOutcomeUnknown = "outcome_unknown"
CodeInvalidLabel = "invalid_label"
)
@@ -144,7 +144,7 @@ func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base ui
return Head{}, false, err
}
if h.List != nil {
return Head{}, false, ErrBusy
return Head{}, false, ErrQueueFull
}
// The intent must retain the removed root, not just an operation id.
// Its complete candidate plan is authenticated before publication.
@@ -100,6 +100,10 @@ type ListChainStore interface {
ListPageReader
}
// ErrQueueFull is retryable backpressure: the bounded pending-list slot
// remains owned by its current work. No references were dropped.
var ErrQueueFull = fmt.Errorf("%w: pending list queue is full", ErrBusy)
func listSession(h Head, me HolderID, session, kind string) error {
if err := h.holderErr(me); err != nil {
return err
@@ -161,7 +165,7 @@ func RunPublishList(ctx context.Context, st ListChainStore, me HolderID, session
return Head{}, false, ErrPrecondition
}
if h.List != nil {
return Head{}, false, ErrBusy
return Head{}, false, ErrQueueFull
}
if err := ReadListChain(ctx, st, h.VolumeID, c, nil); err != nil {
return Head{}, false, err
@@ -0,0 +1,111 @@
package layout
import (
"bytes"
"context"
"errors"
"reflect"
"testing"
)
// Copy bytes as well as metadata: retaining object pointers would let an
// in-place mutation change both the observed state and the expected value.
func queueObjectSnapshot(s *chainStore) map[string]memObject {
out := make(map[string]memObject, len(s.objs))
for name, o := range s.objs {
out[name] = memObject{data: append([]byte(nil), o.data...), meta: o.meta}
}
return out
}
func TestDeleteIntentQueueFullKeepsBothWorkAndReferences(t *testing.T) {
ctx := context.Background()
s, first, p := deleteIntentFixture(t)
// Two incarnations may share image bytes, but each unlink needs its own
// retained target and a free durable slot.
s.h.Snapshots["weekly"] = Snapshot{Root: s.h.Snapshots["daily"].Root, Gen: 5}
r := deleteIntentReader(t, s)
if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil {
t.Fatal(err)
}
if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, first); err != nil {
t.Fatal(err)
}
p.Producer, p.Generation, p.Target = "delete-weekly", s.h.Gen+1, &SnapshotTarget{Name: "weekly", Gen: 5}
ref, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p)
if err != nil {
t.Fatal(err)
}
second := ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target}
before := s.h.clone()
writes, updates := len(s.writes), s.updates
if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, second); !errors.Is(err, ErrQueueFull) {
t.Fatalf("want typed queue_full, got %v", err)
}
if !reflect.DeepEqual(*s.h, before) || s.updates != updates || len(s.writes) != writes {
t.Fatal("full queue dropped references, replaced pending work or adopted pages")
}
// Draining the first slot must preserve weekly's live image. Retry then
// atomically unlinks that exact incarnation and publishes its own work.
weekly := before.Snapshots["weekly"]
shared := queueObjectSnapshot(s)
if _, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); err != nil {
t.Fatal(err)
}
if got, found := s.h.Snapshots["weekly"]; !found || !reflect.DeepEqual(got, weekly) {
t.Fatalf("first drain changed the retained weekly incarnation: got=%+v want=%+v", got, weekly)
}
// The page names the shared root, its segment and payload. Check all of
// them now, before weekly is unlinked and reclamation becomes permitted.
for _, rel := range p.Entries {
want, found := shared[s.full(rel)]
got, present := s.objs[s.full(rel)]
if !found || !present || !bytes.Equal(got.data, want.data) || got.meta != want.meta {
t.Fatalf("first drain changed weekly's shared image object %s", rel)
}
}
if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, second); err != nil {
t.Fatal(err)
}
if _, found := s.h.Snapshots["weekly"]; found || !sameList(s.h.List, &second) {
t.Fatal("retry did not atomically unlink and publish")
}
if _, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); err != nil {
t.Fatal(err)
}
if s.h.List != nil {
t.Fatal("queue did not drain")
}
}
func TestGenericListQueueFullCannotOverwritePendingWork(t *testing.T) {
ctx := context.Background()
s, first, p := chainFixture(t)
if _, err := StageListPage(ctx, s, me, "s1", p); err != nil {
t.Fatal(err)
}
if _, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, first); err != nil {
t.Fatal(err)
}
p.Generation = s.h.Gen + 1
p.Entries = []string{RootName{Hash: Sum([]byte("second candidate"))}.Path()}
ref, err := StageListPage(ctx, s, me, "s1", p)
if err != nil {
t.Fatal(err)
}
second := ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation}
before, updates := s.h.clone(), s.updates
objects, writes := queueObjectSnapshot(s), append([]string(nil), s.writes...)
if _, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, second); !errors.Is(err, ErrQueueFull) {
t.Fatalf("want typed queue_full, got %v", err)
}
if !reflect.DeepEqual(*s.h, before) || s.updates != updates {
t.Fatal("full queue was overwritten")
}
if !reflect.DeepEqual(queueObjectSnapshot(s), objects) || !reflect.DeepEqual(s.writes, writes) {
t.Fatal("generic full-slot refusal mutated objects or attempted an object write")
}
if _, err := RunPublishList(ctx, s, me, "s1", first.Generation-1, first); err != nil {
t.Fatalf("same-list replay refused: %v", err)
}
}
@@ -31,8 +31,7 @@ import (
// alone resolves the owner's directory and is verified by name.
// sessionStore is what the remote writes through: HEAD and the objects.
type sessionStore interface {
layout.HeadStore
layout.ObjectStore
layout.ListChainStore
}
type LayoutRemote struct {
@@ -1261,7 +1260,11 @@ func (l *LayoutRemote) LastCommit() layout.Head {
return l.lastCommit
}
// Clean runs one cleaning of this holder between sessions: clean(c) opens
// Clean first resumes a persisted snapshot-delete intent between sessions,
// using the same cancellation/join as the subsequent compatibility sweep.
// The attached holder is checked before intent effects; the intent itself
// remains receipt-independent authority under its live-root guards.
// Then clean(c) opens
// HEAD, run removes unreachable names under session c, and clean(c) ends.
// A cut or a stop that needs HEAD meanwhile cancels run's context and
// waits for it to end: neither waits on a cleaning nor fails busy. A pass
@@ -1276,7 +1279,8 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context,
l.mu.Unlock()
return layout.ErrBusy
}
if _, err := l.rollBackLocked(ctx); err != nil {
h, err := l.rollBackLocked(ctx)
if err != nil {
l.mu.Unlock()
return err
}
@@ -1286,16 +1290,43 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context,
return err
}
c := "c-" + hex.EncodeToString(b[:])
bh, err := layout.RunBeginClean(ctx, l.st, l.me, c)
if err != nil {
// Validate the attached holder before applying offline intent effects. The
// pure transition performs the same guard without opening clean activity:
// the persisted intent consumer requires HEAD to remain idle.
if _, _, err := h.BeginClean(l.me, c); err != nil {
l.mu.Unlock()
return layoutRemoteErr(err)
}
l.ownGen = bh.Gen
cctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
l.cleaning, l.cleanCancel, l.cleanDone = c, cancel, done
l.mu.Unlock()
defer func() {
cancel()
l.mu.Lock()
l.cleaning, l.cleanCancel = "", nil
close(done)
l.mu.Unlock()
}()
// Resume only the dedicated delete intent. A generic list is consumed by
// its own protocol; membership alone must not grant delete authority.
for h.List != nil && h.List.Kind == layout.ListSnapshotDeleteIntent {
if err := cctx.Err(); err != nil {
return err
}
h, err = layout.RunConsumeSnapshotDeleteIntent(cctx, l.st, l.r)
if err != nil {
return layoutRemoteErr(err)
}
}
bh, err := layout.RunBeginClean(cctx, l.st, l.me, c)
if err != nil {
return layoutRemoteErr(err)
}
l.mu.Lock()
l.ownGen = bh.Gen
l.mu.Unlock()
runErr := run(cctx, l.me, c)
// Bounded by the caller's context: a stop on a hung filer does not
@@ -1308,8 +1339,6 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context,
if endErr == nil {
l.ownGen = eh.Gen
}
l.cleaning, l.cleanCancel = "", nil
close(done)
l.mu.Unlock()
if runErr != nil && !errors.Is(runErr, context.Canceled) {
return runErr
@@ -0,0 +1,99 @@
package chunkstore
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestHolderMaintenanceResumesThePersistedDeleteIntent(t *testing.T) {
for _, wrongClaim := range []bool{false, true} {
t.Run(map[bool]string{false: "holder", true: "wrong claim"}[wrongClaim], func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cat, ref, cost := largeIntentCatalog(t, 1024)
me := cleanHolder
if wrongClaim {
me.ClaimID += "-old"
}
remote, err := NewLayoutRemote(cat, ref, me)
if err != nil {
t.Fatal(err)
}
called := false
err = remote.Clean(ctx, func(ctx context.Context, _ layout.HolderID, _ string) error {
called = true
h, err := remote.ReadHead(ctx)
if err == nil && h.List != nil {
t.Error("fallback sweep started before the persisted intent finished")
}
return err
})
if wrongClaim {
if !errors.Is(err, storage.ErrChunkLayerFenced) || called || len(cost.deletes) != 0 {
t.Fatalf("wrong holder removed work: err=%v callback=%v deletes=%v", err, called, cost.deletes)
}
return
}
if err != nil || !called || len(cost.deletes) != 4 || cost.lists != 0 {
t.Fatalf("intent continuation: err=%v callback=%v deletes=%v namespace lists=%d", err, called, cost.deletes, cost.lists)
}
})
}
}
type blockedMaintenanceIntent struct {
sessionStore
entered chan struct{}
}
func (s blockedMaintenanceIntent) ReadListPage(ctx context.Context, _ layout.ListRef) ([]byte, bool, error) {
close(s.entered)
<-ctx.Done()
return nil, false, ctx.Err()
}
func TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cat, ref, cost := largeIntentCatalog(t, 1024)
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
if err != nil {
t.Fatal(err)
}
entered := make(chan struct{})
remote.st = blockedMaintenanceIntent{sessionStore: remote.st, entered: entered}
result := make(chan error, 1)
go func() {
result <- remote.Clean(ctx, func(context.Context, layout.HolderID, string) error {
return errors.New("fallback must not run after cancellation")
})
}()
select {
case <-entered:
case <-ctx.Done():
t.Fatal("intent did not enter its page read")
}
remote.mu.Lock()
err = remote.stopCleaningLocked(ctx)
remote.mu.Unlock()
if err != nil {
t.Fatal(err)
}
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("intent cancellation: %v", err)
}
case <-ctx.Done():
t.Fatal("maintenance did not join")
}
h, err := remote.ReadHead(ctx)
if err != nil || h.List == nil || h.Activity.Kind != layout.ActIdle || len(cost.deletes) != 0 {
t.Fatalf("cancelled work lost its continuation: head=%+v err=%v deletes=%v", h, err, cost.deletes)
}
}
@@ -0,0 +1,34 @@
package durable
import (
"context"
"errors"
"path/filepath"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestDeviceLegacyBudgetDoesNotInstallARetryableWALHold(t *testing.T) {
s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "store"), 256, 4096, storage.WALStoreOptions{ChunkBlocks: 16})
if err != nil {
t.Fatal(err)
}
defer s.Close()
b := NewStorageBackend(s, holdCommandView{}, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})
synctest.Test(t, func(t *testing.T) {
ctx, cancel := frontend.WithLegacyWriteBudget(context.Background(), time.Now())
defer cancel()
ctx, cancelBackend := b.WriteCommandContext(ctx, time.Time{})
defer cancelBackend()
defer storage.FinishWALWriteHold(ctx, nil)
time.Sleep(5 * time.Second)
_, err := s.WriteContext(ctx, 0, make([]byte, 4096))
if !errors.Is(err, storage.ErrWALPressureTimeout) || errors.Is(err, storage.ErrWALHoldCap) {
t.Fatalf("legacy device budget became retryable hold: %v", err)
}
})
}
@@ -26,9 +26,11 @@ type MaintenancePassStatus struct {
PlannedChunks int64 `json:"plannedChunks"` // chunk objects considered for removal
PlannedRoots int64 `json:"plannedRoots"` // root objects considered for removal
PlannedSegments int64 `json:"plannedSegments"` // segment objects considered for removal
PlannedLists int64 `json:"plannedLists"` // immutable list pages considered for removal
RemovedChunks int64 `json:"removedChunks"` // chunk objects removed
RemovedRoots int64 `json:"removedRoots"` // root objects removed
RemovedSegments int64 `json:"removedSegments"` // segment objects removed
RemovedLists int64 `json:"removedLists"` // immutable list pages removed
Error string `json:"error"` // one-line callback error; empty when the callback completed
HeadGenError string `json:"headGenError"` // diagnostic HEAD read error; empty when read
HeadGen uint64 `json:"headGen"` // observed cleaning HEAD generation; diagnostic only
@@ -121,6 +121,7 @@ var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O s
// ProviderConfig configures a DurableProvider.
type ProviderConfig struct {
WALHold frontend.WALHoldConfig
// RecoveryProgress observes completed local-create and local-open work
// before RecoverVolume.
RecoveryProgress func(storage.RecoveryPhase, uint64)
@@ -397,6 +398,8 @@ type volHandle struct {
// handle. It intentionally exposes lineage and readiness facts without giving
// callers a control surface.
type VolumeStatus struct {
WALHold *storage.WALHoldStatus `json:",omitempty"` // WAL-pressure hold health and cumulative metrics
Degraded bool // diagnostic WAL reclaim stall; does not alter authority or readiness
UnknownOutcome map[layout.HeadWriteCause]uint64 // unknown HEAD-write answers by cause since catalog start; never implies persistence
HeadWrites map[layout.HeadWriteCause]uint64 // acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded
VolumeID string // the volume
@@ -458,6 +461,12 @@ type CutScheduleStatus struct {
// source of authority lineage the provider is allowed to consult
// (sketch §9 boundary).
func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*DurableProvider, error) {
if cfg.WALHold == (frontend.WALHoldConfig{}) {
cfg.WALHold = frontend.DefaultWALHoldConfig()
}
if err := cfg.WALHold.Validate(); err != nil {
return nil, err
}
if cfg.StorageRoot == "" {
return nil, fmt.Errorf("durable: ProviderConfig.StorageRoot required")
}
@@ -1135,6 +1144,7 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L
EndpointVersion: proj.EndpointVersion,
}
b := NewStorageBackend(s, p.view, id)
b.walHold = p.cfg.WALHold
return &volHandle{storage: s, backend: b, path: path, impl: impl}, nil
}
@@ -1284,3 +1294,21 @@ func chunkSidecars(path string) ([]string, error) {
// Compile-time check.
var _ frontend.Provider = (*DurableProvider)(nil)
// WALHoldStatuses exposes only atomic hold/reclaim observations. It avoids the
// general durable status path's frontier locks while a slow disk is diagnosed.
func (p *DurableProvider) WALHoldStatuses() map[string]storage.WALHoldStatus {
p.mu.Lock()
stores := make(map[string]storage.LogicalStorage, len(p.volumes))
for id, h := range p.volumes {
stores[id] = h.storage
}
p.mu.Unlock()
out := make(map[string]storage.WALHoldStatus, len(stores))
for id, s := range stores {
if reporter, ok := s.(interface{ WALHoldStatus() storage.WALHoldStatus }); ok {
out[id] = reporter.WALHoldStatus()
}
}
return out
}
@@ -147,6 +147,7 @@ const maxFullBlockBatchBlocks = 64
// StorageBackend adapts a LogicalStorage into frontend.Backend.
type StorageBackend struct {
walHold frontend.WALHoldConfig
// testBeforeIOLock, test-only, runs in admit after the readiness check,
// right before the I/O lock (an arrival handshake for queued I/O).
testBeforeIOLock func()
@@ -214,11 +215,12 @@ type StorageBackend struct {
// seed) together with rebasing the observer, against installing an
// observer together with its rebase: whichever runs second sees the
// other's result. Lock order: observerMu, then mu.
observerMu sync.Mutex
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
lbaWriteLocks [256]sync.Mutex
observerMu sync.Mutex
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
lbaWriteLocks [256]sync.Mutex
testBeforeRMWRead func()
}
// NewStorageBackend constructs a backend. Starts NON-operational
@@ -230,6 +232,7 @@ type StorageBackend struct {
// impl changes it mid-session).
func NewStorageBackend(s storage.LogicalStorage, view frontend.ProjectionView, id frontend.Identity) *StorageBackend {
b := &StorageBackend{
walHold: frontend.DefaultWALHoldConfig(),
storage: s,
view: view,
id: id,
@@ -330,6 +333,11 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
snapshot := reporter.CheckpointPersistence()
checkpoint = &snapshot
}
var walHold *storage.WALHoldStatus
if reporter, ok := b.storage.(interface{ WALHoldStatus() storage.WALHoldStatus }); ok {
st := reporter.WALHoldStatus()
walHold = &st
}
writeProfile := b.WriteProfile()
if instrumented, ok := b.storage.(storage.WriteInstrumented); ok {
storageProfile := instrumented.WriteInstrumentation()
@@ -362,6 +370,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
storeID = hex.EncodeToString(id[:])
}
return VolumeStatus{
WALHold: walHold,
Degraded: walHold != nil && walHold.Degraded,
StoreID: storeID,
Warnings: warnings,
HolesSuspected: holes,
@@ -820,8 +830,8 @@ func (b *StorageBackend) attachReadyTimeout(cause error) error {
// writes perform a read-modify-write: fetch the current block,
// overlay the partial range, write the full block back.
// Every write is gated.
func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) {
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (written int, writeErr error) {
ctx, cancel := b.WriteCommandContext(ctx, time.Time{})
defer cancel()
iolatency.BackendEnter(ctx)
defer iolatency.BackendExit(ctx)
@@ -831,6 +841,7 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int
return 0, err
}
defer release()
defer func() { storage.FinishWALWriteHold(ctx, writeErr) }()
if len(p) == 0 {
return 0, nil
}
@@ -1113,6 +1124,9 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
block = buf[:chunkLen]
} else {
// Partial-block: RMW.
if b.testBeforeRMWRead != nil {
b.testBeforeRMWRead()
}
existing, err := b.readStorageBlock(ctx, lba)
if err != nil {
writeLock.Unlock()
@@ -1295,3 +1309,20 @@ func expiredCommand(ctx context.Context) error {
}
return err
}
// WriteCommandContext is called at transport dispatch and again by direct
// backend callers. The context carries one identity through all store batches.
func (b *StorageBackend) WriteCommandContext(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
if s, ok := b.storage.(*storage.WALStore); ok {
if frontend.UsesLegacyWriteBudget(ctx) {
ctx = storage.WithWALWriteArrival(ctx, s, arrival)
return frontend.WithWriteBudget(ctx, arrival)
}
cfg := b.walHold
if cfg == (frontend.WALHoldConfig{}) {
cfg = frontend.DefaultWALHoldConfig()
}
return storage.WithWALWriteHold(ctx, s, arrival, cfg.MaxHold, false)
}
return frontend.WithWriteBudget(ctx, arrival)
}
@@ -0,0 +1,139 @@
package durable
import (
"bytes"
"context"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type holdCommandView struct{}
func (holdCommandView) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, Healthy: true}
}
func holdCommandBackend(t *testing.T) *StorageBackend {
t.Helper()
s, err := storage.CreateWALStore(filepath.Join(t.TempDir(), "volume"), 256, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
b := NewStorageBackend(s, holdCommandView{}, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})
b.SetOperational(true, "ready")
return b
}
type holdCommandObserver struct {
called atomic.Bool
first func()
}
func (o *holdCommandObserver) Observe(ctx context.Context, _ uint32, _ uint64, _ []byte) error {
if o.called.CompareAndSwap(false, true) {
o.first()
}
return ctx.Err()
}
func (o *holdCommandObserver) ObserveBatch(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error {
if o.called.CompareAndSwap(false, true) {
o.first()
}
return ctx.Err()
}
func (o *holdCommandObserver) Sync(context.Context, uint64) error { return nil }
func TestWALHoldBudgetSurvivesNestedNVMeDispatch(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
if err := b.SetWriteObserver(&holdCommandObserver{first: func() { time.Sleep(6 * time.Second) }}); err != nil {
t.Fatal(err)
}
b.SetWriteAckPolicy(WriteAckRequireObserverAck)
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: 256 * 4096, NSID: 1})
ctx, cancel := frontend.WithBackendWriteBudget(context.Background(), time.Now(), b)
defer cancel()
got := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 0, NLB: 1, Data: bytes.Repeat([]byte{7}, 4096)})
if err := got.AsError(); err != nil {
t.Fatal(err)
}
})
}
func TestWALHoldReleasesAdmissionBeforeObserverAck(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
paused, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
if err := b.SetWriteObserver(&holdCommandObserver{first: func() { close(paused); <-resume }}); err != nil {
t.Fatal(err)
}
b.SetWriteAckPolicy(WriteAckRequireObserverAck)
doneA, doneB := make(chan error, 1), make(chan error, 1)
go func() { _, err := b.Write(context.Background(), 0, bytes.Repeat([]byte{1}, 128*4096)); doneA <- err }()
<-paused
go func() { _, err := b.Write(context.Background(), 192*4096, bytes.Repeat([]byte{2}, 4096)); doneB <- err }()
synctest.Wait()
select {
case err := <-doneB:
if err != nil {
t.Fatal(err)
}
default:
t.Fatal("unrelated append blocked behind replica acknowledgement")
}
time.Sleep(6 * time.Second) // an observer delay is not WAL-pressure inactivity
if st := b.storage.(*storage.WALStore).WALHoldStatus(); st.Degraded {
t.Fatalf("non-pressure queue delay degraded reclaim: %+v", st)
}
release()
synctest.Wait()
if err := <-doneA; err != nil {
t.Fatal(err)
}
got := make([]byte, 4096)
if _, err := b.Read(context.Background(), 192*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{2}, 4096)) {
t.Fatalf("younger bytes were overwritten: %v", err)
}
})
}
func TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
paused, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
b.testBeforeRMWRead = func() { close(paused); <-resume }
doneA, doneB := make(chan error, 1), make(chan error, 1)
go func() { _, err := b.Write(context.Background(), 1, []byte{7}); doneA <- err }()
<-paused
go func() { _, err := b.Write(context.Background(), 4096, bytes.Repeat([]byte{9}, 4096)); doneB <- err }()
synctest.Wait()
select {
case err := <-doneB:
if err != nil {
t.Fatal(err)
}
default:
t.Fatal("unrelated append blocked behind RMW read")
}
release()
synctest.Wait()
if err := <-doneA; err != nil {
t.Fatal(err)
}
})
}
@@ -40,6 +40,8 @@ func TestBackendErrorClassesAcrossFrontends(t *testing.T) {
status, key, asc, ascq, sct, sc uint8
deadline bool
}{
{name: "wal-hold-cap", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALHoldCap), status: 0x08, sct: 0, sc: 0x82},
{name: "wal-reclaim-stalled", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALReclaimStalled), status: 0x08, sct: 0, sc: 0x82},
{name: "wal-pressure", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALPressureTimeout), status: 0x08, sct: 0, sc: 0x82},
{name: "hydration-pending", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrChunkHydrationPending), status: 0x08, sct: 0, sc: 0x82},
{name: "observer-deadline", err: fmt.Errorf("%w: %w: %w", frontend.ErrBackendBusy, durable.ErrReplicationAckUnavailable, context.DeadlineExceeded), status: 0x08, sct: 0, sc: 0x82, deadline: true},
@@ -0,0 +1,39 @@
package iscsi
import (
"context"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
type serialBudgetBackend struct {
frontend.Backend
legacy bool
deadline time.Time
}
func (b *serialBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.legacy = frontend.UsesLegacyWriteBudget(ctx)
b.deadline, _ = ctx.Deadline()
return len(p), nil
}
func (b *serialBudgetBackend) WriteCommandContext(ctx context.Context, _ time.Time) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, 25*time.Second)
}
func TestSerialISCSIWriteKeepsLegacyBudget(t *testing.T) {
// Budget creation happens after doWrite is called. Freeze time so that
// scheduling between this timestamp and WithTimeout cannot make the correct
// four-second budget look longer than four seconds.
synctest.Test(t, func(t *testing.T) {
b := &serialBudgetBackend{}
h := &SCSIHandler{backend: b, blockSize: 4096, volumeSize: 4096}
start := time.Now()
r := h.doWrite(context.Background(), 0, 1, make([]byte, 4096))
if r.Status != StatusGood || !b.legacy || b.deadline.IsZero() || b.deadline.After(start.Add(4*time.Second)) {
t.Fatalf("serial write status=%d legacy=%v deadline=%v", r.Status, b.legacy, b.deadline)
}
})
}
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"fmt"
"log"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
@@ -277,6 +278,10 @@ func (h *SCSIHandler) doRead(ctx context.Context, lba uint64, transferLen uint32
}
func (h *SCSIHandler) doWrite(ctx context.Context, lba uint64, transferLen uint32, dataOut []byte) SCSIResult {
// The serial session must return to its reader before the initiator NOP window.
// Extended WAL holds require concurrent per-command session handling.
ctx, cancel := frontend.WithLegacyWriteBudget(ctx, time.Time{})
defer cancel()
// G5-5 instrumentation: log every SCSI WRITE arrival at the
// handler. If this line doesn't fire when the kernel initiator
// writes, the iSCSI session/login layer is rejecting the
@@ -0,0 +1,111 @@
package nbd
import (
"bytes"
"context"
"github.com/seaweedfs/seaweed-block/core/frontend"
"io"
"testing"
"time"
)
type deviceBudgetBackend struct {
memoryBackend
writeCtx context.Context
syncCtx context.Context
onSync func(context.Context)
}
func (b *deviceBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.writeCtx = ctx
return len(p), ctx.Err()
}
func (b *deviceBudgetBackend) Sync(ctx context.Context) error {
b.syncCtx = ctx
if b.onSync != nil {
b.onSync(ctx)
}
return nil
}
type deviceBudgetValueKey struct{}
func TestDeviceWriteKeepsLegacyBudget(t *testing.T) {
for _, op := range []string{"write", "fua", "flush"} {
for _, policy := range []string{"unbounded", "earlier_deadline", "cancel_during_sync"} {
t.Run(op+"/"+policy, func(t *testing.T) {
parent := context.WithValue(context.Background(), deviceBudgetValueKey{}, "caller")
var cancel context.CancelFunc
if policy == "earlier_deadline" {
parent, cancel = context.WithTimeout(parent, time.Second)
} else {
parent, cancel = context.WithCancel(parent)
}
defer cancel()
b := &deviceBudgetBackend{}
if policy == "cancel_during_sync" {
b.onSync = func(ctx context.Context) {
cancel()
if ctx.Err() != context.Canceled {
t.Fatalf("Sync lost caller cancellation: %v", ctx.Err())
}
}
}
start := time.Now()
req, reply := new(bytes.Buffer), new(bytes.Buffer)
command := nbdCmdWrite
if op == "fua" {
command |= nbdCmdFUA
}
payload := make([]byte, 4096)
if op == "flush" {
command = nbdCmdFlush
payload = nil
}
writeRequest(t, req, command, [8]byte{1}, 0, payload)
writeRequest(t, req, nbdCmdDisc, [8]byte{2}, 0, nil)
if err := (protocolServer{backend: b, size: 4096}).serve(parent, struct {
io.Reader
io.Writer
}{req, reply}); err != nil {
t.Fatal(err)
}
if op != "flush" {
if b.writeCtx == nil || !frontend.UsesLegacyWriteBudget(b.writeCtx) {
t.Fatal("Write lost legacy transport marker")
}
deadline, bounded := b.writeCtx.Deadline()
if !bounded || !deadline.After(start) || deadline.After(time.Now().Add(4*time.Second)) {
t.Fatalf("Write deadline=%v bounded=%v", deadline, bounded)
}
if prior, ok := parent.Deadline(); ok && !deadline.Equal(prior) {
t.Fatalf("Write lost earlier deadline: %v want %v", deadline, prior)
}
if policy != "earlier_deadline" && b.writeCtx.Err() != context.Canceled {
t.Fatalf("Write context not released: %v", b.writeCtx.Err())
}
} else if b.writeCtx != nil {
t.Fatal("flush called Write")
}
if op != "write" {
if b.syncCtx == nil {
t.Fatal("Sync not called")
}
if frontend.UsesLegacyWriteBudget(b.syncCtx) {
t.Fatal("Sync inherited Write-only marker")
}
got, gotOK := b.syncCtx.Deadline()
want, wantOK := parent.Deadline()
if gotOK != wantOK || !got.Equal(want) {
t.Fatalf("Sync deadline=%v/%v want caller %v/%v", got, gotOK, want, wantOK)
}
if b.syncCtx.Value(deviceBudgetValueKey{}) != "caller" {
t.Fatal("Sync lost caller values")
}
} else if b.syncCtx != nil {
t.Fatal("plain Write called Sync")
}
})
}
}
}
+6 -1
View File
@@ -7,6 +7,9 @@ import (
"fmt"
"io"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
const (
@@ -93,7 +96,9 @@ func (s protocolServer) serve(ctx context.Context, rw io.ReadWriter) error {
if _, err := io.ReadFull(rw, data); err != nil {
return err
}
n, err := s.backend.Write(ctx, int64(offset), data)
writeCtx, cancel := frontend.WithLegacyWriteBudget(ctx, time.Now())
n, err := s.backend.Write(writeCtx, int64(offset), data)
cancel()
if err == nil && n == len(data) && command&nbdCmdFUA != 0 {
err = s.backend.Sync(ctx)
}
+1 -1
View File
@@ -262,7 +262,7 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult {
}
func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
ctx, cancel := frontend.WithBackendWriteBudget(ctx, time.Time{}, h.backend)
defer cancel()
if cmd.NLB == 0 {
return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"}
+1 -1
View File
@@ -605,7 +605,7 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
if arrival.IsZero() {
arrival = req.dispatchReadyAt
}
ctx, cancel := frontend.WithWriteBudget(ctx, arrival)
ctx, cancel := frontend.WithBackendWriteBudget(ctx, arrival, s.handler.backend)
defer cancel()
s.recordWriteCommand()
s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt))
@@ -0,0 +1,103 @@
package ublk
import (
"context"
"github.com/seaweedfs/seaweed-block/core/frontend"
"testing"
"time"
)
type deviceBudgetBackend struct {
failingBackend
writeCtx context.Context
syncCtx context.Context
onSync func(context.Context)
}
func (b *deviceBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.writeCtx = ctx
return len(p), ctx.Err()
}
func (b *deviceBudgetBackend) Sync(ctx context.Context) error {
b.syncCtx = ctx
if b.onSync != nil {
b.onSync(ctx)
}
return nil
}
type deviceBudgetValueKey struct{}
func TestDeviceWriteKeepsLegacyBudget(t *testing.T) {
for _, op := range []string{"write", "fua", "flush"} {
for _, policy := range []string{"unbounded", "earlier_deadline", "cancel_during_sync"} {
t.Run(op+"/"+policy, func(t *testing.T) {
parent := context.WithValue(context.Background(), deviceBudgetValueKey{}, "caller")
var cancel context.CancelFunc
if policy == "earlier_deadline" {
parent, cancel = context.WithTimeout(parent, time.Second)
} else {
parent, cancel = context.WithCancel(parent)
}
defer cancel()
b := &deviceBudgetBackend{}
if policy == "cancel_during_sync" {
b.onSync = func(ctx context.Context) {
cancel()
if ctx.Err() != context.Canceled {
t.Fatalf("Sync lost caller cancellation: %v", ctx.Err())
}
}
}
start := time.Now()
r := request{op: ioOpWrite, nrSectors: 8}
want := int32(4096)
if op == "fua" {
r.flags = ioFlagFUA
}
if op == "flush" {
r = request{op: ioOpFlush}
want = 0
}
if got := newTestHandler(b).handle(parent, r, make([]byte, 4096)); got != want {
t.Fatalf("result=%d want=%d", got, want)
}
if op != "flush" {
if b.writeCtx == nil || !frontend.UsesLegacyWriteBudget(b.writeCtx) {
t.Fatal("Write lost legacy transport marker")
}
deadline, bounded := b.writeCtx.Deadline()
if !bounded || !deadline.After(start) || deadline.After(time.Now().Add(4*time.Second)) {
t.Fatalf("Write deadline=%v bounded=%v", deadline, bounded)
}
if prior, ok := parent.Deadline(); ok && !deadline.Equal(prior) {
t.Fatalf("Write lost earlier deadline: %v want %v", deadline, prior)
}
if policy != "earlier_deadline" && b.writeCtx.Err() != context.Canceled {
t.Fatalf("Write context not released: %v", b.writeCtx.Err())
}
} else if b.writeCtx != nil {
t.Fatal("flush called Write")
}
if op != "write" {
if b.syncCtx == nil {
t.Fatal("Sync not called")
}
if frontend.UsesLegacyWriteBudget(b.syncCtx) {
t.Fatal("Sync inherited Write-only marker")
}
got, gotOK := b.syncCtx.Deadline()
want, wantOK := parent.Deadline()
if gotOK != wantOK || !got.Equal(want) {
t.Fatalf("Sync deadline=%v/%v want caller %v/%v", got, gotOK, want, wantOK)
}
if b.syncCtx.Value(deviceBudgetValueKey{}) != "caller" {
t.Fatal("Sync lost caller values")
}
} else if b.syncCtx != nil {
t.Fatal("plain Write called Sync")
}
})
}
}
}
+3 -1
View File
@@ -148,7 +148,9 @@ func (h handler) serve(ctx context.Context, r request, buf []byte) (result int32
ctx, trace := frontend.BeginDurabilityRequest(ctx, h.backend, kind)
trace.IncludeReceive(received)
defer func() { trace.Finish(result < 0) }()
n, err := h.backend.Write(ctx, int64(offset), data)
writeCtx, cancel := frontend.WithLegacyWriteBudget(ctx, received)
n, err := h.backend.Write(writeCtx, int64(offset), data)
cancel()
if err != nil || n != len(data) {
return errno(syscall.EIO)
}
@@ -0,0 +1,36 @@
package frontend
import (
"fmt"
"time"
)
const walHoldHostMargin = 5 * time.Second
// WALHoldConfig describes the host timeout declared by the operator and the
// maximum time one command may wait for WAL capacity. A target cannot discover
// the initiator's timeout; HostIOTimeout must match the hosts using the volume.
type WALHoldConfig struct {
MaxHold time.Duration
HostIOTimeout time.Duration
}
func DefaultWALHoldConfig() WALHoldConfig {
return WALHoldConfig{MaxHold: 25 * time.Second, HostIOTimeout: 30 * time.Second}
}
// WALHoldConfigError is a startup refusal, not a runtime pressure outcome.
type WALHoldConfigError struct{ Config WALHoldConfig }
func (e *WALHoldConfigError) Error() string {
return fmt.Sprintf("frontend: invalid WAL hold configuration: hold=%s host_io_timeout=%s; require positive hold and hold + 5s <= host_io_timeout", e.Config.MaxHold, e.Config.HostIOTimeout)
}
func (c WALHoldConfig) Validate() error {
// Subtract only after checking the host value. Adding the margin to a
// user-supplied duration could overflow and accept an unsafe configuration.
if c.MaxHold <= 0 || c.HostIOTimeout <= walHoldHostMargin || c.MaxHold > c.HostIOTimeout-walHoldHostMargin {
return &WALHoldConfigError{Config: c}
}
return nil
}
@@ -0,0 +1,54 @@
package frontend
import (
"errors"
"math"
"strings"
"testing"
"time"
)
func TestWALHoldConfigHostTimeoutMargin(t *testing.T) {
cfg := DefaultWALHoldConfig()
if cfg.MaxHold != 25*time.Second || cfg.HostIOTimeout != 30*time.Second {
t.Fatalf("defaults: %+v", cfg)
}
for _, tc := range []struct {
name string
hold, host time.Duration
valid bool
}{
{"default equality", 25 * time.Second, 30 * time.Second, true},
{"raised host", 40 * time.Second, 45 * time.Second, true},
{"lowered host", 10 * time.Second, 15 * time.Second, true},
{"one nanosecond short", 25 * time.Second, 30*time.Second - time.Nanosecond, false},
{"zero hold", 0, 30 * time.Second, false},
{"negative hold", -time.Second, 30 * time.Second, false},
{"zero host", 25 * time.Second, 0, false},
{"negative host", time.Second, -time.Second, false},
{"no room for hold", time.Nanosecond, 5 * time.Second, false},
{"overflow must refuse", time.Duration(math.MaxInt64), 30 * time.Second, false},
{"largest valid", time.Duration(math.MaxInt64) - 5*time.Second, time.Duration(math.MaxInt64), true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := WALHoldConfig{MaxHold: tc.hold, HostIOTimeout: tc.host}
err := cfg.Validate()
if tc.valid {
if err != nil {
t.Fatal(err)
}
} else {
var invalid *WALHoldConfigError
if !errors.As(err, &invalid) {
t.Fatalf("want typed config refusal, got %v", err)
}
if invalid.Config != cfg {
t.Fatalf("refusal lost supplied configuration: %+v", invalid)
}
if !strings.Contains(err.Error(), "host_io_timeout") {
t.Fatalf("missing operator setting: %v", err)
}
}
})
}
}
@@ -47,3 +47,31 @@ func deadlineCausesOnly(err error) bool {
}
return deadlineCausesOnly(errors.Unwrap(err))
}
// WithBackendWriteBudget lets a durable backend apply its command-wide WAL
// hold policy before installing a legacy internal deadline. Earlier caller
// deadlines and cancellation are always retained.
func WithBackendWriteBudget(ctx context.Context, arrival time.Time, b Backend) (context.Context, context.CancelFunc) {
if budget, ok := b.(interface {
WriteCommandContext(context.Context, time.Time) (context.Context, context.CancelFunc)
}); ok {
return budget.WriteCommandContext(ctx, arrival)
}
return WithWriteBudget(ctx, arrival)
}
type legacyWriteBudgetKey struct{}
// WithLegacyWriteBudget keeps final-error device bridges outside the retryable
// WAL hold policy until their device timeout and no-retry policy are wired.
func WithLegacyWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
ctx = context.WithValue(ctx, legacyWriteBudgetKey{}, true)
return WithWriteBudget(ctx, arrival)
}
// UsesLegacyWriteBudget reports an explicit transport choice; backends must not
// replace it with the retryable-protocol WAL hold policy.
func UsesLegacyWriteBudget(ctx context.Context) bool {
legacy, _ := ctx.Value(legacyWriteBudgetKey{}).(bool)
return legacy
}
+21 -2
View File
@@ -377,6 +377,22 @@ func (e errHostHoldsWork) Error() string {
return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", "))
}
// errRetireStorage is a retire that failed to remove the host's record: a
// storage failure, not a refusal (the host may still be registered).
type errRetireStorage struct{ err error }
func (e errRetireStorage) Error() string { return "retire: " + e.err.Error() }
func (e errRetireStorage) Unwrap() error { return e.err }
// metadata keys each held volume for the refusal's typed detail.
func (e errHostHoldsWork) metadata() map[string]string {
md := make(map[string]string, len(e.volumes))
for _, v := range e.volumes {
md[lifecycleclient.VolumeMetadataPrefix+v] = e.server
}
return md
}
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
// Finalize; FormatGateMaster: the one durable step). It is refused while any
// registered host has not reported reads_level >= 1 since this master
@@ -432,7 +448,7 @@ func (h *Host) RetireHost(server, confirm string) error {
return errHostHoldsWork{server: server, volumes: vols}
}
if err := h.lifecycle.Nodes.RemoveNode(server); err != nil {
return fmt.Errorf("retire: %w", err)
return errRetireStorage{err}
}
h.reads.forget(server)
h.log.Printf("blockmaster: host %s retired from the node inventory", server)
@@ -478,9 +494,12 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
defer s.host.workspaceMu.Unlock()
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
var holds errHostHoldsWork
var storage errRetireStorage
switch {
case errors.As(err, &holds):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork).Err()
return nil, lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork, holds.metadata()).Err()
case errors.As(err, &storage):
return nil, status.Error(codes.Internal, err.Error())
case err != nil:
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
@@ -129,6 +129,12 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
if got := reasonOf(moveErr); got != wantReason {
t.Fatalf("level 1: MoveWorkspace onto node-b: reason %q, want %q", got, wantReason)
}
// The forced move's preview answers the same typed reason.
pv, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "p1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
if err != nil || pv.GetAdmitted() || pv.GetReasonCode() != wantReason {
t.Fatalf("level 1: preview of a forced move onto node-b: %+v %v, want reason_code %q", pv, err, wantReason)
}
})
}
}
@@ -278,9 +284,20 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonHostHoldsWork || !strings.Contains(status.Convert(err).Message(), "held") {
t.Fatalf("retire of a host holding a placement: %v (reason %q)", err, reasonOf(err))
}
// The held volumes are typed too: one metadata entry per volume.
if _, md := lifecycleclient.ReasonDetail(err); len(md) != 1 || md[lifecycleclient.VolumeMetadataPrefix+"held"] != "node-b" {
t.Fatalf("retire refusal metadata %v, want volume.held = node-b", md)
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("retire with a confirm that does not match: %v", err)
}
// A failure to remove the host's record is a storage failure (Internal),
// not a refusal: the CLI then answers "failed", exit 1.
r.m.Lifecycle().Nodes.SetPersistHookForTest(func() error { return errors.New("injected record removal failure") })
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); status.Code(err) != codes.Internal {
t.Fatalf("retire whose record removal failed: %v, want Internal", err)
}
r.m.Lifecycle().Nodes.SetPersistHookForTest(nil)
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil {
t.Fatalf("retire of a host holding nothing: %v", err)
}
@@ -583,6 +583,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
out.Reason = status.Convert(err).Message()
out.Code = status.Code(err).String()
out.ReasonCode = lifecycleclient.Reason(err)
return nil
}
r, target, _, why, err := s.workspaceMoveCheckLocked(q)
@@ -594,7 +595,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS
switch {
case why.text != "":
out.Admitted, out.Reason = false, why.text
out.Admitted, out.Reason, out.ReasonCode = false, why.text, why.reason
case !pv.Admitted:
out.Reason = pv.Reason
case pv.Replay:
@@ -603,6 +604,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
out.Admitted, out.Reason = false, err.Error()
out.Code = status.Code(workspaceError(err)).String()
out.ReasonCode = lifecycleclient.Reason(workspaceError(err))
}
}
return nil
@@ -623,6 +625,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
if err != nil {
out.Admitted, out.HeadError = false, err.Error()
out.Code = status.Code(workspaceError(err)).String()
out.ReasonCode = lifecycleclient.Reason(workspaceError(err))
out.Reason = "workspace move: HEAD read failed: " + err.Error()
return out, nil
}
@@ -415,6 +415,8 @@ func chunkErrorCode(err error) (int, string, bool) {
// after capacity is added, so it is told apart from an unreachable one.
case errors.Is(err, storage.ErrChunkRemoteFull):
return http.StatusServiceUnavailable, chunkstore.CodeRemoteFull, true
case errors.Is(err, layout.ErrQueueFull):
return http.StatusConflict, chunkstore.CodeQueueFull, true
case errors.Is(err, storage.ErrChunkRemoteUnavailable):
return http.StatusServiceUnavailable, chunkstore.CodeRemoteUnavailable, true
case errors.Is(err, durable.ErrNotChunkVolume), errors.Is(err, durable.ErrVolumeNotOpen):
@@ -220,6 +220,7 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) {
{fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true},
{fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true},
{fmt.Errorf("x: %w", layout.ErrPrecondition), "head_conflict", 409, true}, // a raced catalog transition (snapshot delete)
{fmt.Errorf("x: %w", layout.ErrQueueFull), "queue_full", 409, true},
// The precondition is the last cause to decide: joined with any
// terminal one, that one is reported.
{errors.Join(storage.ErrChunkLayerClosed, layout.ErrPrecondition), "closing", 503, false},
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// statusRoutes are the status routes and the type each one encodes. The
@@ -28,6 +29,7 @@ var statusRoutes = []struct {
{"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})},
{"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})},
{"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})},
{"/status/wal-hold", "atomic WAL hold observations scoped to this process and store open", reflect.TypeOf(walHoldStatusBody{})},
{"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})},
{"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.Usage{})},
{"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})},
@@ -36,6 +38,12 @@ var statusRoutes = []struct {
{"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})},
}
type walHoldStatusBody struct {
ProcessID string // holder process incarnation
VolumeID string // the served volume
WALHold storage.WALHoldStatus // atomic store-open observations
}
type peersStatusBody struct {
VolumeID string // the served volume
ReplicaID string // this host's replica
@@ -191,6 +191,8 @@ const (
// adds G9A control-plane vocabulary so operators/tests do not infer
// replica readiness from authority movement.
type StatusProjection struct {
Degraded bool // WAL reclaim stalled for at least five seconds; diagnostic, not an authority or readiness change
DegradedReason string `json:",omitempty"`
frontend.Projection
// Version is the build revision plus modified flag, matching master product_revision.
// Unknown provenance does not prove that two builds are equal.
@@ -398,6 +400,8 @@ func (s *StatusServer) Start(addr string) (string, error) {
mux := http.NewServeMux()
registerLabHeapProfile(mux)
mux.HandleFunc("/status", s.handleStatus)
mux.HandleFunc("/metrics", s.handleWALHoldMetrics)
mux.HandleFunc("/status/wal-hold", s.handleWALHoldStatus)
mux.HandleFunc("/status/peers", s.handleStatusPeers)
mux.HandleFunc("/status/durable", s.handleStatusDurable)
mux.HandleFunc("/status/nvme", s.handleStatusNVMe)
@@ -616,6 +620,10 @@ func (s *StatusServer) statusProjection() StatusProjection {
for _, st := range src.DurableStatuses() {
if st.VolumeID == p.VolumeID {
p.Warnings = append(p.Warnings, st.Warnings...)
if st.Degraded {
p.Degraded = true
p.DegradedReason = "wal_reclaim_stalled"
}
}
}
// The frontend readiness rule: the backend's one "may serve" function decides; an
@@ -0,0 +1,79 @@
package volume
import (
"encoding/json"
"fmt"
"net/http"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// This read-only route shares the status listener's access policy. There are
// no per-request or per-LBA labels; counters are scoped to a volume's open.
func (s *StatusServer) handleWALHoldMetrics(w http.ResponseWriter, r *http.Request) {
s.serveWALHold(w, r, true)
}
func (s *StatusServer) handleWALHoldStatus(w http.ResponseWriter, r *http.Request) {
s.serveWALHold(w, r, false)
}
func (s *StatusServer) serveWALHold(w http.ResponseWriter, r *http.Request, metrics bool) {
if r.Method != http.MethodGet {
http.Error(w, "metrics requires GET", http.StatusMethodNotAllowed)
return
}
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
http.Error(w, "metrics restricted to loopback", http.StatusForbidden)
return
}
id := r.URL.Query().Get("volume")
if id == "" {
http.Error(w, "missing volume", http.StatusBadRequest)
return
}
p := s.authorityProjection()
if id != p.VolumeID {
http.NotFound(w, r)
return
}
s.mu.Lock()
src := s.durableSource
s.mu.Unlock()
reporter, ok := src.(interface {
WALHoldStatuses() map[string]storage.WALHoldStatus
})
if !ok {
http.NotFound(w, r)
return
}
st, ok := reporter.WALHoldStatuses()[id]
if !ok {
http.NotFound(w, r)
return
}
if !metrics {
processID := ""
if host, ok := s.view.probe.(*Host); ok && host != nil {
processID = host.incarnation
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(struct {
ProcessID string
VolumeID string
WALHold storage.WALHoldStatus
}{processID, id, st})
return
}
degraded := 0
if st.Degraded {
degraded = 1
}
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
fmt.Fprintf(w, "swblock_wal_reclaim_degraded{volume=%q} %d\n", id, degraded)
fmt.Fprintf(w, "swblock_wal_reclaimed_bytes_total{volume=%q} %d\n", id, st.ReclaimedBytes)
fmt.Fprintf(w, "swblock_wal_extent_bytes_total{volume=%q} %d\n", id, st.ExtentBytes)
fmt.Fprintf(w, "swblock_wal_hold_active{volume=%q} %d\n", id, st.ActiveWaiters)
fmt.Fprintf(w, "swblock_wal_hold_commands_total{volume=%q} %d\n", id, st.Commands)
fmt.Fprintf(w, "swblock_wal_reclaim_stalled_total{volume=%q} %d\n", id, st.StallAnswers)
fmt.Fprintf(w, "swblock_wal_hold_cap_total{volume=%q} %d\n", id, st.CapAnswers)
fmt.Fprintf(w, "swblock_wal_hold_wait_nanoseconds_total{volume=%q} %d\n", id, st.WaitNanos)
}
@@ -0,0 +1,72 @@
package volume
import (
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type holdMetricsSource struct {
stubDurableStatusSource
holds map[string]storage.WALHoldStatus
}
func (s holdMetricsSource) WALHoldStatuses() map[string]storage.WALHoldStatus { return s.holds }
type atomicOnlyHoldSource struct{ holdMetricsSource }
func (atomicOnlyHoldSource) DurableStatuses() []durable.VolumeStatus {
panic("metrics must not read locked frontiers")
}
func TestWALHoldMetricsAtomicSourceAndAccess(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
s.SetDurableStatusSource(atomicOnlyHoldSource{holdMetricsSource{holds: map[string]storage.WALHoldStatus{"v1": {Degraded: true, ActiveWaiters: 1, Commands: 3, StallAnswers: 2, CapAnswers: 1, WaitNanos: 123}}}})
for _, tc := range []struct {
query, remote string
want int
}{
{"?volume=v1", "127.0.0.1:9000", 200}, {"?volume=other", "127.0.0.1:9000", 404}, {"", "127.0.0.1:9000", 400}, {"?volume=v1", "192.0.2.1:9000", 403},
} {
r := httptest.NewRequest("GET", "/metrics"+tc.query, nil)
r.RemoteAddr = tc.remote
w := httptest.NewRecorder()
s.handleWALHoldMetrics(w, r)
if w.Code != tc.want {
t.Fatalf("%s %s status%d want%d", tc.remote, tc.query, w.Code, tc.want)
}
if tc.want == 200 && !strings.Contains(w.Body.String(), "swblock_wal_reclaim_degraded{volume=\"v1\"} 1\n") {
t.Fatalf("missing degraded metric: %s", w.Body.String())
}
}
}
func TestWALHoldDegradedDoesNotChangeReadiness(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
source := holdMetricsSource{stubDurableStatusSource: stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}}
s.SetDurableStatusSource(source)
before := s.statusProjection()
source.vols[0].Degraded = true
after := s.statusProjection()
if !after.Degraded || after.DegradedReason != "wal_reclaim_stalled" {
t.Fatalf("degraded status: %+v", after)
}
if after.FrontendPrimaryReady != before.FrontendPrimaryReady || after.Healthy != before.Healthy {
t.Fatal("diagnostic changed authority/readiness")
}
}
func TestWALHoldAtomicStatusDoesNotReadFrontiers(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
s.SetDurableStatusSource(atomicOnlyHoldSource{holdMetricsSource{holds: map[string]storage.WALHoldStatus{"v1": {Degraded: true, ReclaimedBytes: 4096}}}})
r := httptest.NewRequest("GET", "/status/wal-hold?volume=v1", nil)
r.RemoteAddr = "127.0.0.1:9000"
w := httptest.NewRecorder()
s.handleWALHoldStatus(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "\"Degraded\":true") || !strings.Contains(w.Body.String(), "\"ReclaimedBytes\":4096") {
t.Fatalf("atomic status: %d %s", w.Code, w.Body.String())
}
}
+16 -1
View File
@@ -68,7 +68,17 @@ type NodeInventoryStore struct {
mu sync.Mutex
dir string
records map[string]NodeRegistration
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
failWrite func() error // tests: a non-nil error fails the next record write or removal
}
// SetPersistHookForTest installs (nil clears) a callback that each later
// record write or removal of this store runs under the store mutex first. A
// non-nil error fails that change with nothing changed. Tests only.
func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) {
s.mu.Lock()
defer s.mu.Unlock()
s.failWrite = hook
}
// OpenNodeInventoryStore opens or creates a node inventory store.
@@ -155,6 +165,11 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
if s.failWrite != nil {
if err := s.failWrite(); err != nil {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
}
}
delete(s.records, serverID)
if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
+16 -3
View File
@@ -932,7 +932,11 @@ type WorkspaceMovePreview struct {
HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"`
HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"`
// gRPC status code name for a refusal; empty when admitted. Additive output only.
Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"`
Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"`
// The refusal's typed reason (the reason a MoveWorkspace refusal would carry
// in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or
// when the refusal has none. Additive output only.
ReasonCode string `protobuf:"bytes,14,opt,name=reason_code,json=reasonCode,proto3" json:"reason_code,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1058,6 +1062,13 @@ func (x *WorkspaceMovePreview) GetCode() string {
return ""
}
func (x *WorkspaceMovePreview) GetReasonCode() string {
if x != nil {
return x.ReasonCode
}
return ""
}
type WorkspaceStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"`
@@ -1350,7 +1361,7 @@ const file_workspace_proto_rawDesc = "" +
"\n" +
"request_id\x18\x02 \x01(\tR\trequestId\"Z\n" +
"\x13WorkspaceLostRanges\x12C\n" +
"\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xb1\x03\n" +
"\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xd2\x03\n" +
"\x14WorkspaceMovePreview\x12\x1a\n" +
"\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" +
@@ -1369,7 +1380,9 @@ const file_workspace_proto_rawDesc = "" +
"\fhead_time_ns\x18\v \x01(\x03R\n" +
"headTimeNs\x12&\n" +
"\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\x12\x12\n" +
"\x04code\x18\r \x01(\tR\x04code\"\xb2\x02\n" +
"\x04code\x18\r \x01(\tR\x04code\x12\x1f\n" +
"\vreason_code\x18\x0e \x01(\tR\n" +
"reasonCode\"\xb2\x02\n" +
"\x0fWorkspaceStatus\x12A\n" +
"\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" +
"\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" +
@@ -67,3 +67,7 @@ func ReasonDetail(err error) (string, map[string]string) {
// HostMetadataPrefix keys one refused host in a reason's metadata:
// "host.<server id>" maps to what that host reported.
const HostMetadataPrefix = "host."
// VolumeMetadataPrefix keys one volume in a reason's metadata:
// "volume.<volume id>" maps to the host that holds it.
const VolumeMetadataPrefix = "volume."
@@ -84,6 +84,10 @@ message WorkspaceMovePreview {
int64 head_time_ns = 11; bool head_time_known = 12;
// gRPC status code name for a refusal; empty when admitted. Additive output only.
string code = 13;
// The refusal's typed reason (the reason a MoveWorkspace refusal would carry
// in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or
// when the refusal has none. Additive output only.
string reason_code = 14;
}
message WorkspaceStatus {
WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2;
@@ -455,7 +455,7 @@ func TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites(t *testing.T) {
// An attached layer without the transition protocol still refuses, writing
// nothing. Actual supported layers are covered by the chunk/provider controls.
func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
s, _ := newMappedCheckpointStoreV3(t)
cfg := ctConfig(1)
cfg.Bitmap = nil
cfg.BarrierBound = 1
@@ -463,11 +463,11 @@ func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing
hooks := *s.chunk.Load()
hooks.baseTransitionV3 = nil
s.chunk.Store(&hooks)
a0, b0 := slotsV3(t, path)
a0, b0 := slotsV3Of(t, s) // the store holds the file's lock: read through it
if _, err := s.beginBaseInstallV3(0, idA); !errors.Is(err, errV3NotYet) {
t.Fatalf("begin with a chunk layer attached: err = %v, want errV3NotYet", err)
}
if a, b := slotsV3(t, path); a != a0 || b != b0 {
if a, b := slotsV3Of(t, s); a != a0 || b != b0 {
t.Fatal("a refused begin wrote a descriptor slot")
}
}
@@ -2,6 +2,7 @@ package storage
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"errors"
@@ -325,7 +326,7 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("the injected cut answered %v, want its outcome unknown", err)
}
w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
last5 := w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
var err error
var last chunkCutResult
for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish
@@ -346,6 +347,15 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want)
}
}
// Byte for byte: the remote is exactly the written image (the baseline
// with the three writes), not merely different in the right chunks.
if want := w.imageAt(last5); !bytes.Equal(img, want) {
for at := 0; at < len(want); at += ctBlockSize {
if !bytes.Equal(img[at:at+ctBlockSize], want[at:at+ctBlockSize]) {
t.Fatalf("the remote image differs from the written one at block %d", at/ctBlockSize)
}
}
}
}
// The candidate set's OR keeps the summary, so a set ORed back is listed in
@@ -600,3 +610,122 @@ func TestACutThatAbortsAfterTakingTheRequestReissuesIt(t *testing.T) {
t.Fatalf("the next cut left request generation %d pending", got)
}
}
// The live touched set exists once the layer attaches, before any write,
// on both store formats: a first map entry change only sets a bit (never
// allocates the bitmap under the store's lock). On v1.0 the record shadow's
// attach already seeds it; v1.1's record open does not, so it is allocated
// explicitly before the hooks are published.
func TestTheTouchedSetExistsAtAttach(t *testing.T) {
for _, format := range []string{"v1.0", "v1.1"} {
t.Run(format, func(t *testing.T) {
if format == "v1.1" {
withV11Format(t)
} else {
v10Only(t)
}
s, _ := newChunkTestStore(t)
// attachChunkLayer itself, not mustAttach: its reconcile wait reads
// Stats, whose candidate listing would seed the set.
layer, err := attachChunkLayer(s, newFakeChunkRemote(), ctConfig(1))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { // bounded, as mustAttach's
done := make(chan struct{})
go func() { _ = layer.Close(); close(done) }()
select {
case <-done:
case <-time.After(ctLocalBound):
t.Errorf("chunk layer Close did not return within %v", ctLocalBound)
}
})
l := layer.(*chunkLayerImpl)
l.unkMu.Lock()
allocated := l.touched != nil
l.unkMu.Unlock()
if !allocated {
t.Fatal("no touched set after attach: the first write would allocate it under the store lock")
}
})
}
}
// The status's DirtyChunks is the exact union of the live candidates and a
// cut's in-flight ones while its upload runs (a chunk in both counts once,
// one only in flight still counts), and the in-flight part leaves the count
// once that cut's HEAD installs.
func TestStatsCountsACutsCandidatesUntilItsHeadInstalls(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
l := layer.(*chunkLayerImpl)
w := newWriteLog()
if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set
t.Fatal(err)
}
w.write(t, s, 2*ctChunkBlocks, 0x22) // chunk 2: in flight only, once flushed
w.write(t, s, 3*ctChunkBlocks, 0x33) // chunk 3: in flight, and written again below
entered, release := holdPuts(t, f)
t.Cleanup(release)
done := startCapture(t, layer)
waitKey(t, entered, "chunk upload")
w.write(t, s, 3*ctChunkBlocks+1, 0x3b) // chunk 3 again: live and in flight
w.write(t, s, 4*ctChunkBlocks, 0x44) // chunk 4: live only
mustSyncFlush(t, s) // chunk 2's write leaves the dirty map
during := l.Stats().DirtyChunks
release()
if err := waitErr(t, done, "capture"); err != nil {
t.Fatal(err)
}
after := l.Stats().DirtyChunks
if during != 3 {
t.Fatalf("during the cut's upload: %d dirty chunks, want 3 (chunk 2 in flight, 3 in both, 4 live)", during)
}
if after != 2 {
t.Fatalf("after the cut's HEAD installed: %d dirty chunks, want 2 (chunks 3 and 4, written since)", after)
}
}
// A pre-copy cut keeps its frontend drained through the candidate step, so
// every walk it makes there is pause work, charged exactly once: over the
// same drained cut with nothing to walk, k dirty chunks add 2k (the
// dirty-set visit and the judging of each), and a BASE's whole-volume pass
// over N chunks adds 2N (the pass and the judging of each). A walk charged
// before it ran, or charged twice, misses the exact delta.
func TestADrainedCutChargesItsWholeVolumeWalkToThePause(t *testing.T) {
s, _ := newChunkTestStore(t)
l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl)
if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set
t.Fatal(err)
}
l.precopyPrepare = func(context.Context) (func(), error) { return func() {}, nil } // drained to the freeze
t.Cleanup(func() { l.precopyPrepare = nil })
cut := func(what string) int64 {
t.Helper()
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatalf("%s: %v", what, err)
}
return r.Stats.PauseCandidateOps
}
plain := cut("a drained cut with nothing to walk")
const k = 3
l.stMu.Lock()
for i := uint64(0); i < k; i++ {
l.dirty[i] = true
}
l.stMu.Unlock()
if got, want := cut("k dirty chunks")-plain, int64(2*k); got != want {
t.Fatalf("a drained cut over %d dirty chunks charged %d more pause operations, want %d", k, got, want)
}
l.stMu.Lock()
l.allDirty = true // as after a BASE: every chunk is walked
l.stMu.Unlock()
if got, want := cut("a whole-volume pass")-plain, 2*int64(l.numChunks); got != want {
t.Fatalf("a drained cut's whole-volume pass charged %d more pause operations, want %d (the pass and the judging, %d chunks each)", got, want, l.numChunks)
}
if got := cut("nothing to walk again"); got != plain {
t.Fatalf("a drained cut with nothing to walk after them charged %d, want %d (nothing carried over)", got, plain)
}
}
+19 -2
View File
@@ -475,6 +475,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
hooks.beforeMutation = l.beforeCOWMutation
hooks.beforeDestructive = l.holdCOWDestructive
// The live touched set exists before the hooks are published: the first
// map entry change (under WALStore.mu) only sets a bit, never allocates a
// volume-sized bitmap.
l.unkMu.Lock()
l.touchedLocked(false)
l.unkMu.Unlock()
if !s.chunk.CompareAndSwap(nil, hooks) {
l.cancel()
return nil, errors.New("storage: a chunk layer is already attached")
@@ -1826,7 +1832,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
candidates, visits := l.candidatesFrom(members, h)
visits += int64(len(taken.summary)) // the summary words the walk read
l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause
for idx := range dirtyTaken {
visits++
candidates[idx] = true
@@ -1844,6 +1849,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
}
l.stMu.Unlock()
// Charged after every walk (the touched set, the dirty set, a BASE's
// whole-volume pass): a drained pre-copy frontend is still paused here.
l.pauseOp(int(visits))
candidateOracleCompare(oracleWant, candidates) // tests only
// A chunk known to hold HEAD's bytes at its current version (a clean
// fill, or a compare by a cut that did not publish) is not compared
@@ -2899,7 +2907,16 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
out.ReconcileDone = 0
l.stMu.Unlock()
out.DirtyChunks = len(l.captureCandidates())
dirty := l.captureCandidates()
// A cut's judged candidates stay counted until its HEAD installs: one the
// flush checkpointed out of the dirty map meanwhile is in neither source
// above. Read under stMu; the cut keeps its own taken set.
l.stMu.Lock()
for idx := range l.inflight {
dirty[idx] = true
}
l.stMu.Unlock()
out.DirtyChunks = len(dirty)
out.AbsentChunks = l.absentHydratable()
return out
@@ -35,7 +35,7 @@ var walStoreMethods = map[string]string{
"Coverage": "read (atomic local bitmap coverage and chunk position)",
"AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "ChunkStateMarker": "read (the descriptor's chunk-state marker)", "Boundaries": "read", "CheckpointLSN": "read",
"CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read",
"DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "ReclaimProgress": "read",
"DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "ReclaimProgress": "read", "WALHoldStatus": "read (atomic diagnostic hold metrics)",
"InstalledBaseLSN": "read", "LayoutIdentity": "read", "NextLSN": "read", "NumBlocks": "read",
"OwnerChunkAttachDurableV3": "read", "Read": "read", "ReadContext": "read", "RecoveryMode": "read",
"RecoveryRetentionLSNs": "read", "RecoveryWarnings": "read", "ScanLBAs": "read", "WALCapacityBytes": "read",
@@ -14,6 +14,28 @@ import (
// dark: only these tests call it.
// slotsV3 decodes both descriptor slots of the file at path.
// slotsV3Of reads both descriptor slots through the open store's own file:
// a second handle cannot read a range the store holds locked (Windows).
func slotsV3Of(t *testing.T, s *WALStore) (a, b descriptorV3) {
t.Helper()
for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} {
buf := make([]byte, slotSizeV3)
if _, err := s.fd.ReadAt(buf, off); err != nil {
t.Fatal(err)
}
d, err := decodeSlotV3(buf, nil)
if err != nil {
t.Fatalf("slot %d: %v", i, err)
}
if i == 0 {
a = d
} else {
b = d
}
}
return a, b
}
func slotsV3(t *testing.T, path string) (a, b descriptorV3) {
t.Helper()
f, err := os.Open(path)
@@ -383,7 +405,7 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) {
// unchanged (same position and LSN), but it is a new write: the read must
// retry and return it, not report WAL damage.
func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage(t *testing.T) {
s, path := newStoreV3(t, WModeStrict)
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
resolved, invalid := newHeldV3(t), newHeldV3(t)
writeSynced(t, s, 1, 1) // LSN 1
@@ -403,7 +425,7 @@ func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage
})
waitV3(t, resolved.parked, "Read after resolving LSN 2")
s.v3.testReadResolved = nil
damageRecord(t, path, 2)
damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked
if _, err := s.Recover(); err != nil { // drops LSN 2 and fences its bytes
t.Fatalf("Recover: %v", err)
}
+134 -94
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
@@ -34,13 +35,19 @@ var errVolumeClosed = errors.New("storage: volume closed during admission wait")
// for the hard watermark to clear reduces the budget available
// for semaphore acquisition.
type walAdmission struct {
sem chan struct{} // counting semaphore for concurrent appenders
walUsed func() float64
notifyFn func() // wakes flusher
softMark float64
hardMark float64
closedFn func() bool
faultFn func() error // lock-free terminal fault lookup; nil for controllers without a store
hardBlocked atomic.Bool // last head pressure sample; retained until a head observes capacity
queueMu sync.Mutex
first, last *walAdmissionTicket
active *walAdmissionTicket // an admitted append cannot be preempted
nextOrder atomic.Uint64
headVersion uint64
sem chan struct{} // counting semaphore for concurrent appenders
walUsed func() float64
notifyFn func() // wakes flusher
softMark float64
hardMark float64
closedFn func() bool
faultFn func() error // lock-free terminal fault lookup; nil for controllers without a store
sleepFn func(time.Duration) // replaceable for tests
@@ -109,100 +116,127 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
if fault := a.terminalFault(); fault != nil {
return fault
}
return admissionContextError(err)
return a.commandWaitError(ctx, admissionContextError(err))
}
deadline := time.NewTimer(timeout)
defer deadline.Stop()
pressure, err := sample()
if err != nil {
return err
hold := admissionHold(ctx, a)
if hold != nil {
started := time.Now()
defer func() { hold.waitNanos += time.Since(started).Nanoseconds(); hold.endWait() }()
}
deadline := &time.Timer{}
if timeout > 0 || hold == nil {
deadline = time.NewTimer(timeout)
defer deadline.Stop()
}
ticket := a.enqueueTicket(admissionArrival(ctx, a))
granted := false
defer func() {
if !granted {
a.removeTicket(ticket)
}
}()
// Hard watermark: wait for flusher to drain before competing
// for the semaphore.
if pressure >= a.hardMark {
a.notifyFn()
hardStart := time.Now()
for {
pressure, err = sample()
if err != nil {
return err
}
if pressure < a.hardMark {
break
}
if err := a.terminalFault(); err != nil {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return err
}
if !contextual && a.closedFn() {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return errVolumeClosed
retry:
for {
if err := a.waitForTicket(ctx, deadline, ticket, contextual); err != nil {
return err
}
first, _, version := a.headState(ticket)
if !first {
continue
}
pressure, err := sample()
if err != nil {
return err
}
a.hardBlocked.Store(pressure >= a.hardMark)
// Hard watermark: wait for flusher to drain before competing
// for the semaphore.
if pressure >= a.hardMark {
if hold != nil {
hold.start()
}
a.notifyFn()
hardStart := time.Now()
for {
if first, _, current := a.headState(ticket); !first || current != version {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
continue retry
}
if hold != nil {
if err := hold.check(); err != nil {
return err
}
}
pressure, err = sample()
if err != nil {
return err
}
a.hardBlocked.Store(pressure >= a.hardMark)
if pressure < a.hardMark {
break
}
if err := a.terminalFault(); err != nil {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return err
}
if !contextual && a.closedFn() {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return errVolumeClosed
}
a.notifyFn()
select {
case <-ctx.Done():
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
default:
}
a.sleepFn(2 * time.Millisecond)
}
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
// Pressure dropped — fall through to semaphore acquisition.
} else if pressure >= a.softMark {
// Soft watermark: small delay to desynchronize writer herd.
a.notifyFn()
scale := (pressure - a.softMark) / (a.hardMark - a.softMark)
if scale > 1 {
scale = 1
}
// Scale: softMark→0ms, hardMark→5ms.
delay := time.Duration(scale * 5 * float64(time.Millisecond))
if delay > 0 {
softStart := time.Now()
a.sleepFn(delay)
a.softPressureWaitNs.Add(time.Since(softStart).Nanoseconds())
}
}
// Revalidate queue authority at the capacity grant: an older command's
// next batch may have entered while this invocation sampled or slept.
if a.tryGrantTicket(ticket, version) {
granted = true
return nil
}
if first, _, current := a.headState(ticket); first && current == version {
// A semaphore-only waiter still yields to cancellation, Close and
// terminal-fault sampling; it must not busy-spin on a full token set.
select {
case <-ctx.Done():
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return admissionContextError(ctx.Err())
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return ErrWALPressureTimeout
default:
}
a.sleepFn(2 * time.Millisecond)
}
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
// Pressure dropped — fall through to semaphore acquisition.
} else if pressure >= a.softMark {
// Soft watermark: small delay to desynchronize writer herd.
a.notifyFn()
scale := (pressure - a.softMark) / (a.hardMark - a.softMark)
if scale > 1 {
scale = 1
}
// Scale: softMark→0ms, hardMark→5ms.
delay := time.Duration(scale * 5 * float64(time.Millisecond))
if delay > 0 {
softStart := time.Now()
a.sleepFn(delay)
a.softPressureWaitNs.Add(time.Since(softStart).Nanoseconds())
}
}
// Acquire semaphore slot using the same deadline.
select {
case a.sem <- struct{}{}:
return nil
default:
}
closeTick := time.NewTicker(5 * time.Millisecond)
defer closeTick.Stop()
for {
select {
case a.sem <- struct{}{}:
return nil
case <-ctx.Done():
if err := a.terminalFault(); err != nil {
return err
}
return admissionContextError(ctx.Err())
case <-deadline.C:
if err := a.terminalFault(); err != nil {
return err
}
return ErrWALPressureTimeout
case <-closeTick.C:
if contextual {
if _, err := sample(); err != nil {
return err
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
case <-time.After(5 * time.Millisecond):
}
if err := a.terminalFault(); err != nil {
return err
@@ -215,7 +249,13 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
}
// Release returns a write slot to the semaphore.
func (a *walAdmission) Release() { <-a.sem }
func (a *walAdmission) Release() {
<-a.sem
a.queueMu.Lock()
a.active = nil
a.unlinkTicketLocked(a.first)
a.queueMu.Unlock()
}
// terminalFault is sampled only on waiting paths. The store supplies its atomic
// latch lookup; this does not acquire a store lock or perform persistence I/O.
@@ -0,0 +1,76 @@
package storage
import (
"context"
"math"
"time"
)
// lockFastWALAppend reserves this call's append capacity without a queue ticket.
// Success returns with s.mu held: no other production append can consume the
// observed room until this call appends or refuses. The queue check is atomic
// with that reservation under queueMu. A waiter arriving later must sample
// capacity under s.mu, after this reservation has finished.
//
// Lock order is s.mu -> descriptor snapshot -> writer snapshot -> queueMu;
// descriptor/writer locks are released before queueMu. queueMu covers no file
// I/O, callback or waiting lock. False returns with every lock released.
func (s *WALStore) lockFastWALAppend(ctx context.Context, deadline time.Time, blocks int) (bool, error) {
a := s.admission
if a == nil || s.v3 == nil {
return false, nil
}
started := time.Now()
s.mu.Lock()
s.instr.recordWriteCommitLockWait(time.Since(started))
keep := false
defer func() {
if !keep {
s.mu.Unlock()
}
}()
if s.closed {
return false, errVolumeClosed
}
if err := s.writeBudgetError(ctx, deadline); err != nil {
return false, err
}
w := s.v3.w
if w == nil {
return false, nil
}
d, floor, valid := s.v3.pub.walSnapshotV3()
w.mu.Lock()
head, nonce := w.head, w.nonce
w.mu.Unlock()
if !valid || d.WALSize == 0 || d.BlockSize == 0 || nonce != d.Nonce || head < floor || head-floor > d.WALSize {
return false, nil
}
// The normal encoder remains the format/geometry authority. Do not overflow
// its size arithmetic when deciding whether this optional path is available.
if blocks <= 0 || uint64(blocks) > (math.MaxUint32-walEntryHeaderSizeV3)/uint64(d.BlockSize) {
return false, nil
}
size := uint64(walEntryHeaderSizeV3) + uint64(blocks)*uint64(d.BlockSize)
remaining := d.WALSize - head%d.WALSize
gap := uint64(0)
if size > remaining {
gap = remaining
}
free := d.WALSize - (head - floor)
if gap > free || size > free-gap || gap > counterMaxV3-head || size > counterMaxV3-head-gap {
return false, nil
}
a.queueMu.Lock()
if a.first != nil || a.active != nil || len(a.sem) != 0 {
a.queueMu.Unlock()
return false, nil
}
// s.mu is still held: this capacity cannot be consumed by another append.
keep = true
a.queueMu.Unlock()
if float64(head-floor)/float64(d.WALSize) >= a.softMark {
a.notifyFn()
}
return true, nil
}
@@ -0,0 +1,197 @@
package storage
import (
"context"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestWALAdmissionFastPathHasNoTicket(t *testing.T) {
for _, batch := range []bool{false, true} {
t.Run(map[bool]string{false: "write", true: "batch"}[batch], func(t *testing.T) {
s := admissionPressureV3(t, 0)
write := s.v3.w.writeAt
calls := 0
s.v3.w.writeAt = func(p []byte, off int64) (int, error) {
calls++
a := s.admission
a.queueMu.Lock()
queued := a.first != nil || a.last != nil || a.active != nil || len(a.sem) != 0
a.queueMu.Unlock()
if queued {
t.Error("healthy append allocated or owns a queue ticket")
}
return write(p, off)
}
if batch {
if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)}); err != nil {
t.Fatal(err)
}
} else {
if _, err := s.Write(0, blk(1)); err != nil {
t.Fatal(err)
}
}
if calls != 1 {
t.Fatalf("physical appends=%d", calls)
}
})
}
}
func TestWALAdmissionFastPathCannotPassAWaiter(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
// A full-WAL waiter may exist just as reclaim frees space. Room alone must
// never authorize a new call to bypass that waiter.
ticket := s.admission.enqueueTicket(nil)
pending := true
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
defer func() {
cancel()
if pending {
s.admission.removeTicket(ticket)
}
synctest.Wait()
}()
go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }()
synctest.Wait()
select {
case err := <-done:
t.Fatalf("new append passed waiter: %v", err)
default:
}
s.admission.removeTicket(ticket)
pending = false
synctest.Wait()
if err := <-done; err != nil {
t.Fatal(err)
}
})
}
func TestWALAdmissionFastReservationKeepsAppendLock(t *testing.T) {
s := admissionPressureV3(t, 0)
// The reservation is the store's append lock, not a detachable semaphore
// token. Observe it at the actual pwrite boundary.
original := s.v3.w.writeAt
s.v3.w.writeAt = func(p []byte, off int64) (int, error) {
if s.mu.TryLock() {
s.mu.Unlock()
t.Error("capacity reservation released before append")
}
return original(p, off)
}
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
if _, err := s.WriteContext(ctx, 0, blk(1)); err != nil {
t.Fatal(err)
}
}
// A competing real append must not consume reserved room between admission and
// pwrite. Checking TryLock only at pwrite misses a release followed by reacquire.
func TestWALAdmissionFastReservationExcludesCompetingAppend(t *testing.T) {
// Even store cleanup can block after a lock regression. The parent kills
// and joins this child at its own bound rather than hanging the package.
if !inBoundedChild(t) {
if err := runBoundedChild(t.Name(), 20*time.Second); err != nil {
t.Fatal(err)
}
return
}
for _, batch := range []bool{false, true} {
t.Run(map[bool]string{false: "write", true: "batch"}[batch], func(t *testing.T) {
s := admissionPressureV3(t, 0)
reserved, release, competingAdmitted := make(chan struct{}), make(chan struct{}), make(chan struct{})
var calls atomic.Int32
s.testAfterAdmit = func() {
switch calls.Add(1) {
case 1:
close(reserved)
<-release
case 2:
close(competingAdmitted)
}
}
type result struct {
lsn uint64
err error
}
first, second := make(chan result, 1), make(chan result, 1)
var releaseOnce sync.Once
unblock := func() { releaseOnce.Do(func() { close(release) }) }
join := func(name string, done <-chan result) result {
select {
case got := <-done:
return got
case <-time.After(2 * time.Second):
t.Errorf("%s append did not finish within 2s after release", name)
return result{}
}
}
firstJoined, secondStarted, secondJoined := false, false, false
defer func() {
unblock()
if !firstJoined {
join("first", first)
}
if secondStarted && !secondJoined {
join("competing", second)
}
}()
go func() {
if batch {
lsns, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)})
var lsn uint64
if len(lsns) > 0 {
lsn = uint64(lsns[0])
}
first <- result{lsn, err}
} else {
lsn, err := s.Write(0, blk(1))
first <- result{uint64(lsn), err}
}
}()
select {
case <-reserved:
case got := <-first:
firstJoined = true
t.Errorf("first append returned before reservation hook: %+v", got)
return
case <-time.After(2 * time.Second):
t.Error("first append did not enter reservation hook within 2s")
return
}
competingStarted := make(chan struct{})
secondStarted = true
go func() { close(competingStarted); lsn, err := s.Write(8, blk(8)); second <- result{uint64(lsn), err} }()
select {
case <-competingStarted:
case <-time.After(2 * time.Second):
t.Error("competing append did not start within 2s")
return
}
// A real mutex wait is not a durably blocked synctest operation. Keep the
// competing append scheduled against the paused reservation for a bounded
// real interval; the detached-reservation mutant signals admitted instead.
overtook := false
select {
case <-competingAdmitted:
overtook = true
case <-time.After(100 * time.Millisecond):
}
unblock()
a, b := join("first", first), join("competing", second)
firstJoined, secondJoined = true, true
if overtook || a.err != nil || b.err != nil || a.lsn >= b.lsn {
t.Fatalf("reservation continuity: overtook=%v first=%+v competitor=%+v", overtook, a, b)
}
})
}
}
@@ -0,0 +1,168 @@
package storage
import (
"context"
"time"
)
// A successful admission keeps its ticket until Release, after its append
// capacity decision. Granting the next ticket earlier permits it to consume
// the oldest writer's capacity even if semaphore grants were in FIFO order.
type walAdmissionTicket struct {
ready chan struct{}
prev, next *walAdmissionTicket
arrival time.Time
order uint64
}
func (a *walAdmission) newCommandOrder() uint64 { return a.nextOrder.Add(1) }
// Pending batches retain their command arrival order. An append that already
// owns capacity remains pinned at the head until its store call returns.
func (a *walAdmission) enqueueTicket(arrival *walWriteArrival) *walAdmissionTicket {
a.queueMu.Lock()
defer a.queueMu.Unlock()
t := &walAdmissionTicket{arrival: time.Now(), ready: make(chan struct{}, 1)}
if arrival != nil {
t.arrival, t.order = arrival.arrival, arrival.order
} else {
t.order = a.newCommandOrder()
}
priorFirst := a.first
before := a.last
for before != nil && before != a.active && (t.arrival.Before(before.arrival) || (t.arrival.Equal(before.arrival) && t.order < before.order)) {
before = before.prev
}
t.prev = before
if before == nil {
t.next = a.first
a.first = t
} else {
t.next = before.next
before.next = t
}
if t.next != nil {
t.next.prev = t
} else {
a.last = t
}
if a.first != priorFirst {
a.notifyHeadLocked()
}
return t
}
func (a *walAdmission) notifyHeadLocked() {
a.headVersion++
if a.first != nil {
// Only the new head needs to wake. A buffered notification also covers
// a previously displaced head without waking every queued command.
select {
case a.first.ready <- struct{}{}:
default:
}
}
}
func (a *walAdmission) headState(t *walAdmissionTicket) (bool, <-chan struct{}, uint64) {
a.queueMu.Lock()
defer a.queueMu.Unlock()
return a.first == t, t.ready, a.headVersion
}
func (a *walAdmission) tryGrantTicket(t *walAdmissionTicket, version uint64) bool {
a.queueMu.Lock()
defer a.queueMu.Unlock()
if a.first != t || a.active != nil || a.headVersion != version {
return false
}
select {
case a.sem <- struct{}{}:
a.active = t
return true
default:
return false
}
}
func (a *walAdmission) removeTicket(t *walAdmissionTicket) {
a.queueMu.Lock()
a.unlinkTicketLocked(t)
a.queueMu.Unlock()
}
func (a *walAdmission) unlinkTicketLocked(t *walAdmissionTicket) {
if t.prev != nil {
t.prev.next = t.next
} else {
a.first = t.next
a.notifyHeadLocked()
}
if t.next != nil {
t.next.prev = t.prev
} else {
a.last = t.prev
}
}
func (a *walAdmission) waitForTicket(ctx context.Context, deadline *time.Timer, t *walAdmissionTicket, contextual bool) error {
tick := time.NewTicker(5 * time.Millisecond)
defer tick.Stop()
hold := admissionHold(ctx, a)
for {
if hold != nil {
if a.hardBlocked.Load() {
hold.start()
} else {
hold.endWait()
}
if err := hold.check(); err != nil {
return err
}
}
first, changed, _ := a.headState(t)
if first {
if err := ctx.Err(); err != nil {
return a.commandWaitError(ctx, admissionContextError(err))
}
return nil
}
select {
case <-changed:
continue
case <-ctx.Done():
if fault := a.terminalFault(); fault != nil {
return fault
}
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
case <-tick.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
if !contextual && a.closedFn() {
return errVolumeClosed
}
}
}
}
func (a *walAdmission) commandWaitError(ctx context.Context, fallback error) error {
if fault := a.terminalFault(); fault != nil {
return fault
}
if ctx.Err() == context.Canceled {
return context.Canceled
}
if h := admissionHold(ctx, a); h != nil {
if err := h.check(); err != nil {
return err
}
}
return fallback
}
@@ -0,0 +1,376 @@
package storage
import (
"bytes"
"context"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestWALAdmissionFIFOOwnsCapacityThroughAppend(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
a := newWALAdmission(walAdmissionConfig{MaxConcurrent: 4, SoftWatermark: .7, HardWatermark: .9, WALUsedFn: func() float64 { return 0 }, NotifyFn: func() {}, ClosedFn: func() bool { return false }})
if err := a.Acquire(time.Minute); err != nil {
t.Fatal(err)
}
// A has passed admission but is paused before consuming capacity. Younger
// writes must not append merely because A's semaphore token was granted.
appended := make(chan string, 2)
launch := func(name string, ctx context.Context) {
go func() {
if err := a.acquireContext(ctx, time.Minute, nil); err != nil {
appended <- "error:" + name
return
}
appended <- name // the protected append-capacity consumption
a.Release()
}()
}
launch("B", context.Background())
synctest.Wait()
launch("C", context.Background())
synctest.Wait()
select {
case name := <-appended:
t.Fatalf("younger append overtook A: %s", name)
default:
}
a.Release() // A consumed capacity before handing over its ticket.
synctest.Wait()
for _, want := range []string{"B", "C"} {
select {
case got := <-appended:
if got != want {
t.Fatalf("append order got%s want%s", got, want)
}
default:
t.Fatalf("missing append %s", want)
}
}
})
}
func TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
a := newWALAdmission(walAdmissionConfig{MaxConcurrent: 4, SoftWatermark: .7, HardWatermark: .9, WALUsedFn: func() float64 { return 0 }, NotifyFn: func() {}, ClosedFn: func() bool { return false }})
if err := a.Acquire(time.Minute); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
err := a.acquireContext(ctx, time.Minute, nil)
if err == nil {
a.Release()
}
done <- err
}()
synctest.Wait()
cancel()
synctest.Wait()
if err := <-done; err != context.Canceled {
t.Fatalf("cancelled waiter: %v", err)
}
a.Release()
if err := a.Acquire(time.Minute); err != nil {
t.Fatalf("cancelled ticket blocked next: %v", err)
}
a.Release()
})
}
func TestWALStoreAdmissionFIFOOrdersRealAppends(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
entered, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
var calls atomic.Int32
s.testAfterAdmit = func() {
if calls.Add(1) == 1 {
close(entered)
<-resume
}
}
before := s.NextLSN()
type answer struct {
lsn uint64
err error
}
done := make([]chan answer, 3)
start := func(i int) {
done[i] = make(chan answer, 1)
go func() { n, err := s.Write(uint32(i), blk(byte(i+1))); done[i] <- answer{n, err} }()
}
// Force the queued path with a prior admitted append. Healthy calls are
// now allowed the no-ticket path and need not enter this queue.
if err := s.admission.Acquire(time.Minute); err != nil {
t.Fatal(err)
}
start(0)
synctest.Wait()
s.admission.Release()
<-entered
start(1)
synctest.Wait()
start(2)
synctest.Wait()
if got := s.NextLSN(); got != before {
t.Fatalf("younger write appended ahead of paused oldest: nextLSN%d want%d", got, before)
}
release()
synctest.Wait()
for i := 0; i < 3; i++ {
got := <-done[i]
if got.err != nil || got.lsn != before+uint64(i) {
t.Fatalf("write%d got LSN%d err%v; want%d", i, got.lsn, got.err, before+uint64(i))
}
if b, err := s.Read(uint32(i)); err != nil || !bytes.Equal(b, blk(byte(i+1))) {
t.Fatalf("readback%d: %v", i, err)
}
}
})
}
// An older command returns for its second batch while a younger command is
// already waiting on hard WAL pressure. Reclaim must serve the older batch first.
func TestWALHoldOlderBatchReentersBeforeYoungerPressureWaiter(t *testing.T) {
for _, legacy := range []bool{false, true} {
t.Run(map[bool]string{false: "hold", true: "legacy"}[legacy], func(t *testing.T) {
s := admissionPressureV3(t, 14)
synctest.Test(t, func(t *testing.T) {
older, cancelOld := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
if legacy {
older = WithWALWriteArrival(context.Background(), s, time.Now())
}
defer cancelOld()
defer FinishWALWriteHold(older, nil)
first, err := s.WriteContext(older, 16, blk(16))
if err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond)
younger, cancelYoung := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
if legacy {
younger = WithWALWriteArrival(context.Background(), s, time.Now())
}
defer cancelYoung()
defer FinishWALWriteHold(younger, nil)
type result struct {
lsn uint64
err error
}
youngDone, oldDone := make(chan result, 1), make(chan result, 1)
go func() { l, e := s.WriteContext(younger, 18, blk(18)); youngDone <- result{l, e} }()
synctest.Wait()
go func() { l, e := s.WriteContext(older, 17, blk(17)); oldDone <- result{l, e} }()
synctest.Wait()
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
synctest.Wait()
old, young := <-oldDone, <-youngDone
if old.err != nil || young.err != nil || old.lsn != first+1 || young.lsn != first+2 {
t.Fatalf("older multi-batch command was passed: first=%d older=%+v younger=%+v", first, old, young)
}
for _, i := range []uint32{16, 17, 18} {
got, e := s.Read(i)
if e != nil || !bytes.Equal(got, blk(byte(i))) {
t.Fatalf("readback %d: %v", i, e)
}
}
})
})
}
}
func TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure(t *testing.T) {
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 512, 4096, 1<<20, WModeStrict, 16)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.DisableAutoFlushForRecoveryTest()
// Fill actual space, not just the hard watermark: after the first
// batch fewer than one small record fits, so the younger call must wait.
for i := 0; i < 235; i++ {
if _, err := s.Write(uint32(i), blk(byte(i))); err != nil {
t.Fatal(err)
}
}
synctest.Test(t, func(t *testing.T) {
older, cancelOld := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancelOld()
defer FinishWALWriteHold(older, nil)
blocks := make([][]byte, 16)
for i := range blocks {
blocks[i] = blk(byte(i + 1))
}
first, err := s.WriteBatchContext(older, 256, blocks)
if err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond)
younger, cancelYoung := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancelYoung()
defer FinishWALWriteHold(younger, nil)
type answer struct {
lsn uint64
err error
}
youngDone, oldDone := make(chan answer, 1), make(chan answer, 1)
go func() { l, e := s.WriteContext(younger, 300, blk(99)); youngDone <- answer{l, e} }()
synctest.Wait()
go func() {
ls, e := s.WriteBatchContext(older, 272, blocks)
var last uint64
if len(ls) > 0 {
last = ls[len(ls)-1]
}
oldDone <- answer{last, e}
}()
synctest.Wait()
if s.NextLSN() != first[len(first)-1]+1 {
t.Fatal("pressure wait did not retain both commands")
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
synctest.Wait()
old, young := <-oldDone, <-youngDone
if old.err != nil || young.err != nil || old.lsn != first[len(first)-1]+16 || young.lsn != old.lsn+1 {
t.Fatalf("large write overtaken: first=%v old=%+v young=%+v", first, old, young)
}
for i := 0; i < 32; i++ {
got, e := s.Read(uint32(256 + i))
if e != nil || !bytes.Equal(got, blocks[i%16]) {
t.Fatalf("large readback %d: %v", i, e)
}
}
})
}
func TestWALAdmissionResamplesAfterOlderBatchChangesHead(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
older, co := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer co()
time.Sleep(time.Millisecond)
younger, cy := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cy()
sampled, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
var samples atomic.Int32
done := make(chan error, 1)
go func() {
err := s.admission.acquireContext(younger, time.Minute, func() (float64, error) {
if samples.Add(1) == 1 {
close(sampled)
<-resume
}
return 0, nil
})
if err == nil {
s.admission.Release()
}
done <- err
}()
<-sampled
if err := s.admission.acquireContext(older, time.Minute, func() (float64, error) { return 0, nil }); err != nil {
t.Fatal(err)
}
s.admission.Release()
release()
synctest.Wait()
if err := <-done; err != nil {
t.Fatal(err)
}
if samples.Load() < 2 {
t.Fatal("capacity granted from a sample predating an intervening append")
}
})
}
func TestWALAdmissionActiveAppendPinsReorderedCancellation(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
older := WithWALWriteArrival(context.Background(), s, time.Now())
older, cancelOld := context.WithCancel(older)
defer cancelOld()
time.Sleep(time.Millisecond)
active := WithWALWriteArrival(context.Background(), s, time.Now())
if err := s.admission.acquireContext(active, time.Minute, nil); err != nil {
t.Fatal(err)
}
released := false
younger, cancelYoung := context.WithCancel(context.Background())
defer cancelYoung()
oldDone, youngDone := make(chan error, 1), make(chan error, 1)
defer func() {
cancelOld()
cancelYoung()
if !released {
s.admission.Release()
}
synctest.Wait()
}()
go func() {
err := s.admission.acquireContext(younger, time.Minute, nil)
if err == nil {
s.admission.Release()
}
youngDone <- err
}()
synctest.Wait()
go func() {
err := s.admission.acquireContext(older, time.Minute, nil)
if err == nil {
s.admission.Release()
}
oldDone <- err
}()
synctest.Wait()
// An older re-entry may reorder pending tickets, never the append that has
// already been admitted. Cancelling that re-entry must retain the live head.
a := s.admission
a.queueMu.Lock()
pinned := a.first == a.active && a.first != nil && a.first.next != nil && a.first.next.order == admissionArrival(older, a).order
a.queueMu.Unlock()
if !pinned {
t.Fatal("older re-entry displaced the active append")
}
cancelOld()
synctest.Wait()
if err := <-oldDone; err != context.Canceled {
t.Fatalf("cancelled re-entry: %v", err)
}
select {
case err := <-youngDone:
t.Fatalf("younger append passed active head: %v", err)
default:
}
a.queueMu.Lock()
pinned = a.first == a.active && a.first.next == a.last
a.queueMu.Unlock()
if !pinned {
t.Fatal("reordered cancellation damaged the active head")
}
a.Release()
released = true
synctest.Wait()
if err := <-youngDone; err != nil {
t.Fatal(err)
}
if err := a.Acquire(time.Second); err != nil {
t.Fatalf("queue not drained: %v", err)
}
a.Release()
})
}
@@ -0,0 +1,179 @@
package storage
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
// Exercise the real v3 append path twice with one command, rather than the
// legacy wrapper: time outside admission and prior batches consume its cap.
func TestWALHoldRealWALAgedBatchKeepsCapAndEarlierDeadline(t *testing.T) {
for _, earlier := range []bool{false, true} {
t.Run(map[bool]string{false: "arrival_cap", true: "earlier_caller"}[earlier], func(t *testing.T) {
s := admissionPressureV3(t, 14)
synctest.Test(t, func(t *testing.T) {
arrival := time.Now()
parent, stopParent := context.WithCancel(context.Background())
if earlier {
stopParent()
parent, stopParent = context.WithDeadline(context.Background(), arrival.Add(23*time.Second))
}
defer stopParent()
ctx, cancel := WithWALWriteHold(parent, s, arrival, 25*time.Second, false)
defer cancel()
first, err := s.WriteContext(ctx, 16, blk(16))
if err != nil {
t.Fatal(err)
}
time.Sleep(21 * time.Second)
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
// This producer ends independently of the write, even if a cap regresses.
for i := 0; i < 8; i++ {
select {
case <-stop:
return
case <-time.After(time.Second):
s.flusher.instr.extentWriteBytes.Add(4096)
}
}
}()
// Independently bounded cleanup also catches a broken admission deadline.
watchdogDone := make(chan struct{})
go func() {
defer close(watchdogDone)
select {
case <-stop:
return
case <-time.After(10 * time.Second):
cancel()
}
}()
defer func() { close(stop); cancel(); <-joined; <-watchdogDone }()
_, err = s.WriteContext(ctx, 17, blk(17))
FinishWALWriteHold(ctx, err)
want := 25 * time.Second
if earlier {
want = 23 * time.Second
if !errors.Is(err, ErrWALPressureTimeout) || errors.Is(err, ErrWALHoldCap) {
t.Fatalf("earlier caller outcome: %v", err)
}
} else if !errors.Is(err, ErrWALHoldCap) {
t.Fatalf("cap outcome: %v", err)
}
if elapsed := time.Since(arrival); elapsed < want || elapsed > want+20*time.Millisecond {
t.Fatalf("second batch returned at %s want %s", elapsed, want)
}
if s.NextLSN() != first+1 {
t.Fatal("expired suffix appended")
}
})
})
}
}
// A nonzero counter is historical evidence, not continuing progress. Once it
// stops changing, the actual held append must get only one renewed window.
func TestWALHoldSamplerFixedNonzeroProgressExpires(t *testing.T) {
for _, kind := range []string{"reclaim", "extent"} {
t.Run(kind, func(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
start := time.Now()
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
synctest.Wait()
time.Sleep(4 * time.Second)
if kind == "reclaim" {
s.flusher.instr.reclaimedBytes.Add(4096)
} else {
s.flusher.instr.extentWriteBytes.Add(4096)
}
// This watchdog is independent of the counter and of the hold outcome.
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
select {
case <-stop:
case <-time.After(8 * time.Second):
cancel()
}
}()
defer func() { close(stop); cancel(); <-joined }()
time.Sleep(2 * time.Second)
select {
case err := <-done:
t.Fatalf("progress did not renew once: %v", err)
default:
}
err := <-done
if elapsed := time.Since(start); !errors.Is(err, ErrWALReclaimStalled) || elapsed < 9*time.Second || elapsed > 9*time.Second+20*time.Millisecond {
t.Fatalf("fixed %s sample: elapsed=%s error=%v; want stall after 5s silence", kind, elapsed, err)
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("hold waiter leaked")
}
})
})
}
}
// Drive the actual atomic sampler used by a pressure-held store append.
func TestWALHoldSamplerRenewsOnlySuccessfulByteProgress(t *testing.T) {
for _, kind := range []string{"reclaim", "extent", "unchanged", "phase", "empty_cycle", "failed_write"} {
t.Run(kind, func(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
synctest.Wait()
time.Sleep(4 * time.Second)
switch kind {
case "reclaim":
s.flusher.instr.reclaimedBytes.Add(4096)
case "extent":
s.flusher.instr.extentWriteBytes.Add(4096)
case "phase":
s.flusher.instr.phase.Store(int32(flusherWriting))
case "empty_cycle":
s.flusher.instr.cyclesStarted.Add(1)
s.flusher.instr.cyclesSucceeded.Add(1)
case "failed_write":
s.flusher.instr.cyclesFailed.Add(1)
s.flusher.instr.checkpointFailures.Add(1)
}
time.Sleep(2 * time.Second)
positive := kind == "reclaim" || kind == "extent"
select {
case err := <-done:
if positive || !errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("at 6s kind=%s outcome=%v", kind, err)
}
default:
if !positive {
cancel()
synctest.Wait()
<-done
t.Fatalf("%s renewed the stalled window", kind)
}
cancel()
synctest.Wait()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("joined hold=%v", err)
}
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("hold waiter leaked")
}
})
})
}
}
@@ -0,0 +1,58 @@
package storage
import "sync/atomic"
// WALHoldStatus is diagnostic back-pressure health, not authority or admission.
// Counters are cumulative for this open; changing them grants no capacity.
type WALHoldStatus struct {
OpenSequence uint64 // process-local store-open observation scope; compare with the status process identity
ReclaimedBytes uint64
ExtentBytes uint64
Degraded bool
Reason string
ActiveWaiters int64
Commands uint64
StallAnswers uint64
CapAnswers uint64
WaitNanos uint64
LastWaitNanos int64
LastReason string
FlusherPhase string
}
type walHoldEvent struct {
Reason string
WaitNanos int64
}
var nextWALHoldScope atomic.Uint64
type walHoldInstrumentation struct {
scope atomic.Uint64
active atomic.Int64
commands, stalls, caps, waitNanos atomic.Uint64
degraded atomic.Pointer[ReclaimProgress]
last atomic.Pointer[walHoldEvent]
}
func (s *WALStore) WALHoldStatus() WALHoldStatus {
scope := s.walHold.scope.Load()
if scope == 0 {
s.walHold.scope.CompareAndSwap(0, nextWALHoldScope.Add(1))
scope = s.walHold.scope.Load()
}
p := s.ReclaimProgress()
d := s.walHold.degraded.Load()
if d != nil && (p.ReclaimedBytes > d.ReclaimedBytes || p.ExtentBytes > d.ExtentBytes) {
s.walHold.degraded.CompareAndSwap(d, nil)
d = s.walHold.degraded.Load()
}
st := WALHoldStatus{OpenSequence: scope, ReclaimedBytes: p.ReclaimedBytes, ExtentBytes: p.ExtentBytes, Degraded: d != nil, ActiveWaiters: s.walHold.active.Load(), Commands: s.walHold.commands.Load(), StallAnswers: s.walHold.stalls.Load(), CapAnswers: s.walHold.caps.Load(), WaitNanos: s.walHold.waitNanos.Load(), FlusherPhase: p.Phase}
if st.Degraded {
st.Reason = string(walReclaimStalled)
}
if e := s.walHold.last.Load(); e != nil {
st.LastReason = e.Reason
st.LastWaitNanos = e.WaitNanos
}
return st
}
@@ -0,0 +1,59 @@
package storage
import "time"
const walReclaimWindow = 5 * time.Second
type walHoldReason string
const (
walReclaimStalled walHoldReason = "wal_reclaim_stalled"
walHoldCap walHoldReason = "wal_hold_cap"
)
// walHoldWindow belongs to one command. Global reclaim observations may renew
// its inactivity deadline, but can never shorten its initial window or move
// its absolute command cap. The admission waiter owns it; it needs no lock.
type walHoldWindow struct {
capAt time.Time
progressAt time.Time
stallAfter time.Duration
}
func newWALHoldWindow(arrival, holdStarted time.Time, maxHold time.Duration) walHoldWindow {
return walHoldWindow{capAt: arrival.Add(maxHold), progressAt: holdStarted, stallAfter: walReclaimWindow}
}
// newWALNoRetryHoldWindow is for protocols whose error completion is final.
// A zero device cap means no device timeout; it does not inherit a network
// frontend's cap. Diagnostic degradation still starts at five seconds.
func newWALNoRetryHoldWindow(arrival, holdStarted time.Time, deviceCap time.Duration) walHoldWindow {
w := walHoldWindow{progressAt: holdStarted, stallAfter: 30 * time.Second}
if deviceCap > 0 {
w.capAt = arrival.Add(deviceCap)
}
return w
}
func (w *walHoldWindow) degraded(now time.Time) bool {
return !now.Before(w.progressAt.Add(walReclaimWindow))
}
// observeProgress is called only when a same-scope checkpoint advanced or
// the current flusher cycle successfully wrote new extent bytes. An unchanged
// sample, failed write, phase heartbeat or empty cycle must not call it.
func (w *walHoldWindow) observeProgress(at time.Time) {
if at.After(w.progressAt) {
w.progressAt = at
}
}
func (w *walHoldWindow) expired(now time.Time) walHoldReason {
if !w.capAt.IsZero() && !now.Before(w.capAt) {
return walHoldCap
}
if !now.Before(w.progressAt.Add(w.stallAfter)) {
return walReclaimStalled
}
return ""
}
@@ -0,0 +1,108 @@
package storage
import (
"testing"
"time"
)
func TestWALHoldWindowRetryGetsOwnStallWindow(t *testing.T) {
now := time.Now()
oldProgress := now.Add(-20 * time.Second)
w := newWALHoldWindow(now, now, 25*time.Second)
w.observeProgress(oldProgress)
if got := w.expired(now); got != "" {
t.Fatalf("retry immediately stalled from global sample: %s", got)
}
if got := w.expired(now.Add(5*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("premature stall: %s", got)
}
if got := w.expired(now.Add(5 * time.Second)); got != walReclaimStalled {
t.Fatalf("stall boundary: %s", got)
}
// A later command cannot inherit an earlier command's elapsed window.
later := newWALHoldWindow(now.Add(3*time.Second), now.Add(3*time.Second), 25*time.Second)
later.observeProgress(now)
if got := later.expired(now.Add(5 * time.Second)); got != "" {
t.Fatalf("shared window stalled newer command: %s", got)
}
}
func TestWALHoldWindowProgressDoesNotRenewCap(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now, 25*time.Second)
for sec := 4; sec <= 24; sec += 4 {
at := now.Add(time.Duration(sec) * time.Second)
if got := w.expired(at); got != "" {
t.Fatalf("live reclaim stalled at %ds: %s", sec, got)
}
w.observeProgress(at)
}
if got := w.expired(now.Add(25*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("early cap: %s", got)
}
if got := w.expired(now.Add(25 * time.Second)); got != walHoldCap {
t.Fatalf("progress extended cap: %s", got)
}
}
func TestWALHoldWindowStartsCapAtCommandArrival(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now.Add(23*time.Second), 25*time.Second)
if got := w.expired(now.Add(25 * time.Second)); got != walHoldCap {
t.Fatalf("queue time escaped cap: %s", got)
}
}
func TestWALHoldWindowOlderObservationCannotMoveWindowBack(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now, 25*time.Second)
w.observeProgress(now.Add(4 * time.Second))
w.observeProgress(now.Add(time.Second))
if got := w.expired(now.Add(8 * time.Second)); got != "" {
t.Fatalf("older observation shortened window: %s", got)
}
if got := w.expired(now.Add(9 * time.Second)); got != walReclaimStalled {
t.Fatalf("no-progress window: %s", got)
}
}
func TestWALHoldWindowNoRetrySeparatesDegradedFromError(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 0)
if w.degraded(now.Add(5*time.Second - time.Nanosecond)) {
t.Fatal("premature degraded")
}
if !w.degraded(now.Add(5 * time.Second)) {
t.Fatal("stall not visible at5s")
}
if got := w.expired(now.Add(30*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("final answer before30s: %s", got)
}
if got := w.expired(now.Add(30 * time.Second)); got != walReclaimStalled {
t.Fatalf("stall answer at30s: %s", got)
}
}
func TestWALHoldWindowNoDeviceTimeoutHasNoCapWhileProgressMoves(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 0)
for sec := 4; sec <= 120; sec += 4 {
at := now.Add(time.Duration(sec) * time.Second)
if got := w.expired(at); got != "" {
t.Fatalf("progressing uncapped hold expired at%ds: %s", sec, got)
}
w.observeProgress(at)
if w.degraded(at) {
t.Fatal("successful progress left degraded window")
}
}
}
func TestWALHoldWindowDeviceCapStillBoundsProgress(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 10*time.Second)
w.observeProgress(now.Add(9 * time.Second))
if got := w.expired(now.Add(10 * time.Second)); got != walHoldCap {
t.Fatalf("device cap renewed: %s", got)
}
}
@@ -0,0 +1,219 @@
package storage
import (
"context"
"errors"
"fmt"
"log"
"time"
)
var (
ErrWALReclaimStalled = fmt.Errorf("storage: wal_reclaim_stalled: %w", ErrWALPressureTimeout)
ErrWALHoldCap = fmt.Errorf("storage: wal_hold_cap: %w", ErrWALPressureTimeout)
)
type walWriteArrivalKey struct{}
type walWriteArrival struct {
store *WALStore
arrival time.Time
order uint64
}
func newWALWriteArrival(s *WALStore, arrival time.Time) walWriteArrival {
if arrival.IsZero() {
arrival = time.Now()
}
var order uint64
if s.admission != nil {
order = s.admission.newCommandOrder()
}
return walWriteArrival{store: s, arrival: arrival, order: order}
}
func writeArrivalFor(ctx context.Context, s *WALStore) *walWriteArrival {
if v, _ := ctx.Value(walWriteArrivalKey{}).(*walWriteArrival); v != nil && v.store == s {
return v
}
if h := holdFor(ctx, s); h != nil {
return &h.walWriteArrival
}
return nil
}
// WithWALWriteArrival preserves command ordering across sequential store calls,
// independently of the transport's pressure timeout policy. It takes no ticket.
func WithWALWriteArrival(ctx context.Context, s *WALStore, arrival time.Time) context.Context {
if writeArrivalFor(ctx, s) != nil {
return ctx
}
v := newWALWriteArrival(s, arrival)
return context.WithValue(ctx, walWriteArrivalKey{}, &v)
}
func admissionArrival(ctx context.Context, a *walAdmission) *walWriteArrival {
if v, _ := ctx.Value(walWriteArrivalKey{}).(*walWriteArrival); v != nil && v.store.admission == a {
return v
}
if h := admissionHold(ctx, a); h != nil {
return &h.walWriteArrival
}
return nil
}
type walWriteHoldKey struct{}
// A command owns this state across its sequential store batches. Only the
// command's write goroutine observes progress or finishes the observations.
type walWriteHold struct {
walWriteArrival
waiting bool
waitStarted time.Time
waitNanos int64
reason walHoldReason
maxHold time.Duration
final bool
window walHoldWindow
progress ReclaimProgress
started bool
finished bool
}
// WithWALWriteHold preserves caller cancellation/deadlines and one command
// identity across adapter batches. The caller must FinishWALWriteHold after
// the byte command, including an error return. Each store append owns and
// releases its own ticket synchronously; cancellation cannot release it early.
func WithWALWriteHold(ctx context.Context, s *WALStore, arrival time.Time, maxHold time.Duration, final bool) (context.Context, context.CancelFunc) {
if h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold); h != nil {
return ctx, func() {}
}
var command walWriteArrival
if existing := writeArrivalFor(ctx, s); existing != nil {
command = *existing
} else {
command = newWALWriteArrival(s, arrival)
}
arrival = command.arrival
h := &walWriteHold{walWriteArrival: command, maxHold: maxHold, final: final}
h.window = newWALHoldWindow(arrival, time.Now(), maxHold)
if final {
h.window = newWALNoRetryHoldWindow(arrival, time.Now(), maxHold)
}
ctx = context.WithValue(ctx, walWriteHoldKey{}, h)
if maxHold > 0 {
return context.WithDeadline(ctx, arrival.Add(maxHold))
}
return context.WithCancel(ctx)
}
func holdFor(ctx context.Context, s *WALStore) *walWriteHold {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h != nil && h.store == s {
return h
}
return nil
}
func admissionHold(ctx context.Context, a *walAdmission) *walWriteHold {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h != nil && h.store.admission == a {
return h
}
return nil
}
// FinishWALWriteHold records a complete byte command's pressure observations.
// Each store call has already released its admission ticket before returning.
func FinishWALWriteHold(ctx context.Context, outcome error) {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h == nil || h.finished {
return
}
h.finished = true
if h.started || h.reason != "" {
reason := string(h.reason)
if reason == "" {
if outcome == nil {
reason = "completed"
} else if errors.Is(outcome, context.Canceled) {
reason = "cancelled"
} else {
reason = "write_failed"
}
}
if !h.started {
h.store.walHold.commands.Add(1)
}
h.store.walHold.waitNanos.Add(uint64(h.waitNanos))
h.store.walHold.last.Store(&walHoldEvent{Reason: reason, WaitNanos: h.waitNanos})
if h.reason == walHoldCap {
h.store.walHold.caps.Add(1)
}
if h.reason == walReclaimStalled {
h.store.walHold.stalls.Add(1)
}
detail := ""
if outcome != nil {
detail = outcome.Error()
}
p := h.store.ReclaimProgress()
log.Printf("storage: WAL write hold reason=%q held_ns=%d reclaimed_bytes=%d extent_bytes=%d phase=%s error=%q", reason, h.waitNanos, p.ReclaimedBytes, p.ExtentBytes, p.Phase, detail)
}
}
func (h *walWriteHold) start() {
if h.waiting {
return
}
h.waiting = true
h.waitStarted = time.Now()
h.window.progressAt = h.waitStarted
h.progress = h.store.ReclaimProgress()
h.store.walHold.active.Add(1)
if !h.started {
h.started = true
h.store.walHold.commands.Add(1)
}
}
func (h *walWriteHold) endWait() {
if !h.waiting {
return
}
h.waiting = false
h.store.walHold.active.Add(-1)
}
func (h *walWriteHold) check() error {
if fault := h.store.stickyIOFault(); fault != nil {
return fault
}
if h.finished {
return context.Canceled
}
now := time.Now()
if h.started {
p := h.store.ReclaimProgress()
if p.ReclaimedBytes < h.progress.ReclaimedBytes || p.ExtentBytes < h.progress.ExtentBytes {
return errors.New("storage: WAL reclaim observation scope changed")
}
if p.ReclaimedBytes > h.progress.ReclaimedBytes || p.ExtentBytes > h.progress.ExtentBytes {
h.window.observeProgress(now)
}
h.progress = p
}
if h.waiting && h.window.degraded(now) {
p := h.progress
h.store.walHold.degraded.CompareAndSwap(nil, &p)
}
switch reason := h.window.expired(now); reason {
case walHoldCap:
h.reason = walHoldCap
return ErrWALHoldCap
case walReclaimStalled:
if h.waiting {
h.reason = walReclaimStalled
return ErrWALReclaimStalled
}
}
return nil
}
@@ -0,0 +1,157 @@
package storage
import (
"bytes"
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
func TestWALWriteHoldMovingReclaimOutlastsOldAdmissionBudget(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
go func() {
for i := 0; i < 4; i++ {
time.Sleep(4 * time.Second)
s.flusher.instr.extentWriteBytes.Add(4096)
}
time.Sleep(4 * time.Second)
if err := s.flusher.flushOnce(); err != nil {
panic(err)
}
}()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if err != nil {
t.Fatal(err)
}
if got, err := s.Read(16); err != nil || !bytes.Equal(got, blk(16)) {
t.Fatalf("post-hold bytes: %v", err)
}
if time.Since(start) < 20*time.Second {
t.Fatalf("did not hold for reclaim: %s", time.Since(start))
}
})
}
func TestWALWriteHoldStallIsTypedAndFreshPerCommand(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
for i := 0; i < 2; i++ {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
cancel()
if !errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("try%d: %v", i, err)
}
if got := time.Since(start); got < 5*time.Second || got > 5*time.Second+20*time.Millisecond {
t.Fatalf("try%d window=%s", i, got)
}
}
})
}
func TestWALWriteHoldCapWhileProgressMoves(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
for i := 0; i < 30; i++ {
select {
case <-stop:
return
case <-time.After(time.Second):
s.flusher.instr.extentWriteBytes.Add(4096)
}
}
}()
before := s.NextLSN()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
close(stop)
<-joined
FinishWALWriteHold(ctx, err)
if !errors.Is(err, ErrWALHoldCap) {
t.Fatalf("cap was not typed: %v", err)
}
if got := time.Since(start); got != 25*time.Second {
t.Fatalf("cap at%s", got)
}
if s.NextLSN() != before {
t.Fatal("cap appended")
}
if st := s.WALHoldStatus(); st.CapAnswers != 1 || st.LastReason != "wal_hold_cap" {
t.Fatalf("cap status: %+v", st)
}
})
}
func TestWALWriteHoldDegradedBeforeFinalStallAndCancellationJoins(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 0, true)
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
time.Sleep(5*time.Second + 10*time.Millisecond)
st := s.WALHoldStatus()
if !st.Degraded || st.ActiveWaiters != 1 || st.StallAnswers != 0 {
t.Fatalf("not degraded before final answer: %+v", st)
}
select {
case err := <-done:
t.Fatalf("final error before30s: %v", err)
default:
}
s.flusher.instr.extentWriteBytes.Add(4096)
if s.WALHoldStatus().Degraded {
t.Fatal("successful extent progress did not clear diagnostic degradation")
}
cancel()
synctest.Wait()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled hold: %v", err)
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("cancelled hold left active waiter")
}
})
}
func TestWALWriteHoldLatchedFaultWinsAtStallBoundary(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
fault := errors.New("injected physical persistence fault")
go func() { time.Sleep(5*time.Second - time.Millisecond); s.latchV3(fault) }()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if !errors.Is(err, fault) || errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("stall masked physical fault: %v", err)
}
})
}
func TestWALWriteHoldFinalWithoutDeviceTimerWaitsThirtySeconds(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 0, true)
defer cancel()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if !errors.Is(err, ErrWALReclaimStalled) || time.Since(start) != 30*time.Second {
t.Fatalf("final window %s: %v", time.Since(start), err)
}
})
}
+29 -10
View File
@@ -47,6 +47,7 @@ import (
// - Online resize
// - Compaction (the WAL is bounded but periodic checkpoints free space)
type WALStore struct {
walHold walHoldInstrumentation
dataSyncStatus DataSyncStatus // selected before publication; never changes in this open
// recoveryWarnings and holesSuspected: the last Recover's typed
@@ -161,7 +162,8 @@ type WALStore struct {
// failed. Leaf lock: taken last, nothing is acquired under it.
fileSyncMu sync.Mutex
// testAfterAdmit, when set, runs in Write, WriteBatch and ApplyEntry
// after their entry checks and before the append lock. Tests only.
// after entry/capacity checks. Queued calls have not taken the append
// lock; no-ticket fast calls already own it. Tests only.
testAfterAdmit func()
// testBeforeFileSync, when set, runs in syncFile just before fileSyncMu
// is taken. Tests only.
@@ -530,8 +532,15 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u
if err := s.writeBudgetError(ctx, deadline); err != nil {
return 0, err
}
if s.admission != nil {
fastLocked, err := s.lockFastWALAppend(ctx, deadline, 1)
if err != nil {
return 0, err
}
if !fastLocked && s.admission != nil {
wait := s.admissionTimeout
if holdFor(ctx, s) != nil {
wait = 0
}
if !deadline.IsZero() {
wait = time.Until(deadline)
}
@@ -544,9 +553,11 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u
h()
}
commitLockStart := time.Now()
s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below
s.instr.recordWriteCommitLockWait(time.Since(commitLockStart))
if !fastLocked {
commitLockStart := time.Now()
s.mu.Lock() // blocking keeps RWMutex writer preference (#252)
s.instr.recordWriteCommitLockWait(time.Since(commitLockStart))
}
if s.closed {
s.mu.Unlock()
return 0, errors.New("storage: Write after Close")
@@ -565,7 +576,6 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u
appendStart := time.Now()
var walRelOff uint64
var err error
walRelOff, err = s.appendWriteV3(lba, data, lsn, func() error { return s.writeBudgetError(ctx, deadline) })
@@ -631,8 +641,15 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block
if err := s.writeBudgetError(ctx, deadline); err != nil {
return nil, err
}
if s.admission != nil {
fastLocked, err := s.lockFastWALAppend(ctx, deadline, len(blocks))
if err != nil {
return nil, err
}
if !fastLocked && s.admission != nil {
wait := s.admissionTimeout
if holdFor(ctx, s) != nil {
wait = 0
}
if !deadline.IsZero() {
wait = time.Until(deadline)
}
@@ -645,9 +662,11 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block
h()
}
commitLockStart := time.Now()
s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below
s.instr.recordWriteCommitLockWait(time.Since(commitLockStart))
if !fastLocked {
commitLockStart := time.Now()
s.mu.Lock() // blocking keeps RWMutex writer preference (#252)
s.instr.recordWriteCommitLockWait(time.Since(commitLockStart))
}
if s.closed {
s.mu.Unlock()
return nil, errors.New("storage: WriteBatch after Close")
@@ -6,6 +6,7 @@ import (
"math"
"math/rand"
"path/filepath"
"sort"
"testing"
"time"
)
@@ -181,11 +182,11 @@ func TestWALStoreV3DrainHeldIsTheFlusherPhase(t *testing.T) {
}
// A dense image written as single 4 KiB writes in random order, three
// WALs' worth, on a slow disk (every extent write takes 2 ms), with a 500 ms admission
// budget. A whole-map cycle (about 480 entries, about 1 s) frees nothing
// until it ends, so a write times out waiting for space; bounded cycles free
// space every sixteenth of the WAL, and no write times out while reclaim
// moves. The guest sees a slow disk, not errors.
// WALs' worth, on a slow disk (every extent write takes 5 ms), with an
// admission budget of half a whole-map cycle. A whole-map cycle (about 480
// entries) frees nothing until it ends, so a write times out waiting for
// space; bounded cycles free space every sixteenth of the WAL, and no write
// times out while reclaim moves. The guest sees a slow disk, not errors.
func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) {
const walSize = 2 << 20
const count = 3 * walSize / 4096
@@ -195,8 +196,17 @@ func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.admissionTimeout = 500 * time.Millisecond
s.flusher.beforeExtentWriteForTest = func() { time.Sleep(2 * time.Millisecond) }
// The slow disk is a 5 ms sleep per extent write. The admission budget is
// half a whole-map cycle (about 480 records), from the sleep as measured
// on this host: a whole-map cycle still outlasts it (the red), while a
// bounded cycle (a sixteenth of this WAL, about 32 records) leaves room
// for a slow fsync on a busy host (the budget is about 1.2 s, the bounded
// cycle's writes about 160 ms).
const delay = 5 * time.Millisecond
sleep := measuredSleep(delay)
s.admissionTimeout = 240 * sleep
t.Logf("measured sleep %v: admission budget %v", sleep, s.admissionTimeout)
s.flusher.beforeExtentWriteForTest = func() { time.Sleep(delay) }
lbas := rand.New(rand.NewSource(1)).Perm(count)
start := time.Now()
busy := 0
@@ -528,3 +538,15 @@ func TestWALStoreV3HeldDrainEndsInTheProductionDrain(t *testing.T) {
}
}
}
// measuredSleep is the median time a sleep of d actually takes on this host.
func measuredSleep(d time.Duration) time.Duration {
var got [9]time.Duration
for i := range got {
start := time.Now()
time.Sleep(d)
got[i] = time.Since(start)
}
sort.Slice(got[:], func(i, j int) bool { return got[i] < got[j] })
return got[len(got)/2]
}
@@ -423,6 +423,10 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) {
if _, err := s.Write(2, blk(2)); err != nil {
t.Fatal(err)
}
// This ACK-boundary schedule parks before the append lock. Disable
// admission so it does not reserve that lock via the no-ticket path;
// fast-path reservation and queued ordering have separate controls.
s.admission = nil
prev := s.v3.wack.Load()
parked, release := make(chan struct{}), make(chan struct{})
rel := sync.OnceFunc(func() { close(release) })
@@ -869,7 +873,7 @@ func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T)
// recovery drops its cut, must not acknowledge it; a fresh Sync after the
// recovery acknowledges normally.
func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) {
s, path := newStoreV3(t, WModeLagged)
s, _ := newStoreV3(t, WModeLagged)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
h := newHeldV3(t)
writeSynced(t, s, 1, 1)
@@ -880,7 +884,7 @@ func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) {
syn := h.start(func() error { _, err := s.Sync(); return err })
waitV3(t, h.parked, "the outer Sync before its completion")
s.v3.testSyncBeforeCompletion = nil
damageRecord(t, path, 2)
damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked
if _, err := s.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}
@@ -11,6 +11,12 @@ import (
func (s *WALStore) writeAdmissionDeadline(ctx context.Context) time.Time {
now := time.Now()
deadline, hasDeadline := ctx.Deadline()
if holdFor(ctx, s) != nil {
if hasDeadline {
return deadline
}
return time.Time{}
}
if s.v3 != nil {
local := now.Add(s.admissionTimeout)
if !hasDeadline || local.Before(deadline) {
@@ -32,6 +38,12 @@ func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) err
if ctx.Err() == context.Canceled {
return context.Canceled
}
if h := holdFor(ctx, s); h != nil {
if err := h.check(); err != nil {
return err
}
}
if !deadline.IsZero() && !time.Now().Before(deadline) {
return ErrWALPressureTimeout
}
+16
View File
@@ -382,3 +382,19 @@ These are tracked for fixes. Most were raised by an independent review of this r
- **No authentication** on the control plane, the replication channel or the filer client. Frontends bind to loopback by default. **Planned:** mTLS and role checks for destructive operations.
- **blockmaster is a single instance.** There is no master high availability. A master outage longer than the lease stops I/O on every workspace, and recovery is then a forced move; Kubernetes volumes cannot fail over while it is down.
- **Formats are exact-version.** The superblock, HEAD and segment formats are checked exactly and fail closed; the walstore superblock has no CRC. A format change needs a dual-reader release.
### WAL admission order
Each store Write/WriteBatch invocation keeps its oldest ticket through the append-capacity decision. Handing out multiple FIFO tokens before append would let a younger write consume the older write's space. Waiting and physical I/O run without the queue mutex. Command-wide multi-batch hold integration is separate from this store invocation queue.
```mermaid
stateDiagram-v2
[*] --> Queued
Queued --> Oldest: prior invocation releases
Queued --> Removed: cancellation or refusal
Oldest --> Append: capacity available
Oldest --> Removed: cancellation or refusal
Append --> Released: append decision returns
Released --> [*]
Removed --> [*]
```
@@ -1,9 +1,11 @@
# Immutable cleaning and intent list pages
This Draft integrates the immutable codec with the existing filer/blob store,
HEAD CAS and cleaning exclusion. It is dormant: no cut/restore/delete driver
calls the producer or consumer yet, and no automatic cleaner policy changes.
This is not the final format declaration or the complete V8 producer wiring.
This consumer slice wires persisted snapshot-delete intent continuation into
holder maintenance and adds repeated compatibility sweeps of unreachable list
pages after root/segment/chunk removal. It preserves conditional removal,
current-chain reachability and the existing cut/stop cancellation path.
Cut and upload-intent producers remain deferred. Offline volume-delete CLI,
durable volume-delete cursors and their scheduled resweep window are separate.
The ProducerSeam r1 encoding reserves four pending-chain slots in HEAD:
existing `list` plus `lists`, an optional array of at most three `ListCursor`
@@ -61,8 +63,20 @@ fields, kind confusion, identity/hash mismatch, counts, canonical ordering,
forbidden paths and size/entry limits. Unknown newer versions are refused.
The fallback cleaner stays a full mark/sweep until a separately reviewed
switch, made safe for reachable list/intent objects. Nothing in this codec
starts that switch or weakens existing reclamation protections.
switch. Its catalog pass now also enumerates `lists/` in bounded pages after
the root, segment and chunk phases, using the same holder/session and
conditional removal guards. It authenticates the whole HEAD-reachable chain
before removing any candidate page, preserving shared tails; a missing
continuation stops retirement. A restarted catalog can re-enumerate from the
beginning: completed deletions are absent and cannot be deleted again. The
in-memory cursor only schedules retries; it grants no reclamation authority.
Maintenance totals include list pages, with separate `plannedLists` and
`removedLists` counters so they never count as chunks.
This is the compatibility sweep, not the by-change switch. Complete V8
producer/consumer activation, restore-source and volume-delete progress
integration, and their crash/counting qualification remain required. No
proportional-to-changes claim is made for this full namespace scan.
## Publication, continuation and retirement
```mermaid
@@ -196,9 +210,39 @@ new authority branch require exact-head model/code review before activation.
No product delete driver calls this seam yet. The one-slot admission capacity,
remaining producer wiring and Linux/race qualification remain outstanding.
The catalog exposes `CleanSnapshotDeletePage` for an executor to resume exactly
one page from the current durable intent. It reconstructs the store and reader
from the full volume reference and delegates to the same guarded consumer;
it neither claims the volume nor looks up a receipt. `pending` is meaningful
only on success. No directory listing is used, and an unread tail is left for
the next call. A failed cursor CAS leaves that page pending; a lost reply is
settled from HEAD. The catalog restart controls count actual conditional
deletions and require each completed object to be deleted once. Live-root
reachability still has its existing manifest-read cost: absence of namespace
enumeration is not a claim that the whole path is proportional to changes.
Automatic maintenance and general drop/upload-intent producer wiring are not
enabled by exposing this catalog entry point.
The generic `StageListPage` rejects snapshot-delete intent before any HEAD or
object I/O, just as generic publication and consumption reject that kind. Its
ordinary EnsureObject adoption must never restore a snapshot-intent producer
tag after dedicated publication protected it. The held-generic-staging control
crosses snap end, cleaner planning and refreshed publication and proves this
door cannot recreate an earlier cleaner's removal authority.
### Candidate-shard decoding cost
The by-change intent path selects the candidate's shard in `Reader.EachRef`.
`layout.ShardSize` is the fixed 10000-entry limit; `DecodeSegment` rejects a
larger segment. The two-chunk counting control decodes that same shard twice,
so its bound is 20000 decoded references, rather than a full-volume scan.
With the fixture's five-byte owner and shard-zero indexes this is at most
1120054 encoded segment bytes (1119764 measured once saturated). It checks
one distinct shard as well as GET, entry and byte limits: two partial shards
are not admitted merely because their aggregate fits those limits.
At 1024, 16384, 262144 and 1048576 current entries, aggregate segment bytes
are 114452, 1119764, 1119764 and 1119764. Root bytes remain the separate
size-dependent term: 126, 225, 2700 and 10422. The by-change segment index
and two-level root are deferred; these measurements do not remove the
compatibility full sweep's namespace cost.
+36 -16
View File
@@ -476,15 +476,27 @@ snapshot lifetime; local persistence does not bypass it.
`AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync
mutant violates liveness. Prior authored LIGHT receipts are referenced in
`docs/spec/README.md`; this change does not claim a new TLC execution.
- A v3 write carries one four-second command deadline through dispatch,
adapter batches, store admission locks and occupancy snapshots. Admission
reserves append headroom and expiry before append refuses without mutation.
Already-started physical I/O, COW/observer callbacks and higher-layer waits
are not preempted. An unresolved pin or local stall returns
`ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns
Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original
non-retryable mapping. This is a local pressure outcome, not a whole-I/O
deadline; the broader budget gap is tracked separately in issue221.
- Store Write/WriteBatch uses no ticket when there is room and no waiter. The
append lock retains that space through the append; the queue lock atomically
checks no waiter exists, then releases before file I/O. Otherwise admission
queues pending invocations by command arrival.
A later batch of an older command precedes younger waiters, while an already
admitted append cannot be preempted. Equal arrivals use a stable command order. The oldest
ticket remains held through the append-capacity decision and is released by
the existing post-write Release. A cancelled or refused invocation removes
its ticket and wakes the next. No queue mutex is held while sampling pressure,
waiting, or appending. Each store call releases its ticket before returning
to the adapter; it never spans an RMW read or a replica acknowledgement.
- An NVMe WAL frontend command carries one arrival-based hold identity through
adapter batches. Each queued store call rejoins admission at its original command position and only
its head consumes append capacity. Queue-head changes invalidate a prior
pressure sample before a capacity grant. Command observations finish after
all its store calls return. Caller cancellation and an earlier deadline
stay effective. Successful reclaim/extent counter increases renew the
per-command inactivity window, never its absolute cap. Other backends keep
the four-second cooperative WriteCommandBudget. Already-started physical
I/O and short locks are not preempted; no detached worker appends after an
expiry answer. Permanent storage faults win over pressure/refusal timing.
- Every frontend I/O error completion uses one shared retry class
(`INV-FE-ERROR-RETRY-CLASS-001`, the shared backend-error classification rule): (a) a known permanent
cause anywhere in the wrapped/joined tree wins: EIO, ENOSPC, EROFS, counter
@@ -581,11 +593,11 @@ stateDiagram-v2
| no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` |
| pending ordinary create with a proved id8 collision | pending create with a fresh durable layout id | rejected exclusive VOLUME create, valid foreign full identity belongs to the selected name/id8 directory; not ready, not attached, not a restore; persist replacement before retry, settle unknown rename on replay; never modify the colliding volume | `LayoutStore.CreateVolumeRecord`; `FileStore.RedrawPendingLayoutID`; master `createLifecycleVolume` | `INV-CREATE-DIR-COLLISION-001` |
| any version-1 HEAD with reserved lists | same reserved lists after any existing HEAD transition | at most three additional checked cursors, no repeated Ref across list/lists; deep clone and exact preservation; never consumed or a reason to refuse serving | `head.go` `check`, `clone`, `runTransition`; `remove.go` `Cleaner.Page` retains list metadata | `INV-LIST-RESERVED-001` |
| snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every referenced page durable and authenticated; unknown reply retains session and pages | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` |
| snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every page durable; full slot returns queue_full without replacing work; unknown reply retains protection | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` |
| clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` |
| clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` |
| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001` |
| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent` | `INV-SNAPSHOT-DELETE-CONSUME-001` |
| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `BCatalog.CleanSnapshotDeletePage`; `LayoutRemote.Clean` | `INV-SNAPSHOT-DELETE-CONSUME-001` |
| idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` |
| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` |
| snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` |
@@ -752,8 +764,14 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing spans and truncation before allocating a payload; the scanner reads a record only after those checks bound its size, and refuses nonzero padding, a bad CRC or a bad footer before using its bytes. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | STUB |
| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | ACTIVE |
| `INV-WAL-V3-ADMISSION-001` | v3 write admission measures WAL pressure from the active v3 writer's physical head minus the both-slot reuse floor, as a fraction of WALSize. | M1 Serving (write admission) | `core/storage/walstore.go` `openInitializedV3`, `WALStore.walUsedFraction`; `core/storage/write_command_budget.go` `WALStore.writePressureSample` | `TestWALStoreV3AdmissionUsesNativeOccupancy` (`core/storage/walstore_admission_v3_test.go`); `TestWALStoreV3WritePressureSampleMatchesOccupancy` (`core/storage/write_command_budget_test.go`); liveness under pressure: `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback), `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) (`core/frontend/durable/provider_chunk_burst_test.go`) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE |
| `INV-WAL-V3-ADMISSION-FIFO-001` | Room with no waiter is reserved atomically without a ticket. Otherwise tickets keep command-arrival order across batches. Admitted appends cannot be preempted. Release precedes RMW/peer ACK waits; cancellation removes a waiter. | M1 Serving (write admission) | `core/storage/wal_admission.go` `acquireContext`, `Release`; `core/storage/wal_admission_fifo.go`; `core/storage/wal_admission_fast.go` `lockFastWALAppend` | `TestWALAdmissionFastReservationExcludesCompetingAppend`, `TestWALAdmissionFastPathHasNoTicket`, `TestWALAdmissionFastPathCannotPassAWaiter`, `TestWALAdmissionFastReservationKeepsAppendLock`, `TestWALAdmissionFIFOOwnsCapacityThroughAppend`, `TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext`, `TestWALStoreAdmissionFIFOOrdersRealAppends`, `TestWALHoldOlderBatchReentersBeforeYoungerPressureWaiter`, `TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure`, `TestWALAdmissionResamplesAfterOlderBatchChangesHead`, `TestWALAdmissionActiveAppendPinsReorderedCancellation`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | WALHold r2 rows 325-333; WALHold r3b two-batch ordering (`batch_to_tail`); WALHold r3c fast path (`fast_ignores_waiters`); model qualification complete, native/performance gates separate | ACTIVE |
| `INV-WAL-HOLD-WINDOW-001` | A command's WAL-pressure inactivity window starts no earlier than its own hold; a host retry gets a fresh window. Successful same-store reclaim or extent-byte increments renew it. | M1 Serving (write admission) | `core/storage/wal_write_hold.go` `start`, `check`; `wal_hold_window.go` | `TestWALWriteHoldStallIsTypedAndFreshPerCommand`, `TestWALWriteHoldMovingReclaimOutlastsOldAdmissionBudget`, `TestWALHoldWindowRetryGetsOwnStallWindow`, `TestWALHoldSamplerRenewsOnlySuccessfulByteProgress`, `TestWALHoldSamplerFixedNonzeroProgressExpires` | WALHold r2 rows 325-333, StallHoldsOwnWindow, ErrorOnlyOnStall | ACTIVE |
| `INV-WAL-HOLD-CAP-001` | Progress does not renew a command's arrival-based hold cap. Startup refuses a non-positive network cap or a cap leaving less than five seconds before the declared host timeout. | M1 Serving (write admission) | `core/storage/wal_hold_window.go`; `core/frontend/wal_hold_config.go` | `TestWALWriteHoldCapWhileProgressMoves`, `TestWALHoldRealWALAgedBatchKeepsCapAndEarlierDeadline`, `TestWALHoldConfigHostTimeoutMargin`, `TestParseFlagsWALHoldHostTimeout` | WALHold r2 rows 325-333, NoHostTimeout, RetryOnlyAtCap | ACTIVE |
| `INV-WAL-HOLD-DEGRADED-001` | Five seconds of WAL pressure without progress marks reclaim diagnostically degraded; it does not change authority or frontend readiness. | M1 Serving (diagnostics) | `core/storage/wal_write_hold.go` `check`; `wal_hold_status.go`; `core/host/volume/status_server.go` | `TestWALWriteHoldDegradedBeforeFinalStallAndCancellationJoins`, `TestWALHoldDegradedDoesNotChangeReadiness`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | WALHold r2 window; diagnostic projection only | ACTIVE |
| `INV-WAL-HOLD-OBSERVE-001` | The hold status and metrics routes read atomic progress without requiring general frontier locks and preserve the status listener's access policy. | M1 Serving (diagnostics) | `core/host/volume/wal_hold_metrics.go`; `DurableProvider.WALHoldStatuses` | `TestWALHoldMetricsAtomicSourceAndAccess`, `TestWALHoldAtomicStatusDoesNotReadFrontiers` | NONE (read-only observation) | ACTIVE |
| `INV-WAL-HOLD-TRANSPORT-SCOPE-001` | ublk, NBD and serial iSCSI explicitly retain the legacy write budget and cannot install a retryable WAL hold; ublk/NBD apply it to Write only, while FUA Sync and flush retain the caller context; final-error extended holds remain deferred. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithLegacyWriteBudget`; `core/frontend/durable/storage_adapter.go` `WriteCommandContext`; ublk, NBD and serial iSCSI write dispatch | `TestDeviceWriteKeepsLegacyBudget` (`core/frontend/ublk/device_write_budget_test.go`, `core/frontend/nbd/device_write_budget_test.go`); `TestDeviceLegacyBudgetDoesNotInstallARetryableWALHold` (`core/frontend/durable/device_write_scope_test.go`); `TestSerialISCSIWriteKeepsLegacyBudget` | WALHold r2 rows 325-333; final-error activation deferred | ACTIVE |
| `INV-WAL-V3-ADMISSION-FAULT-001` | A terminal I/O fault latched while a v3 write waits on WAL pressure or for an admission slot ends that wait with the fault's original typed cause, also when the deadline has expired at the same check. | M1 Serving (write admission) | `core/storage/wal_admission.go` `walAdmission.acquireContext`, `walAdmission.terminalFault`; `core/storage/write_command_budget.go` `WALStore.writeBudgetError` | `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreV3WriteBudgetKeepsTerminalFault` (`core/storage/write_command_budget_test.go`); also in `core/storage/wal_admission_fault_v3_test.go` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-DEADLINE-001` | One command deadline, the earlier of the caller's deadline and the command's arrival plus `WriteCommandBudget`, bounds every adapter batch of a write and its store waits for the capture and lifecycle locks, on the local clock. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-DEADLINE-001` | A command keeps any earlier caller deadline across adapter batches. Retryable WAL commands use their arrival-based cap; explicit legacy device transports and other backends keep WriteCommandBudget. An expired command starts no new append. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext`; `core/storage/wal_write_hold.go` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALHoldBudgetSurvivesNestedNVMeDispatch`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-SHORTLOCK-001` | A v3 write takes the store, descriptor and WAL writer locks blocking, never by polling, so RWMutex writer preference holds, and its command deadline is checked once they are held. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext`; `core/storage/write_command_budget.go` `WALStore.writePressureSample`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-NOPAYLOAD-001` | A v3 write whose command deadline has passed starts no new payload WAL write: the deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write. | M1 Serving (write admission) | `core/storage/walstore_v3.go` `WALStore.appendWriteV3`, `WALStore.writeBatchV3Locked`, `WALStore.v3BudgetAfterRollover`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-EXPIRY-STATE-001` | A v3 write refused for an expired deadline before its append leaves the WAL bytes, nextLSN and the dirty map unchanged. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendExpiredWriteDoesNotAppend` | — | ACTIVE |
@@ -1404,13 +1422,15 @@ Notes:
| ID | Statement | Transition | Enforced in | Guard | Model | Status |
|---|---|---|---|---|---|---|
| `INV-LIST-RESERVED-001` | Version-1 HEAD preserves at most three additional checked list cursors without consuming them or refusing serving; list-page retirement remains conservative while they are present and reports newer_pending_work. | M9 all existing HEAD updates | `core/frontend/chunkstore/layout/head.go` `check`, `clone`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.Page` | `TestMaintenanceStatusRealPassAndTimeout/newer-pending-work`, `TestReservedListsGoldenBytes`, `TestReservedListsValidationAndClone`, `TestReservedListsCloneDoesNotAlias`, `TestReservedListsDoNotBecomeCompatibilitySweepCandidates`, `TestMachineReadableHeadCensusCoversRealTransitionFieldSets`, `TestListWritesMatchExportedCensus` | ProducerSeam r1 E1-E3: Bounded, NoLeak, NoDangling (encoding only; producer deferred) | DORMANT |
| `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply never abandons their protection. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish` | PageChain 246-250; NoDangling | DORMANT |
| `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply retains protection; a full slot returns queue_full without replacing pending work. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish`, `TestGenericListQueueFullCannotOverwritePendingWork`, `TestDeleteIntentQueueFullKeepsBothWorkAndReferences` | PageChain 246-250; QueueCap 375-380 (az1 8/8); NoDangling | DORMANT |
| `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT |
| `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT |
| `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned`; `core/frontend/chunkstore/clean_b.go` `RemoveUnreachableAll` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire`, `TestBCatalogFullSweepKeepsTheEntireCurrentList`, `TestBCatalogListRetirementResumesAfterRestart` | PageChain 246,248-251; NoDangling | ACTIVE |
| `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT |
| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT |
| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `core/frontend/chunkstore/layout/delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Clean` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt`, `TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan`, `TestCatalogIntentCursorInterruptAndLostReply`, `TestHolderMaintenanceResumesThePersistedDeleteIntent`, `TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins` | PageChain r2 246,251-253 (az1 13/13); StaleClean 159-161 | ACTIVE |
| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata`, `TestGenericIntentStagingCannotUndoRefreshedPublication` | StaleClean 159-161; exact-head refinement read required | DORMANT |
The snapshot-delete consumer and list-page retirement above are reachable through holder maintenance and covered by Go assertions. Their ACTIVE status describes that reachability and test coverage, not fresh Linux, composed-operation or release qualification. Cut and upload-intent producers remain deferred; their dormant publication rows are not activated by this consumer slice.
The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here:
its holder/session guard and all existing controls remain unchanged. The new
dormant snapshot-intent branch instead requires the exact current HEAD intent,
@@ -1494,7 +1514,7 @@ The two STUB rows of the start path are measured by the 1 TiB row's kill-and-res
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | The write's store admission deadline, fixed once when the write enters the store: the earlier of the caller's deadline and entry + 4 s (`admissionTimeout`), less a reserve of min(1 s, a quarter of the time then left), so at most entry + 3 s, on the local clock. In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once the flusher's progress brings pressure below 0.90; a wait for one of the 64 admission slots ends when another write releases its slot. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` wait behind it for at most this bound. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. |
| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | NVMe WAL hold commands share their arrival-based cap (default 25 s) and a per-command five-second inactivity window, renewed only by reclaimed/extent bytes. Explicit legacy transports keep the earlier of caller deadline and store entry + 4 s, less a reserve of min(1 s, a quarter of the time left). In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once pressure falls below 0.90; FIFO admission then retains its ticket through that store append, releasing before adapter RMW/replica waits. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` join the command's bounded admission wait (default cap 25 s for NVMe holds; legacy admission at most about 3 s). Started I/O and short locks remain cooperative. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. |
The WAL-pressure admission wait is the one wait here held under store locks (the `captureMu` and `lifecycleMu` read locks). It is a local wait: pressure samples, a timer and the flusher's local progress. No remote call is made while those locks are held, so the rule that no remote call runs under a lock still holds.
+12
View File
@@ -691,3 +691,15 @@ Every command on the pages above, and the test that runs it.
| Scheduled snapshots (`--chunk-snapshot-schedule`) on a running volume with a real clock | not run in 1.0 as written: the schedule is tested with a fake clock (`core/frontend/durable/chunk_snapshot_schedule_test.go`) | not run |
| Periodic capture (`--chunk-capture-interval`) on a running volume | a lab run on the release candidate: automatic cuts while the guest wrote, every acknowledged write read back | lab |
| SeaweedFS vacuum (`/vol/vacuum`, `volume.vacuum`) | not run in 1.0: a SeaweedFS command; the tests check that the cleaning deletes the chunks, not that SeaweedFS compacts its files | not run |
## Host I/O timeout configuration
The holder cannot discover an initiator's I/O timeout. Set `blockvolume --host-io-timeout` (`host_io_timeout`) to match the hosts using the volume; the default is `30s`. If you raise or lower the hosts' `io_timeout`, change this setting to match. For hosts with different timeouts, use the shortest timeout.
For NVMe/TCP, the per-command WAL-pressure hold limit, `--wal-hold-timeout`, defaults to `25s`. Startup refuses a non-positive hold or a hold that leaves less than five seconds before `--host-io-timeout`: `hold + 5s <= host_io_timeout`. Thus the default `25s` hold and `30s` host timeout are valid. For a `15s` host timeout, set the hold to at most `10s`. The five-second margin allows for network and queueing delay; it does not configure the host.
For NVMe/TCP, a store append with enough space and no waiter proceeds without a queue ticket. Otherwise each store append waiting on WAL capacity keeps its FIFO position until that append returns; a new call cannot bypass a waiter even if reclaim has just made room. A command keeps its arrival cap across batches, and each batch rejoins admission by the original command arrival: an older command precedes younger waiters, while an append already admitted completes first. The ticket is released before read-modify-write reads and replica acknowledgement waits. Reclaimed WAL bytes or successful extent writes renew that command's five-second inactivity window; identical samples and flusher phase changes do not. At the hold cap or a five-second reclaim stall, NVMe returns retryable SC `0x82` (CRD2 when ACRE is negotiated). Permanent storage faults keep their original failure classification.
A five-second reclaim stall also sets diagnostic `Degraded` in status. Read `GET /status/wal-hold?volume=<name>` for atomic hold counters, reclaimed/extent bytes and flusher phase, or `GET /metrics?volume=<name>` for numeric metrics. These endpoints share the status listener's access rules and avoid frontier locks. A degraded reclaim diagnostic does not remove authority or turn frontend readiness off. Successful reclaim/extent progress clears that diagnostic. Hold events name `wal_hold_cap`, `wal_reclaim_stalled`, completion, cancellation or a write failure, with accumulated admission-wait nanoseconds.
The extended WAL-pressure hold policy is currently limited to NVMe/TCP. The serial iSCSI session keeps its existing short write/admission budget (four seconds for a command, about three seconds for WAL admission), returning BUSY under transient pressure; it does not hold its reader for the extended window. Long iSCSI holds require concurrent session command handling and initiator qualification. ublk and NBD retain an explicit four-second backend Write budget and can return a final EIO under pressure. That budget applies only to Write: FUA then performs Sync with the original caller context, exactly as a separate write plus flush; standalone flush keeps that context too. Their final-error 30-second stall policy and device-timeout-derived cap are deferred until actual device timeout configuration and native controls are wired; the network host timeout declaration does not configure those devices. Do not assume the extended slow-reclaim guarantee for ublk/NBD.
+42
View File
@@ -14,6 +14,8 @@ The volume's authority and health projection. Go type `volume.StatusProjection`.
| Field | Type | Meaning |
|---|---|---|
| `Degraded` | bool | WAL reclaim stalled for at least five seconds; diagnostic, not an authority or readiness change |
| `DegradedReason` | string | — (omitted when empty) |
| `VolumeID` | string | the volume this host serves |
| `ReplicaID` | string | this host's replica of it |
| `Epoch` | uint64 | the authority epoch of the current assignment |
@@ -78,6 +80,21 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `ReplicaID` | string | this host's replica |
| `VolumeCount` | int | number of entries in Volumes |
| `Volumes[]` | object | the durable store state of the served volume |
| `Volumes[].WALHold` | object | WAL-pressure hold health and cumulative metrics (omitted when empty) |
| `Volumes[].WALHold.OpenSequence` | uint64 | process-local store-open observation scope; compare with the status process identity |
| `Volumes[].WALHold.ReclaimedBytes` | uint64 | — |
| `Volumes[].WALHold.ExtentBytes` | uint64 | — |
| `Volumes[].WALHold.Degraded` | bool | — |
| `Volumes[].WALHold.Reason` | string | — |
| `Volumes[].WALHold.ActiveWaiters` | int64 | — |
| `Volumes[].WALHold.Commands` | uint64 | — |
| `Volumes[].WALHold.StallAnswers` | uint64 | — |
| `Volumes[].WALHold.CapAnswers` | uint64 | — |
| `Volumes[].WALHold.WaitNanos` | uint64 | — |
| `Volumes[].WALHold.LastWaitNanos` | int64 | — |
| `Volumes[].WALHold.LastReason` | string | — |
| `Volumes[].WALHold.FlusherPhase` | string | — |
| `Volumes[].Degraded` | bool | diagnostic WAL reclaim stall; does not alter authority or readiness |
| `Volumes[].UnknownOutcome{}` | uint64 | unknown HEAD-write answers by cause since catalog start; never implies persistence |
| `Volumes[].HeadWrites{}` | uint64 | acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded |
| `Volumes[].VolumeID` | string | the volume |
@@ -247,9 +264,11 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Maintenance.lastPass.plannedChunks` | int64 | chunk objects considered for removal |
| `Volumes[].Chunk.Maintenance.lastPass.plannedRoots` | int64 | root objects considered for removal |
| `Volumes[].Chunk.Maintenance.lastPass.plannedSegments` | int64 | segment objects considered for removal |
| `Volumes[].Chunk.Maintenance.lastPass.plannedLists` | int64 | immutable list pages considered for removal |
| `Volumes[].Chunk.Maintenance.lastPass.removedChunks` | int64 | chunk objects removed |
| `Volumes[].Chunk.Maintenance.lastPass.removedRoots` | int64 | root objects removed |
| `Volumes[].Chunk.Maintenance.lastPass.removedSegments` | int64 | segment objects removed |
| `Volumes[].Chunk.Maintenance.lastPass.removedLists` | int64 | immutable list pages removed |
| `Volumes[].Chunk.Maintenance.lastPass.error` | string | one-line callback error; empty when the callback completed |
| `Volumes[].Chunk.Maintenance.lastPass.headGenError` | string | diagnostic HEAD read error; empty when read |
| `Volumes[].Chunk.Maintenance.lastPass.headGen` | uint64 | observed cleaning HEAD generation; diagnostic only |
@@ -374,6 +393,29 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
### `GET /status/wal-hold`
Atomic WAL hold observations scoped to this process and store open. Go type `volume.walHoldStatusBody`.
| Field | Type | Meaning |
|---|---|---|
| `ProcessID` | string | holder process incarnation |
| `VolumeID` | string | the served volume |
| `WALHold` | object | atomic store-open observations |
| `WALHold.OpenSequence` | uint64 | process-local store-open observation scope; compare with the status process identity |
| `WALHold.ReclaimedBytes` | uint64 | — |
| `WALHold.ExtentBytes` | uint64 | — |
| `WALHold.Degraded` | bool | — |
| `WALHold.Reason` | string | — |
| `WALHold.ActiveWaiters` | int64 | — |
| `WALHold.Commands` | uint64 | — |
| `WALHold.StallAnswers` | uint64 | — |
| `WALHold.CapAnswers` | uint64 | — |
| `WALHold.WaitNanos` | uint64 | — |
| `WALHold.LastWaitNanos` | int64 | — |
| `WALHold.LastReason` | string | — |
| `WALHold.FlusherPhase` | string | — |
### `GET /status/recovery`
The engine's replica projection (only with recovery enabled). Go type `engine.ReplicaProjection`.