mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Let progressing maintenance passes finish beyond one minute (#969)
Interim merge note (spec trace workflow startup_failure since 22:45Z): go test (linux) and process-level tests (real binaries) passed on 53d87521; spec-trace-check.sh and public-text-check.sh run locally with the base branch's scripts against this head and body: both pass. Linux qualification at 2def4a14 (53d87521 is its conflict-only rebase): vet clean, -short of the six touched packages pass, targeted -race -count=2 finds no race. Code review ACCEPT carried to 53d87521; model review PASS.
This commit is contained in:
1 parent
124e505964
commit
91e6f4dfc4
49 files changed
+3632
-230
No files matched your search
+41
@@ -210,3 +210,44 @@ core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Stage
|
||||
core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Land
|
||||
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Stage
|
||||
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Land
|
||||
core/frontend/durable/maintenance_progress.go CutTime.Complete
|
||||
core/frontend/durable/maintenance_progress.go CutTime.Fail
|
||||
core/frontend/durable/maintenance_progress.go CutTime.Tick
|
||||
core/frontend/chunkstore/maintenance_request.go CutTime.CallTimeout
|
||||
core/frontend/chunkstore/layout/maintenance_progress.go CutTime.Complete
|
||||
core/frontend/chunkstore/layout/remove.go CutTime.Complete
|
||||
core/frontend/chunkstore/retain_b.go CutTime.Complete
|
||||
core/frontend/chunkstore/layout/read.go CutTime.Complete
|
||||
core/frontend/chunkstore/layout/list_chain.go CutTime.Complete
|
||||
core/frontend/chunkstore/clean_b.go CutTime.Complete
|
||||
core/frontend/chunkstore/layout/delete_intent.go CutTime.Complete
|
||||
core/frontend/chunkstore/layout_remote.go CutTime.Complete
|
||||
core/frontend/chunkstore/clean_b.go SnapshotRemoval.BeginClean
|
||||
core/frontend/chunkstore/clean_b.go SnapshotRemoval.EndClean
|
||||
core/frontend/chunkstore/clean_b.go StaleClean.HeadRead
|
||||
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.Validate
|
||||
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.EndClean
|
||||
core/frontend/chunkstore/clean_b.go CleanBatch.PrepOut
|
||||
core/frontend/chunkstore/clean_b.go CleanBatch.Close
|
||||
core/frontend/chunkstore/clean_b.go CleanBatch.Effects
|
||||
core/frontend/chunkstore/clean_admission.go CleanBatch.Request
|
||||
core/frontend/chunkstore/clean_admission.go CleanBatch.Begin
|
||||
core/frontend/chunkstore/catalog_snapshot_operation.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/layout_remote.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepOut
|
||||
core/frontend/chunkstore/layout/remove.go CleanBatch.Effects
|
||||
core/frontend/chunkstore/clean_b.go CleanBatch.BeginIn
|
||||
core/frontend/chunkstore/clean_b.go CleanBatch.PrepIn
|
||||
core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepIn
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/retain_b.go CleanBatch.Request
|
||||
core/frontend/chunkstore/retain_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Request
|
||||
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/layout_remote.go CleanBatch.Begin
|
||||
core/frontend/chunkstore/clean_admission.go CleanBatch.Close
|
||||
core/frontend/chunkstore/layout_store.go CleanBatch.Request
|
||||
core/frontend/chunkstore/layout_store.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/layout/head.go CleanBatch.Request
|
||||
core/frontend/chunkstore/layout/head.go CleanBatch.Publish
|
||||
|
@@ -0,0 +1,158 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
|
||||
)
|
||||
|
||||
type progressingPreparationFiler struct {
|
||||
chunkstore.Filer
|
||||
mu sync.Mutex
|
||||
enabled bool
|
||||
seen map[string]bool
|
||||
removeDelay time.Duration
|
||||
prepStart, prepEnd, removeStart, removeEnd time.Time
|
||||
}
|
||||
|
||||
func (f *progressingPreparationFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
f.mu.Lock()
|
||||
key := path.Join(dir, name)
|
||||
delay := f.enabled && strings.Contains(dir, "/pool/") && !f.seen[key]
|
||||
if delay {
|
||||
f.seen[key] = true
|
||||
if f.prepStart.IsZero() {
|
||||
f.prepStart = time.Now()
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if delay {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(15 * time.Second):
|
||||
}
|
||||
}
|
||||
entry, err := f.Filer.LookupEntry(ctx, dir, name)
|
||||
if delay && err == nil {
|
||||
f.mu.Lock()
|
||||
f.prepEnd = time.Now()
|
||||
f.mu.Unlock()
|
||||
}
|
||||
return entry, err
|
||||
}
|
||||
|
||||
func (f *progressingPreparationFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
delay := f.removeDelay
|
||||
slow := delay > 0 && strings.Contains(dir, "/pool/")
|
||||
if slow {
|
||||
f.mu.Lock()
|
||||
if f.removeStart.IsZero() {
|
||||
f.removeStart = time.Now()
|
||||
}
|
||||
f.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(delay):
|
||||
}
|
||||
}
|
||||
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
|
||||
if slow && err == nil {
|
||||
f.mu.Lock()
|
||||
f.removeEnd = time.Now()
|
||||
f.mu.Unlock()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// A real callback, catalog sweep and provider status cross the old total bound.
|
||||
func TestRealMaintenanceProgressingPastOneMinuteCompletes(t *testing.T) {
|
||||
testRealMaintenanceProgress(t, 0)
|
||||
}
|
||||
|
||||
func TestRealMaintenancePreparationAndRemovalEachOutliveWindow(t *testing.T) {
|
||||
testRealMaintenanceProgress(t, 500*time.Millisecond)
|
||||
}
|
||||
|
||||
func testRealMaintenanceProgress(t *testing.T, removeDelay time.Duration) {
|
||||
t.Helper()
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fixture := testutil.NewLayoutFixture(t, "v1", 4096, 16)
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 4096, ChunkBlocks: 16, ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: time.Minute, ChunkStagger: true}
|
||||
fixture.Configure(&cfg)
|
||||
slow := &progressingPreparationFiler{Filer: fixture.Filer, seen: map[string]bool{}, removeDelay: removeDelay}
|
||||
cat, err := chunkstore.NewBCatalog(slow, fixture.Blobs, "/provider-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var p *durable.DurableProvider
|
||||
cfg.ChunkMaintenance = newChunkMaintenance(cat, fixture.Ref, func(ctx context.Context) (layoutCleaner, error) {
|
||||
r, e := p.LayoutRemote(ctx, "v1")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return r.(layoutCleaner), nil
|
||||
}, true, time.Now)
|
||||
p, err = durable.NewDurableProvider(cfg, cleaningView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := cat.Store(fixture.Ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = fixture.Filer.CreateEntry(ctx, path.Join("/provider-test", fixture.Ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint64(0); i < 192; i++ {
|
||||
data := bytes.Repeat([]byte{byte(i + 1)}, 4096)
|
||||
n := layout.NameChunk(i, data)
|
||||
if err = layout.EnsureObject(ctx, st, n.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
slow.mu.Lock()
|
||||
slow.enabled = true
|
||||
slow.mu.Unlock()
|
||||
if !p.KickMaintenance("v1") {
|
||||
t.Fatal("kick refused")
|
||||
}
|
||||
time.Sleep(95*time.Second + 192*removeDelay)
|
||||
synctest.Wait()
|
||||
m := maintenanceJSON(t, p)
|
||||
if m["passesOk"] != float64(1) {
|
||||
t.Fatalf("real progressing sweep failed to complete: %v", m)
|
||||
}
|
||||
slow.mu.Lock()
|
||||
prep, removal := slow.prepEnd.Sub(slow.prepStart), slow.removeEnd.Sub(slow.removeStart)
|
||||
slow.mu.Unlock()
|
||||
t.Logf("completed phases: preparation=%v removal=%v window=1m", prep, removal)
|
||||
if prep <= time.Minute || removeDelay > 0 && removal <= time.Minute {
|
||||
t.Fatalf("fixture did not cross both phase windows: preparation=%v removal=%v", prep, removal)
|
||||
}
|
||||
last := m["lastPass"].(map[string]any)
|
||||
if last["removedChunks"] != float64(192) || last["processed"].(float64) < 192 || last["error"] != "" {
|
||||
t.Fatalf("real sweep counts: %v", last)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -280,7 +280,13 @@ func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) {
|
||||
} else if last["error"] != "" || last["headGenError"] != "" {
|
||||
t.Fatalf("unexpected error: %v", last)
|
||||
}
|
||||
if after.Gen != before.Gen+2 || m["passesOk"] != float64(1) || last["headGen"].(float64) != float64(expectedGen) {
|
||||
// Initial admission closes before enumeration, then roots, segments
|
||||
// and (unless metadata-only) chunks each have their own begin/end.
|
||||
pages := uint64(3)
|
||||
if kind == "metadata-only" {
|
||||
pages = 2
|
||||
}
|
||||
if after.Gen != before.Gen+2+2*pages || m["passesOk"] != float64(1) || last["headGen"].(float64) != float64(expectedGen) {
|
||||
t.Fatalf("before=%d after=%d status=%v", before.Gen, after.Gen, m)
|
||||
}
|
||||
total, chunks := float64(3), float64(1)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"currentStartNs": 0,
|
||||
"lastPass": {
|
||||
"atNs": 1,
|
||||
"processed": 0,
|
||||
"planned": 0,
|
||||
"removed": 0,
|
||||
"plannedChunks": 0,
|
||||
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// chunkRunCatalogSnapshotDelete is the CLI-owned execution/observation seam.
|
||||
@@ -37,6 +39,31 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata
|
||||
return map[string]any{"operation_id": op.ID, "volume_id": op.VolumeID.String(), "incarnation": snapshotIncarnation(op), "instance": op.Instance, "sequence": op.Sequence, "state": op.State}, nil
|
||||
}
|
||||
answer, err := cat.RunSnapshotDeleteOperation(ctx, volume, op, work)
|
||||
_, bounded := ctx.Deadline()
|
||||
for bounded && errors.Is(err, layout.ErrBusy) {
|
||||
// Resume the captured incarnation, never re-admit the snapshot name.
|
||||
// The enclosing command's window bounds both pauses and attempts.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, err
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, readErr := cat.Store(volume)
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
op, readErr = st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
answer, err = cat.RunSnapshotDeleteOperation(ctx, volume, op, work)
|
||||
}
|
||||
if errors.Is(err, layout.ErrBusy) {
|
||||
return nil, err // A caller without a window must not start endless retries.
|
||||
}
|
||||
if err != nil {
|
||||
return nil, &chunkstore.CatalogError{Code: "no_progress", Message: err.Error() + "; resume with --request-id " + op.ID, Retryable: true, Err: err}
|
||||
}
|
||||
|
||||
@@ -345,7 +345,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) || errors.Is(err, layout.ErrQueueFull))
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrBusy))
|
||||
default:
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
}
|
||||
|
||||
@@ -439,6 +439,7 @@ func layoutCode(err error) string {
|
||||
code string
|
||||
}{
|
||||
{layout.ErrQueueFull, chunkstore.CodeQueueFull},
|
||||
{layout.ErrBusy, "layout_busy"},
|
||||
{layout.ErrNoSnapshot, "snapshot_not_found"},
|
||||
{layout.ErrSnapshotDeleteNeedsOperation, "snapshot_delete_requires_operation"},
|
||||
{layout.ErrHasDependents, "snapshot_has_dependents"},
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
func TestSnapshotDeleteCLILayoutBusyIsTypedRetryable(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{"open clean transaction", fmt.Errorf("delete: %w", layout.ErrBusy), "layout_busy"},
|
||||
{"queue full remains specific", layout.ErrQueueFull, "queue_full"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := layoutCode(tc.err); got != tc.code {
|
||||
t.Errorf("layoutCode: %q; want %q", got, tc.code)
|
||||
}
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkResult("snapshot-delete", nil, tc.err, &out, &diag)
|
||||
answer := chunkErrorOut(t, out.String())
|
||||
if exit != chunkExitFailed || answer.Code != tc.code || !answer.Retryable {
|
||||
t.Fatalf("CLI delete: exit=%d answer=%+v; want failure with %s retryable", exit, answer, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotDeleteCLIRetriesBusyWithSameIdentityWithinWindow(t *testing.T) {
|
||||
for _, neverReady := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("neverReady=%v", neverReady), func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
mem := newMemChunkStore()
|
||||
useMemChunkStore(t, mem)
|
||||
v := cliVolume(t, mem, "v1", "daily")
|
||||
cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI)
|
||||
st, _ := cat.Store(v)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
|
||||
defer cancel()
|
||||
op, err := st.AdmitSnapshotDeleteOperation(ctx, "same-delete", "daily", func(context.Context) (uint64, error) { return 19, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := 0
|
||||
work := func(ctx context.Context, st *chunkstore.LayoutStore, running chunkstore.SnapshotOperation) error {
|
||||
calls++
|
||||
if running.ID != op.ID || running.Instance != op.Instance || running.Sequence != op.Sequence || *running.TargetGeneration != 19 {
|
||||
t.Fatal("busy retry changed the admitted target or identity")
|
||||
}
|
||||
if neverReady || calls < 3 {
|
||||
return layout.ErrBusy
|
||||
}
|
||||
_, err := st.AdvanceSnapshotOperation(ctx, running, "succeeded", json.RawMessage(`{"state":"deleted"}`), "")
|
||||
return err
|
||||
}
|
||||
var diag bytes.Buffer
|
||||
_, err = chunkCatalogSnapshotDeleteAnswer(ctx, cat, v, op, work, false, &diag)
|
||||
if neverReady {
|
||||
if !errors.Is(err, layout.ErrBusy) || ctx.Err() == nil || calls < 2 || calls > 4 {
|
||||
t.Fatalf("busy window: calls=%d ctx=%v err=%v", calls, ctx.Err(), err)
|
||||
}
|
||||
} else if err != nil || calls != 3 {
|
||||
t.Fatalf("retry after release: calls=%d err=%v", calls, err)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,12 @@ func (c *BCatalog) ReadHeadObserved(ctx context.Context, v VolumeRef) (layout.He
|
||||
// DeleteSnapshot removes the named snapshot; refused while it has
|
||||
// dependents.
|
||||
func (c *BCatalog) DeleteSnapshot(ctx context.Context, v VolumeRef, name string) (layout.Head, error) {
|
||||
done, err := c.acquirePublishers(ctx, v)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
defer done()
|
||||
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
@@ -160,7 +166,7 @@ func (c *BCatalog) Restore(ctx context.Context, src VolumeRef, snapshot string,
|
||||
if !found {
|
||||
return layout.Head{}, layout.ErrMissing
|
||||
}
|
||||
return layout.CreateTarget(ctx, ss, sr, snapshot, ts, layout.Volume{ID: target.ID, Name: target.Name, Format: layout.VolumeFormat, Geometry: source.Geometry}, copyRoot)
|
||||
return layout.CreateTarget(ctx, c.publishingStore(src, ss), sr, snapshot, c.publishingStore(target, ts), layout.Volume{ID: target.ID, Name: target.Name, Format: layout.VolumeFormat, Geometry: source.Geometry}, copyRoot)
|
||||
}
|
||||
|
||||
func (c *BCatalog) fetchVerified(ctx context.Context, s *LayoutStore, v VolumeRef, rel string, want layout.Hash) ([]byte, error) {
|
||||
@@ -190,7 +196,7 @@ func (c *BCatalog) ReleaseTarget(ctx context.Context, src, target VolumeRef) (la
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
return layout.OperatorReleaseDependent(ctx, ss, ts, tr, target.ID)
|
||||
return layout.OperatorReleaseDependent(ctx, c.publishingStore(src, ss), c.publishingStore(target, ts), tr, target.ID)
|
||||
}
|
||||
|
||||
// DeleteVolume deletes the volume in the kernel's order. The sources it is
|
||||
@@ -223,10 +229,10 @@ func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.De
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources = append(sources, ss)
|
||||
sources = append(sources, c.publishingStore(o, ss))
|
||||
}
|
||||
list := func(ctx context.Context) ([]string, error) { return c.listObjects(ctx, v) }
|
||||
if err := layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list, progress...); err != nil {
|
||||
if err := layout.DeleteVolume(ctx, c.publishingStore(v, s), auth, v.ID, sources, s, list, progress...); err != nil {
|
||||
return skipped, err
|
||||
}
|
||||
return skipped, s.deleteSnapshotOperations(ctx)
|
||||
|
||||
@@ -28,6 +28,7 @@ func (c *BCatalog) RunSnapshotDeleteOperation(ctx context.Context, v VolumeRef,
|
||||
if err != nil {
|
||||
return SnapshotOperation{}, err
|
||||
}
|
||||
st = c.publishingStore(v, st)
|
||||
op, err := st.ReadSnapshotOperationHandle(ctx, expected.ID, expected.Verb, expected.Instance, expected.Sequence)
|
||||
if err != nil {
|
||||
return SnapshotOperation{}, err
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// cleanAdmission is process-local scheduling, never layout authority. It is
|
||||
// shared by one catalog's stores/remotes for the same full volume identity.
|
||||
// No storage call is made with mu held. Publishers register before waiting;
|
||||
// their cancellation always withdraws the mark, so cleaning cannot be orphaned.
|
||||
type cleanAdmission struct {
|
||||
mu sync.Mutex
|
||||
changed chan struct{}
|
||||
cleaning bool
|
||||
publishers uint64
|
||||
}
|
||||
|
||||
func (g *cleanAdmission) signal() {
|
||||
if g.changed != nil {
|
||||
close(g.changed)
|
||||
}
|
||||
g.changed = make(chan struct{})
|
||||
}
|
||||
|
||||
func (g *cleanAdmission) publisher(ctx context.Context) (func(), error) {
|
||||
// Scheduling never changes the kernel's activity guards. A3 excludes
|
||||
// synchronous reference-removing publications from registration inside
|
||||
// their own live batch, preserving SnapshotRemoval semantics.
|
||||
owned, _ := ctx.Value(heldCleanAdmissionKey{}).(*cleanAdmissionLease)
|
||||
g.mu.Lock()
|
||||
// Do not form a cross-volume wait cycle while a callback holds a clean
|
||||
// lease elsewhere. The caller can retry after releasing that activity.
|
||||
if owned != nil && !owned.released.Load() && owned.gate != g && g.cleaning {
|
||||
g.mu.Unlock()
|
||||
return nil, layout.ErrBusy
|
||||
}
|
||||
// A3: a synchronous reference-removing callback inside this batch is
|
||||
// unregistered. Its original kernel guards and held-generation check
|
||||
// still apply; scheduling never grants it layout authority.
|
||||
if owned != nil && !owned.released.Load() && owned.gate == g {
|
||||
g.mu.Unlock()
|
||||
return func() {}, nil
|
||||
}
|
||||
g.publishers++
|
||||
g.signal()
|
||||
done := func() { g.mu.Lock(); g.publishers--; g.signal(); g.mu.Unlock() }
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
g.mu.Unlock()
|
||||
done()
|
||||
return nil, err
|
||||
}
|
||||
if !g.cleaning {
|
||||
g.mu.Unlock()
|
||||
return done, nil
|
||||
}
|
||||
changed := g.changed
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
g.mu.Lock()
|
||||
g.publishers--
|
||||
g.signal()
|
||||
g.mu.Unlock()
|
||||
return nil, ctx.Err()
|
||||
case <-changed:
|
||||
}
|
||||
g.mu.Lock()
|
||||
}
|
||||
}
|
||||
|
||||
func (g *cleanAdmission) batch(ctx context.Context) (func(), error) {
|
||||
g.mu.Lock()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
g.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if !g.cleaning && g.publishers == 0 {
|
||||
g.cleaning = true
|
||||
g.mu.Unlock()
|
||||
return func() { g.mu.Lock(); g.cleaning = false; g.signal(); g.mu.Unlock() }, nil
|
||||
}
|
||||
if g.changed == nil {
|
||||
g.signal()
|
||||
}
|
||||
changed := g.changed
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-changed:
|
||||
}
|
||||
g.mu.Lock()
|
||||
}
|
||||
}
|
||||
|
||||
// acquirePublishers marks every HEAD this catalog operation can publish. These
|
||||
// are interests, not exclusive writer locks: nested/duplicate volume interests
|
||||
// can coexist and never wait on each other. Only a held cleaner delays them.
|
||||
// The operation's existing HEAD CAS/session remains the publication authority.
|
||||
func (c *BCatalog) acquirePublishers(ctx context.Context, volumes ...VolumeRef) (func(), error) {
|
||||
releases := make([]func(), 0, len(volumes))
|
||||
done := func() {
|
||||
for i := len(releases) - 1; i >= 0; i-- {
|
||||
releases[i]()
|
||||
}
|
||||
}
|
||||
for _, volume := range volumes {
|
||||
release, err := c.cleaningCursor(volume).admission.publisher(ctx)
|
||||
if err != nil {
|
||||
done()
|
||||
return nil, err
|
||||
}
|
||||
releases = append(releases, release)
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
|
||||
type initialCleanAdmissionKey struct{}
|
||||
type heldCleanAdmissionKey struct{}
|
||||
type cleanAdmissionLease struct {
|
||||
once sync.Once
|
||||
done func()
|
||||
gate *cleanAdmission
|
||||
released atomic.Bool
|
||||
}
|
||||
|
||||
func (a *cleanAdmissionLease) release() { a.once.Do(func() { a.released.Store(true); a.done() }) }
|
||||
|
||||
// The initial remote activity transfers admission at its first durable close,
|
||||
// before the catalog acquires per-page admission. The remote also defers the
|
||||
// same idempotent release for an error or a callback that is not the catalog.
|
||||
func releaseInitialCleanAdmission(ctx context.Context) {
|
||||
if a, ok := ctx.Value(initialCleanAdmissionKey{}).(*cleanAdmissionLease); ok {
|
||||
a.release()
|
||||
}
|
||||
}
|
||||
|
||||
// publishingStore scopes admission to each read/compute/CAS transition, never the
|
||||
// surrounding enumeration, object copying, receipt settlement, or delete loop.
|
||||
// The clone shares counters/backends; the plain Store remains a low-level view.
|
||||
func (c *BCatalog) publishingStore(v VolumeRef, s *LayoutStore) *LayoutStore {
|
||||
view := *s
|
||||
view.publicationAdmission = &c.cleaningCursor(v).admission
|
||||
return &view
|
||||
}
|
||||
|
||||
// BeginHeadPublication is the kernel's optional scheduling hook, called before
|
||||
// reading the HEAD of one transition and released after its CAS/no-op/error.
|
||||
// Plain low-level and authority stores do not register. UpdateHead itself must
|
||||
// not acquire: runTransition already owns the interest and prepared generation.
|
||||
func (s *LayoutStore) BeginHeadPublication(ctx context.Context) (func(), error) {
|
||||
if s.publicationAdmission == nil {
|
||||
return func() {}, nil
|
||||
}
|
||||
return s.publicationAdmission.publisher(ctx)
|
||||
}
|
||||
@@ -0,0 +1,721 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type publicationProbeKey struct{}
|
||||
|
||||
type publicationBackendFiler struct {
|
||||
Filer
|
||||
beforeCAS func(context.Context) error
|
||||
}
|
||||
|
||||
func (f *publicationBackendFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if e.Name == layout.HeadName && ctx.Value(publicationProbeKey{}) == true {
|
||||
if err := f.beforeCAS(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return f.Filer.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
type publisherDelayKey struct{}
|
||||
type pausedPublisherFiler struct {
|
||||
Filer
|
||||
paused bool
|
||||
skip int
|
||||
}
|
||||
|
||||
func (f *pausedPublisherFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if ctx.Value(publisherDelayKey{}) == true && name == layout.HeadName && !f.paused {
|
||||
if f.skip > 0 {
|
||||
f.skip--
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
f.paused = true
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestMaintenanceWaitingPublisherRunsBeforeNextBatch(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
cat.f = &pausedPublisherFiler{Filer: cat.f}
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
release, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "first-batch"); err != nil {
|
||||
release()
|
||||
t.Fatal(err)
|
||||
}
|
||||
publisher := make(chan error, 1)
|
||||
go func() {
|
||||
remote.mu.Lock()
|
||||
_, err := remote.beginSessionLocked(context.WithValue(ctx, publisherDelayKey{}, true))
|
||||
remote.mu.Unlock()
|
||||
publisher <- err
|
||||
}()
|
||||
synctest.Wait() // The cut has registered its mark while the first batch holds.
|
||||
g.mu.Lock()
|
||||
waiting := g.publishers
|
||||
g.mu.Unlock()
|
||||
if waiting != 1 {
|
||||
release()
|
||||
t.Fatalf("publisher mark=%d; want 1", waiting)
|
||||
}
|
||||
next := make(chan error, 1)
|
||||
go func() {
|
||||
done, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
next <- err
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
_, err = layout.RunBeginClean(ctx, st, cleanHolder, "second-batch")
|
||||
next <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
if _, err := layout.RunEndClean(ctx, st, cleanHolder, "first-batch", layout.CauseCleanEnd); err != nil {
|
||||
release()
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
// The publisher is deliberately slow AFTER admission, before its HEAD write.
|
||||
// A pause/chance is insufficient: no second batch may enter during this gap.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
select {
|
||||
case err := <-next:
|
||||
t.Fatalf("second batch passed waiting publisher before its write: %v", err)
|
||||
default:
|
||||
}
|
||||
if err := <-publisher; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-next; !errors.Is(err, layout.ErrBusy) {
|
||||
t.Fatalf("next begin did not observe publisher's open snapshot: %v", err)
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil || h.Activity != (layout.Activity{Kind: layout.ActSnap, Session: remote.session}) {
|
||||
t.Fatalf("publisher did not win: %+v err=%v", h.Activity, err)
|
||||
}
|
||||
if _, err := layout.RunAbort(ctx, st, cleanHolder, remote.session, layout.CauseSessionRollback); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("waiting same-catalog cut wrote HEAD before the next batch could begin")
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceCancelledPublisherWithdrawsItsMark(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var g cleanAdmission
|
||||
release, err := g.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
done, err := g.publisher(ctx)
|
||||
if done != nil {
|
||||
done()
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
cancel()
|
||||
if err := <-result; !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancelled publisher: %v", err)
|
||||
}
|
||||
release()
|
||||
done, err := g.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done()
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.publishers != 0 || g.cleaning {
|
||||
t.Fatalf("orphaned admission: publishers=%d cleaning=%v", g.publishers, g.cleaning)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenancePublisherWaitKeepsRemoteDeadlineClassification(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _, err := st.ReadHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
release, err := g.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_, err = remote.Begin(ctx)
|
||||
if !errors.Is(err, storage.ErrChunkRemoteUnavailable) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
release()
|
||||
t.Fatalf("admission wait changed caller classification: %v", err)
|
||||
}
|
||||
after, _, err := st.ReadHead(context.Background())
|
||||
if err != nil || before.Gen != after.Gen {
|
||||
release()
|
||||
t.Fatalf("cancelled waiter wrote HEAD: err=%v", err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
release()
|
||||
if pending != 0 {
|
||||
t.Fatalf("cancelled remote left %d publisher marks", pending)
|
||||
}
|
||||
session, err := remote.Begin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("fresh publisher after cancellation: %v", err)
|
||||
}
|
||||
if _, err := layout.RunAbort(context.Background(), st, cleanHolder, session, layout.CauseSessionRollback); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceOwnCutStillCancelsAndJoinsItsCleanerBeforeAdmission(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release, err := remote.admission.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cleanCtx, cleanCancel := context.WithCancel(context.Background())
|
||||
defer cleanCancel()
|
||||
remote.cleaning, remote.cleanCancel, remote.cleanDone = "own-cleaner", cleanCancel, make(chan struct{})
|
||||
joined := make(chan struct{})
|
||||
go func() {
|
||||
<-cleanCtx.Done()
|
||||
release()
|
||||
remote.mu.Lock()
|
||||
remote.cleaning = ""
|
||||
close(remote.cleanDone)
|
||||
remote.mu.Unlock()
|
||||
close(joined)
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
session, err := remote.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("own cut waited on admission without cancelling/joining cleaner: %v", err)
|
||||
}
|
||||
<-joined
|
||||
if cleanCtx.Err() != context.Canceled {
|
||||
t.Fatal("own cleaner was not cancelled")
|
||||
}
|
||||
if _, err := layout.RunAbort(context.Background(), st, cleanHolder, session, layout.CauseSessionRollback); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceRetainPublisherPrecedesANewCleanPass(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
now := time.Now()
|
||||
snapshotWithMeta(t, cat, ref, "expired", layout.SnapshotMeta{Class: layout.ClassSemantic, CreatedNs: now.Add(-2 * time.Hour).UnixNano(), ExpiresNs: now.Add(-time.Hour).UnixNano()}, "expiration", 2)
|
||||
if err := cat.SetRetention(ctx, ref, retain.Policy{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cat.f = &pausedPublisherFiler{Filer: cat.f, skip: 1}
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
release, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
retained := make(chan error, 1)
|
||||
go func() {
|
||||
result, err := cat.Retain(context.WithValue(ctx, publisherDelayKey{}, true), ref, now, false)
|
||||
expired := false
|
||||
for _, name := range result.Deleted {
|
||||
expired = expired || name == "expired"
|
||||
}
|
||||
if err == nil && !expired {
|
||||
err = fmt.Errorf("retention did not publish: deleted=%v", result.Deleted)
|
||||
}
|
||||
retained <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
g.mu.Lock()
|
||||
marked := g.publishers
|
||||
g.mu.Unlock()
|
||||
if marked != 1 {
|
||||
release()
|
||||
t.Fatalf("Retain did not register while batch held: publishers=%d", marked)
|
||||
}
|
||||
release()
|
||||
synctest.Wait() // Retain is paused before its first HEAD read, with mark held.
|
||||
entered := make(chan struct{})
|
||||
cleaned := make(chan error, 1)
|
||||
go func() {
|
||||
cleaned <- remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error {
|
||||
close(entered)
|
||||
h, found, err := st.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
return fmt.Errorf("clean entry HEAD: found=%v err=%v", found, err)
|
||||
}
|
||||
if _, present := h.Snapshots["expired"]; present {
|
||||
return fmt.Errorf("new clean pass overtook Retain publication")
|
||||
}
|
||||
_, err = cat.RemoveUnreachableAll(ctx, ref, me, session)
|
||||
return err
|
||||
})
|
||||
}()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
select {
|
||||
case <-entered:
|
||||
t.Fatal("new clean pass entered before marked Retain published")
|
||||
default:
|
||||
}
|
||||
if err := <-retained; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-cleaned; err != nil {
|
||||
t.Fatalf("initial admission was not handed to catalog batches: %v", err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.cleaning || g.publishers != 0 {
|
||||
t.Fatalf("nested initial/batch gate leaked: cleaning=%v publishers=%d", g.cleaning, g.publishers)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceNestedCatalogPublishersDoNotSelfDeadlock(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
cat, ref, _, _ := cleanFixture(t)
|
||||
done, err := cat.acquirePublishers(ctx, ref, ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.DeleteSnapshot(ctx, ref, "s"); err != nil {
|
||||
done()
|
||||
t.Fatalf("nested direct writer deadlocked/refused: %v", err)
|
||||
}
|
||||
done()
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.publishers != 0 {
|
||||
t.Fatalf("nested publisher marks leaked: %d", g.publishers)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenancePartialMultiVolumeAdmissionUnwindsOnCancellation(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
cat, first, _, _ := cleanFixture(t)
|
||||
second := newRef(t, "second")
|
||||
secondGate := &cat.cleaningCursor(second).admission
|
||||
release, err := secondGate.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
done, err := cat.acquirePublishers(ctx, first, second)
|
||||
if done != nil {
|
||||
done()
|
||||
}
|
||||
release()
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("multi-volume wait did not honour context: %v", err)
|
||||
}
|
||||
for _, ref := range []VolumeRef{first, second} {
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
pending, held := g.publishers, g.cleaning
|
||||
g.mu.Unlock()
|
||||
if pending != 0 || held {
|
||||
t.Fatalf("partial acquisition leaked for %s: publishers=%d held=%v", ref.Name, pending, held)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceNestedWriterInsideInitialCleanKeepsKernelSemantics(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
insideCAS := 0
|
||||
cat.f = &publicationBackendFiler{Filer: cat.f, beforeCAS: func(context.Context) error {
|
||||
insideCAS++
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
return fmt.Errorf("A3 publication transiently registered INSIDE backend CAS: %d", pending)
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := time.Now()
|
||||
err = remote.Clean(ctx, func(ctx context.Context, _ layout.HolderID, session string) error {
|
||||
h, err := cat.DeleteSnapshot(context.WithValue(ctx, publicationProbeKey{}, true), ref, "s")
|
||||
if err == nil && h.Activity != (layout.Activity{Kind: layout.ActClean, Session: session}) {
|
||||
return fmt.Errorf("nested publisher changed activity: %+v", h.Activity)
|
||||
}
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
return fmt.Errorf("A3 removal nested publisher registration: %d", pending)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil || time.Since(started) != 0 {
|
||||
t.Fatalf("nested initial writer waited or changed kernel semantics: elapsed=%v err=%v", time.Since(started), err)
|
||||
}
|
||||
if insideCAS != 1 {
|
||||
t.Fatalf("A3 proof did not observe its backend CAS: %d", insideCAS)
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("nested publication left activity: %+v err=%v", h.Activity, err)
|
||||
}
|
||||
if _, found := h.Snapshots["s"]; found {
|
||||
t.Fatal("nested kernel-authorized delete was lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceReleasedBatchContextCannotBypassANewBatch(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var g cleanAdmission
|
||||
first, err := g.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease := &cleanAdmissionLease{done: first, gate: &g}
|
||||
oldCtx := context.WithValue(context.Background(), heldCleanAdmissionKey{}, lease)
|
||||
lease.release()
|
||||
second, err := g.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(oldCtx, time.Second)
|
||||
defer cancel()
|
||||
done, err := g.publisher(ctx)
|
||||
if done != nil {
|
||||
done()
|
||||
}
|
||||
second()
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("released batch context bypassed a later batch: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceCrossVolumeCallbackDoesNotWaitWhileHoldingAClean(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
cat, first, _, _ := cleanFixture(t)
|
||||
second := newRef(t, "second")
|
||||
firstGate := &cat.cleaningCursor(first).admission
|
||||
secondGate := &cat.cleaningCursor(second).admission
|
||||
releaseFirst, err := firstGate.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease := &cleanAdmissionLease{done: releaseFirst, gate: firstGate}
|
||||
defer lease.release()
|
||||
releaseSecond, err := secondGate.batch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer releaseSecond()
|
||||
ctx, cancel := context.WithTimeout(context.WithValue(context.Background(), heldCleanAdmissionKey{}, lease), time.Second)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
done, err := cat.acquirePublishers(ctx, first, second)
|
||||
if done != nil {
|
||||
done()
|
||||
}
|
||||
if !errors.Is(err, layout.ErrBusy) || time.Since(started) != 0 {
|
||||
t.Fatalf("cross-volume callback held clean while waiting: elapsed=%v err=%v", time.Since(started), err)
|
||||
}
|
||||
for _, g := range []*cleanAdmission{firstGate, secondGate} {
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatalf("partial nested interest remained: %d", pending)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceRetainPlanningDoesNotRegister(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cat, ref, _, _ := cleanFixture(t)
|
||||
cat.f = &pausedPublisherFiler{Filer: cat.f}
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := cat.Retain(context.WithValue(ctx, publisherDelayKey{}, true), ref, time.Now(), false)
|
||||
result <- err
|
||||
}()
|
||||
synctest.Wait() // Planning is paused in its first HEAD read.
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatalf("planning holds publisher interest: %d", pending)
|
||||
}
|
||||
release, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenancePublishingStoreScopesOneConditionalWrite(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cat, ref, plain, _ := cleanFixture(t)
|
||||
view := cat.publishingStore(ref, plain)
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
release, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, found, err := view.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("read: %v %v", found, err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 || plain.publicationAdmission != nil {
|
||||
t.Fatal("read or plain low-level store registered")
|
||||
}
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
done, err := view.BeginHeadPublication(ctx)
|
||||
if err != nil {
|
||||
result <- err
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
fresh, _, err := view.ReadHead(ctx)
|
||||
if err == nil {
|
||||
err = view.UpdateHead(ctx, fresh.Gen, fresh, layout.CauseDependentRelease)
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
g.mu.Lock()
|
||||
pending = g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 1 {
|
||||
t.Fatalf("conditional publication did not register: %d", pending)
|
||||
}
|
||||
release()
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
pending = g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatal("publication retained interest after return")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceRetainReleasesBetweenRetirements(t *testing.T) {
|
||||
cat, ref, _, _ := cleanFixture(t)
|
||||
now := time.Now()
|
||||
snapshotWithMeta(t, cat, ref, "expired", layout.SnapshotMeta{Class: layout.ClassSemantic, CreatedNs: now.Add(-2 * time.Hour).UnixNano(), ExpiresNs: now.Add(-time.Hour).UnixNano()}, "expiration", 2)
|
||||
if err := cat.SetRetention(context.Background(), ref, retain.Policy{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reports := 0
|
||||
ctx := layout.WithMaintenanceProgress(context.Background(), func(layout.MaintenancePosition) {
|
||||
reports++
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Errorf("retirement completion retained interest across decisions: %d", pending)
|
||||
}
|
||||
})
|
||||
result, err := cat.Retain(ctx, ref, now, false)
|
||||
if err != nil || len(result.Deleted) != 2 || reports != 2 {
|
||||
t.Fatalf("retirements: %+v reports=%d err=%v", result, reports, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceReleasePublicationReadsAfterBatchClose(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
target := newRef(t, "dependent")
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sn := h.Snapshots["s"]
|
||||
sn.Dependents = []layout.Dependent{{Target: target.Name, TargetID: target.ID, Root: sn.Root}}
|
||||
h.Snapshots["s"] = sn
|
||||
if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseDependentAdd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
release, err := g.batch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "publication-wait"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := layout.RunReleaseDependent(ctx, cat.publishingStore(ref, st), target.ID)
|
||||
result <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 1 {
|
||||
t.Fatalf("release did not register: %d", pending)
|
||||
}
|
||||
if _, err := layout.RunEndClean(ctx, st, cleanHolder, "publication-wait", layout.CauseCleanEnd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
if err := <-result; err != nil {
|
||||
t.Fatalf("release prepared against batch generation instead of waiting before its read: %v", err)
|
||||
}
|
||||
h, _, err = st.ReadHead(ctx)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle || len(h.Snapshots["s"].Dependents) != 0 {
|
||||
t.Fatalf("release did not publish after batch close: %+v %v", h, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenancePublisherInterestHeldThroughBackendCAS(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cat, ref, _, _ := cleanFixture(t)
|
||||
entered, finish := make(chan struct{}), make(chan struct{})
|
||||
cat.f = &publicationBackendFiler{Filer: cat.f, beforeCAS: func(ctx context.Context) error {
|
||||
close(entered)
|
||||
select {
|
||||
case <-finish:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}}
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
published := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := layout.RunDeleteSnapshot(context.WithValue(ctx, publicationProbeKey{}, true), cat.publishingStore(ref, st), "s")
|
||||
published <- err
|
||||
}()
|
||||
<-entered // The actual backend HEAD CAS has not returned.
|
||||
next := make(chan error, 1)
|
||||
g := &cat.cleaningCursor(ref).admission
|
||||
go func() {
|
||||
done, err := g.batch(ctx)
|
||||
if err == nil {
|
||||
done()
|
||||
}
|
||||
next <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
select {
|
||||
case err := <-next:
|
||||
t.Fatalf("clean batch entered before backend CAS returned: %v", err)
|
||||
default:
|
||||
}
|
||||
g.mu.Lock()
|
||||
pending := g.publishers
|
||||
g.mu.Unlock()
|
||||
if pending != 1 {
|
||||
t.Fatalf("backend CAS lost publication interest: %d", pending)
|
||||
}
|
||||
close(finish)
|
||||
if err := <-published; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-next; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, present := h.Snapshots["s"]; present {
|
||||
t.Fatal("backend CAS did not remove snapshot")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -7,12 +7,15 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
var cleanPage uint32 = 1000
|
||||
|
||||
const cleanSessionHold = 5 * time.Second
|
||||
|
||||
// CleanResult counts names examined/deleted by this bounded pass, all kinds.
|
||||
type CleanResult struct {
|
||||
Shards int
|
||||
@@ -27,10 +30,31 @@ type CleanResult struct {
|
||||
Lists int
|
||||
}
|
||||
|
||||
// The cursor is scheduling only: after a timeout a new session re-plans tags
|
||||
// and validates HEAD; no cached safety decision survives the pass. Completing
|
||||
// the last shard wraps to roots so earlier/new names are revisited next time.
|
||||
// cleanPosition orders the finite sweep without retaining object identities.
|
||||
type cleanPosition struct {
|
||||
phase int
|
||||
shard uint64
|
||||
after string
|
||||
}
|
||||
|
||||
func (p cleanPosition) before(q cleanPosition) bool {
|
||||
if p.phase != q.phase {
|
||||
return p.phase < q.phase
|
||||
}
|
||||
if p.shard != q.shard {
|
||||
return p.shard < q.shard
|
||||
}
|
||||
return p.after < q.after
|
||||
}
|
||||
|
||||
// The cursor is scheduling only: a new pass re-plans tags and validates HEAD;
|
||||
// no cached safety decision survives it. The single stuck position and refusal
|
||||
// count survive earlier revisits, but reset when that work position advances.
|
||||
type cleanCursor struct {
|
||||
admission cleanAdmission
|
||||
refusals uint8 // saturates at K; spans passes, including refused revisits
|
||||
stuck cleanPosition
|
||||
|
||||
mu sync.Mutex
|
||||
phase int // roots, segments, chunks
|
||||
shard string
|
||||
@@ -59,6 +83,7 @@ func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor {
|
||||
// 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) {
|
||||
ctx = layout.WithMaintenancePhase(ctx, layout.MaintenanceSweep)
|
||||
cur := c.cleaningCursor(v)
|
||||
if !cur.mu.TryLock() {
|
||||
return res, layout.ErrBusy
|
||||
@@ -69,6 +94,134 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
return res, err
|
||||
}
|
||||
cleaner := layout.NewCleaner(s, r, s, me, session)
|
||||
// Clean entered with this pass's activity. Release it before enumeration;
|
||||
// each bounded candidate page below acquires its own activity and fresh view.
|
||||
closed, err := endCleanBatch(ctx, s, me, session)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
releaseInitialCleanAdmission(ctx)
|
||||
page := func(kind string, shard uint64, names []string) (out layout.RemovalResult, err error) {
|
||||
if len(names) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
fresh, found, err := s.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if !found {
|
||||
return out, layout.ErrHeadAbsent
|
||||
}
|
||||
if fresh.Gen != closed.Gen {
|
||||
cleaner.ResetReachability()
|
||||
}
|
||||
position := cleanPosition{shard: shard, after: cur.after}
|
||||
switch kind {
|
||||
case layout.RootDir:
|
||||
position.phase = 0
|
||||
case layout.SegDir:
|
||||
position.phase = 1
|
||||
case layout.PoolDir:
|
||||
position.phase, position.after = 2, cur.poolAfter
|
||||
case layout.ListDir:
|
||||
position.phase, position.after = 3, cur.listAfter
|
||||
}
|
||||
// Once armed, revisits must also prepare under activity; otherwise a
|
||||
// busy root revisit could prevent reaching the stuck pool page forever.
|
||||
if cur.refusals >= 3 {
|
||||
release, err := cur.admission.batch(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
lease := &cleanAdmissionLease{done: release, gate: &cur.admission}
|
||||
defer lease.release()
|
||||
held := context.WithValue(ctx, heldCleanAdmissionKey{}, lease)
|
||||
started := time.Now()
|
||||
opened, err := layout.RunBeginClean(held, s, me, session)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
cleaner.ResetReachability()
|
||||
prepCtx, cancel := context.WithDeadline(held, started.Add(cleanSessionHold))
|
||||
heldCtx := layout.WithHeldCleanerBatch(prepCtx, opened, func(_ context.Context, _ layout.Head, effects func(context.Context) error) error {
|
||||
// Only read-only preparation carries the session deadline.
|
||||
// Never cancel an in-flight mutation at the hold timer.
|
||||
return effects(layout.WithCleanBatchEnd(held, started.Add(cleanSessionHold)))
|
||||
})
|
||||
out, err = cleaner.Page(heldCtx, kind, shard, names)
|
||||
cancel()
|
||||
var closeErr error
|
||||
closed, closeErr = endCleanBatch(held, s, me, session)
|
||||
if closeErr != nil {
|
||||
return layout.RemovalResult{}, errors.Join(err, closeErr)
|
||||
}
|
||||
if out.After != "" && !position.before(cur.stuck) {
|
||||
cur.refusals = 0
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
refused := false
|
||||
applied := false
|
||||
settled := true
|
||||
batchCtx := layout.WithCleanerBatch(ctx, fresh, func(ctx context.Context, base layout.Head, effects func(context.Context) error) error {
|
||||
release, err := cur.admission.batch(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lease := &cleanAdmissionLease{done: release, gate: &cur.admission}
|
||||
defer lease.release()
|
||||
ctx = context.WithValue(ctx, heldCleanAdmissionKey{}, lease)
|
||||
started := time.Now()
|
||||
opened, err := layout.RunBeginClean(ctx, s, me, session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var effectErr error
|
||||
if opened.Gen != base.Gen+1 {
|
||||
// Preparation overlapped another publication: no prepared decision
|
||||
// is allowed to run at the new generation.
|
||||
cleaner.ResetReachability()
|
||||
refused = true
|
||||
effectErr = layout.ErrPrecondition
|
||||
} else {
|
||||
applied = true
|
||||
effectErr = effects(layout.WithCleanBatchEnd(ctx, started.Add(cleanSessionHold)))
|
||||
}
|
||||
var closeErr error
|
||||
closed, closeErr = endCleanBatch(ctx, s, me, session)
|
||||
if closeErr != nil {
|
||||
settled = false
|
||||
}
|
||||
return errors.Join(effectErr, closeErr)
|
||||
})
|
||||
out, err = cleaner.Page(batchCtx, kind, shard, names)
|
||||
if !settled {
|
||||
return layout.RemovalResult{}, err
|
||||
}
|
||||
if refused {
|
||||
if cur.refusals == 0 || cur.stuck.before(position) {
|
||||
cur.stuck = position
|
||||
}
|
||||
if cur.refusals < 3 {
|
||||
cur.refusals++
|
||||
}
|
||||
} else if applied && out.After != "" && !position.before(cur.stuck) {
|
||||
cur.refusals = 0
|
||||
}
|
||||
if out.More && err == nil {
|
||||
// Give callers already retrying layout_busy a handoff opportunity.
|
||||
// This pause is outside the session and earns no pass progress.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return out, ctx.Err()
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
// Every new session starts at the first root: between sessions an operator
|
||||
// may un-name one whose segments this session would otherwise remove first.
|
||||
// Preserve segment/chunk progress, but never carry a root-phase view forward.
|
||||
@@ -101,7 +254,7 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
} else {
|
||||
res.PlannedSegments += len(names)
|
||||
}
|
||||
out, err := cleaner.Page(ctx, kind, 0, names)
|
||||
out, err := page(kind, 0, names)
|
||||
res.Removed += len(out.Names)
|
||||
if kind == layout.RootDir {
|
||||
res.Roots += len(out.Names)
|
||||
@@ -114,6 +267,9 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if out.More {
|
||||
continue
|
||||
}
|
||||
if uint32(len(names)) < cleanPage {
|
||||
cur.phase++
|
||||
cur.after = ""
|
||||
@@ -146,17 +302,17 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
if err := ctx.Err(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
page, err := s.ListChunkCandidates(ctx, shard, cur.poolAfter, cleanPage)
|
||||
candidates, err := s.ListChunkCandidates(ctx, shard, cur.poolAfter, cleanPage)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
names := make([]string, len(page))
|
||||
for i, n := range page {
|
||||
names := make([]string, len(candidates))
|
||||
for i, n := range candidates {
|
||||
names[i] = n.String()
|
||||
}
|
||||
res.Planned += len(page)
|
||||
res.PlannedChunks += len(page)
|
||||
out, err := cleaner.Page(ctx, layout.PoolDir, shard, names)
|
||||
res.Planned += len(candidates)
|
||||
res.PlannedChunks += len(candidates)
|
||||
out, err := page(layout.PoolDir, shard, names)
|
||||
res.Removed += len(out.Names)
|
||||
if out.After != "" {
|
||||
cur.poolAfter = path.Base(out.After)
|
||||
@@ -164,7 +320,10 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if uint32(len(page)) < cleanPage {
|
||||
if out.More {
|
||||
continue
|
||||
}
|
||||
if uint32(len(candidates)) < cleanPage {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -189,7 +348,7 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
}
|
||||
res.Planned += len(names)
|
||||
res.PlannedLists += len(names)
|
||||
out, err := cleaner.Page(ctx, layout.ListDir, 0, names)
|
||||
out, err := page(layout.ListDir, 0, names)
|
||||
res.Removed += len(out.Names)
|
||||
res.Lists += len(out.Names)
|
||||
if out.After != "" {
|
||||
@@ -198,6 +357,9 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if out.More {
|
||||
continue
|
||||
}
|
||||
if uint32(len(names)) < cleanPage {
|
||||
break
|
||||
}
|
||||
@@ -205,3 +367,47 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
|
||||
cur.phase, cur.shard, cur.after, cur.poolAfter, cur.listAfter = 0, "", "", "", ""
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// endCleanBatch settles an applied-but-unanswered close before any re-entry.
|
||||
// Only this pass's activity may be retried; another session is never ended.
|
||||
func endCleanBatch(ctx context.Context, st layout.HeadStore, me layout.HolderID, session string) (layout.Head, error) {
|
||||
uncertain := false
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
closed, err := layout.RunEndClean(ctx, st, me, session, layout.CauseCleanEnd)
|
||||
if err != nil {
|
||||
uncertain = true
|
||||
h, found, readErr := st.ReadHead(ctx)
|
||||
if readErr != nil || !found {
|
||||
return layout.Head{}, errors.Join(err, readErr)
|
||||
}
|
||||
if h.Epoch != me.Epoch || h.Holder != me.Holder || h.ClaimID != me.ClaimID {
|
||||
return layout.Head{}, errors.Join(err, layout.ErrNotHolder)
|
||||
}
|
||||
switch h.Activity {
|
||||
case layout.Activity{Kind: layout.ActIdle}:
|
||||
// It closed, but another writer may have acted before this read.
|
||||
// Do not attribute this observed generation to our cached view.
|
||||
h.Gen = 0
|
||||
return h, nil
|
||||
case layout.Activity{Kind: layout.ActClean, Session: session}:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return layout.Head{}, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
continue // Still ours: retry the same close, never a new begin.
|
||||
default:
|
||||
return layout.Head{}, err
|
||||
}
|
||||
}
|
||||
if uncertain {
|
||||
// A later successful retry may only have read idle after a delayed
|
||||
// close and another publication. Its generation is not our provenance.
|
||||
closed.Gen = 0
|
||||
}
|
||||
return closed, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// Observe successful durable HEAD closes, not the end of an in-memory callback.
|
||||
// One candidate per page makes consecutive removals distinct bounded batches.
|
||||
type batchReleaseFiler struct {
|
||||
Filer
|
||||
id layout.VolumeID
|
||||
idleWrites, lastIdle, deletes int
|
||||
between func()
|
||||
}
|
||||
|
||||
func (f *batchReleaseFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Name == layout.HeadName {
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActIdle {
|
||||
f.idleWrites++
|
||||
if f.deletes > 0 && f.between != nil {
|
||||
between := f.between
|
||||
f.between = nil
|
||||
between()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMaintenanceBatchDropsReachabilityAfterPublication(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
oldPage := cleanPage
|
||||
cleanPage = 1
|
||||
defer func() { cleanPage = oldPage }()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
// Candidate 4 sorts after the first orphan (2), in the SAME shard whose
|
||||
// reachability was cached by the first candidate's removal.
|
||||
data := bytes.Repeat([]byte{4}, 4096)
|
||||
reused := layout.NameChunk(4, data)
|
||||
if err := layout.EnsureObject(ctx, st, reused.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
published := false
|
||||
observed := &batchReleaseFiler{Filer: cat.f, id: ref.ID}
|
||||
observed.between = func() {
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
prev := map[uint64]layout.Ref{1: {Owner: ref.Name, OwnerID: ref.ID, Chunk: live}}
|
||||
next := map[uint64]layout.Ref{1: prev[1], 4: {Owner: ref.Name, OwnerID: ref.ID, Chunk: reused}}
|
||||
// EnsureObject adopts the existing candidate into this publication's
|
||||
// session; its bytes were already present before cache construction.
|
||||
commitImage(t, st, ref.Name, "between-batches", prev, next, map[uint64][]byte{4: data}, 2, "new-snapshot")
|
||||
published = true
|
||||
}
|
||||
cat.f = observed
|
||||
if _, _, err := cleanVia(ctx, cat, ref, cleanHolder); err != nil {
|
||||
t.Fatalf("sweep across publication: %v", err)
|
||||
}
|
||||
if !published || !present(t, st, reused) {
|
||||
t.Fatal("publication between batches was missed or its re-referenced candidate was removed")
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, st, n) {
|
||||
t.Fatalf("unreferenced candidate remains: %s", n)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type unknownBatchCloseStore struct {
|
||||
layout.HeadStore
|
||||
apply bool
|
||||
absent bool
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *unknownBatchCloseStore) ReadHead(ctx context.Context) (layout.Head, bool, error) {
|
||||
if s.absent && s.calls > 0 {
|
||||
return layout.Head{}, false, nil
|
||||
}
|
||||
return s.HeadStore.ReadHead(ctx)
|
||||
}
|
||||
|
||||
func (s *unknownBatchCloseStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head, cause layout.HeadWriteCause) error {
|
||||
s.calls++
|
||||
if s.calls == 1 {
|
||||
if s.apply {
|
||||
if err := s.HeadStore.UpdateHead(ctx, gen, next, cause); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return s.HeadStore.UpdateHead(ctx, gen, next, cause)
|
||||
}
|
||||
|
||||
func TestMaintenanceBatchSettlesUnknownCloseBeforeReentry(t *testing.T) {
|
||||
for _, applied := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("applied=%v", applied), func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
_, _, st, _ := cleanFixture(t)
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "this-pass"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unknown := &unknownBatchCloseStore{HeadStore: st, apply: applied}
|
||||
if _, err := endCleanBatch(ctx, unknown, cleanHolder, "this-pass"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := 2
|
||||
if applied {
|
||||
want = 1
|
||||
}
|
||||
if unknown.calls != want {
|
||||
t.Fatalf("close writes=%d; want %d", unknown.calls, want)
|
||||
}
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "this-pass"); err != nil {
|
||||
t.Fatalf("re-entry after settled close: %v", err)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
t.Run("foreign session is preserved", func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, _, st, _ := cleanFixture(t)
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "other-pass"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _, _ := st.ReadHead(ctx)
|
||||
if _, err := endCleanBatch(ctx, st, cleanHolder, "this-pass"); err == nil {
|
||||
t.Fatal("foreign close accepted")
|
||||
}
|
||||
after, _, _ := st.ReadHead(ctx)
|
||||
if after.Gen != before.Gen || after.Activity != before.Activity {
|
||||
t.Fatal("foreign activity changed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceBatchUnknownCloseAbsentHeadRefuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, _, st, _ := cleanFixture(t)
|
||||
if _, err := layout.RunBeginClean(ctx, st, cleanHolder, "this-pass"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unknown := &unknownBatchCloseStore{HeadStore: st, absent: true}
|
||||
if _, err := endCleanBatch(ctx, unknown, cleanHolder, "this-pass"); err == nil {
|
||||
t.Fatal("absent HEAD settled an unknown close")
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil || unknown.calls != 1 || h.Activity != (layout.Activity{Kind: layout.ActClean, Session: "this-pass"}) {
|
||||
t.Fatalf("absent settlement changed activity: %+v calls=%d err=%v", h.Activity, unknown.calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *batchReleaseFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if !strings.Contains(dir, "/pool/") {
|
||||
return f.Filer.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
if f.deletes > 0 && f.idleWrites <= f.lastIdle {
|
||||
return fmt.Errorf("next removal batch started without a durable idle HEAD between batches (completed=%d)", f.deletes)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(20 * time.Second):
|
||||
}
|
||||
if err := f.Filer.DeleteEntry(ctx, dir, name, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
f.deletes++
|
||||
f.lastIdle = f.idleWrites
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMaintenanceLongPassReleasesLayoutBetweenBatches(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
oldPage := cleanPage
|
||||
cleanPage = 1
|
||||
defer func() { cleanPage = oldPage }()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
for _, index := range []uint64{4, 5} {
|
||||
data := bytes.Repeat([]byte{byte(index)}, 4096)
|
||||
n := layout.NameChunk(index, data)
|
||||
if err := layout.EnsureObject(ctx, st, n.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orphans = append(orphans, n)
|
||||
}
|
||||
observed := &batchReleaseFiler{Filer: cat.f, id: ref.ID}
|
||||
cat.f = observed
|
||||
started := time.Now()
|
||||
res, _, err := cleanVia(ctx, cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatalf("bounded-batch pass: %v (removed=%d)", err, observed.deletes)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed <= time.Minute || observed.deletes != len(orphans) || res.Removed != len(orphans) {
|
||||
t.Fatalf("long pass witness: elapsed=%v deletes=%d result=%+v; want >1m and all %d orphans gone", elapsed, observed.deletes, res, len(orphans))
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, st, n) {
|
||||
t.Fatalf("orphan remains: %s", n)
|
||||
}
|
||||
}
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
if !present(t, st, live) {
|
||||
t.Fatal("the current root and snapshot's live chunk was removed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Return the old, valid settlement read, then let the delayed close and a
|
||||
// publication land before RunEndClean retries. The retry reads idle and writes
|
||||
// nothing: its generation belongs to the publication, not to this clean pass.
|
||||
type delayedBatchCloseFiler struct {
|
||||
Filer
|
||||
id layout.VolumeID
|
||||
deletes, lost, settled, idleRetryReads, writesAfterPublication int
|
||||
pending func() error
|
||||
publish func()
|
||||
published bool
|
||||
}
|
||||
|
||||
func (f *delayedBatchCloseFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if e.Name == layout.HeadName {
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActIdle && f.deletes == 1 && f.lost == 0 {
|
||||
f.lost++
|
||||
f.pending = func() error { return f.Filer.UpdateEntry(ctx, dir, e, expected) }
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
if f.published {
|
||||
f.writesAfterPublication++
|
||||
}
|
||||
}
|
||||
return f.Filer.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
func (f *delayedBatchCloseFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
e, err := f.Filer.LookupEntry(ctx, dir, name)
|
||||
if err != nil || name != layout.HeadName {
|
||||
return e, err
|
||||
}
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.pending != nil {
|
||||
if h.Activity.Kind != layout.ActClean {
|
||||
return nil, fmt.Errorf("settlement did not observe own clean: %+v", h.Activity)
|
||||
}
|
||||
f.settled++
|
||||
apply := f.pending
|
||||
f.pending = nil
|
||||
if err := apply(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.publish()
|
||||
f.published = true
|
||||
// This read linearized before the delayed close and publication.
|
||||
return e, nil
|
||||
}
|
||||
if f.published && h.Activity.Kind == layout.ActIdle && f.writesAfterPublication == 0 {
|
||||
f.idleRetryReads++
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func (f *delayedBatchCloseFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if err := f.Filer.DeleteEntry(ctx, dir, name, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.Contains(dir, "/pool/") {
|
||||
f.deletes++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMaintenanceDelayedClosePublicationInvalidatesNextPage(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
oldPage := cleanPage
|
||||
cleanPage = 1
|
||||
defer func() { cleanPage = oldPage }()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
data := bytes.Repeat([]byte{4}, 4096)
|
||||
reused := layout.NameChunk(4, data)
|
||||
if err := layout.EnsureObject(ctx, st, reused.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
observed := &delayedBatchCloseFiler{Filer: cat.f, id: ref.ID}
|
||||
observed.publish = func() {
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
prev := map[uint64]layout.Ref{1: {Owner: ref.Name, OwnerID: ref.ID, Chunk: live}}
|
||||
next := map[uint64]layout.Ref{1: prev[1], 4: {Owner: ref.Name, OwnerID: ref.ID, Chunk: reused}}
|
||||
commitImage(t, st, ref.Name, "delayed-close-publication", prev, next, map[uint64][]byte{4: data}, 2, "new-snapshot")
|
||||
}
|
||||
cat.f = observed
|
||||
_, _, err := cleanVia(ctx, cat, ref, cleanHolder)
|
||||
if observed.lost != 1 || observed.settled != 1 || observed.idleRetryReads == 0 {
|
||||
t.Fatalf("missing delayed-close/no-op-retry witness: lost=%d settled=%d idleReadsBeforeWrite=%d err=%v", observed.lost, observed.settled, observed.idleRetryReads, err)
|
||||
}
|
||||
t.Logf("lost closes=%d; settlement reads of own clean=%d; idle retry reads before any write=%d", observed.lost, observed.settled, observed.idleRetryReads)
|
||||
if err != nil {
|
||||
t.Fatalf("next page retained pre-publication reachability: %v", err)
|
||||
}
|
||||
if !present(t, st, reused) {
|
||||
t.Fatal("next page removed the re-referenced candidate")
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, st, n) {
|
||||
t.Fatalf("next-page continuation left orphan %s", n)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
type timedBatchFiler struct {
|
||||
Filer
|
||||
mu sync.Mutex
|
||||
id layout.VolumeID
|
||||
start time.Time
|
||||
maxHold time.Duration
|
||||
deletes int
|
||||
tagDelay time.Duration
|
||||
preparationHeld bool
|
||||
tagSeen map[string]bool
|
||||
}
|
||||
|
||||
func (f *timedBatchFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if f.tagDelay > 0 && strings.Contains(dir, "/pool/") {
|
||||
f.mu.Lock()
|
||||
if f.tagSeen == nil {
|
||||
f.tagSeen = map[string]bool{}
|
||||
}
|
||||
key := dir + "/" + name
|
||||
delay := !f.tagSeen[key]
|
||||
f.tagSeen[key] = true
|
||||
if delay {
|
||||
f.preparationHeld = f.preparationHeld || !f.start.IsZero()
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if delay {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(f.tagDelay):
|
||||
}
|
||||
}
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestMaintenanceSlowPreparationDoesNotHoldSession(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, _, _ := cleanFixture(t)
|
||||
observed := &timedBatchFiler{Filer: cat.f, id: ref.ID, tagDelay: 6 * time.Second}
|
||||
cat.f = observed
|
||||
started := time.Now()
|
||||
if _, _, err := cleanVia(ctx, cat, ref, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observed.preparationHeld || time.Since(started) < 12*time.Second || observed.maxHold > 5*time.Second || observed.deletes != 2 {
|
||||
t.Fatalf("elapsed=%v held during preparation=%v max hold=%v removed=%d", time.Since(started), observed.preparationHeld, observed.maxHold, observed.deletes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type missingBatchPreparationFiler struct {
|
||||
Filer
|
||||
id layout.VolumeID
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (f *missingBatchPreparationFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Name == layout.HeadName {
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActIdle {
|
||||
f.closed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *missingBatchPreparationFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if name == layout.HeadName && f.closed {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestMaintenanceBatchPreparationAbsentHeadRefuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
cat.f = &missingBatchPreparationFiler{Filer: cat.f, id: ref.ID}
|
||||
if _, _, err := cleanVia(ctx, cat, ref, cleanHolder); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("missing HEAD accepted for preparation: %v", err)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, st, n) {
|
||||
t.Fatal("absent HEAD permitted candidate removal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type preparationRaceFiler struct {
|
||||
Filer
|
||||
id layout.VolumeID
|
||||
cleanSeen, closed bool
|
||||
reads int
|
||||
armed atomic.Bool
|
||||
beforeBegin func()
|
||||
}
|
||||
|
||||
func (f *preparationRaceFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Name == layout.HeadName {
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActClean {
|
||||
f.cleanSeen = true
|
||||
}
|
||||
if h.Activity.Kind == layout.ActIdle && f.cleanSeen {
|
||||
f.closed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *preparationRaceFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if strings.Contains(dir, "/pool/") && strings.HasPrefix(name, "4-") {
|
||||
f.armed.Store(true)
|
||||
}
|
||||
if name == layout.HeadName && f.closed && f.armed.Load() {
|
||||
f.reads++
|
||||
// Candidate4 arms this at its tag read. Publish after preparation's
|
||||
// authoritative read, just before Begin observes the new generation.
|
||||
if f.reads == 2 && f.beforeBegin != nil {
|
||||
publish := f.beforeBegin
|
||||
f.beforeBegin = nil
|
||||
publish()
|
||||
}
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestMaintenanceBatchRefusesPublicationAfterPreparation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
data := bytes.Repeat([]byte{4}, 4096)
|
||||
needed := layout.NameChunk(4, data)
|
||||
if err := layout.EnsureObject(ctx, st, needed.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
published := false
|
||||
f := &preparationRaceFiler{Filer: cat.f, id: ref.ID}
|
||||
f.beforeBegin = func() {
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
prev := map[uint64]layout.Ref{1: {Owner: ref.Name, OwnerID: ref.ID, Chunk: live}}
|
||||
next := map[uint64]layout.Ref{1: prev[1], 4: {Owner: ref.Name, OwnerID: ref.ID, Chunk: needed}}
|
||||
commitImage(t, st, ref.Name, "after-preparation", prev, next, map[uint64][]byte{4: data}, 2, "later")
|
||||
published = true
|
||||
}
|
||||
cat.f = f
|
||||
if _, _, err := cleanVia(ctx, cat, ref, cleanHolder); !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("stale preparation was not refused: %v", err)
|
||||
}
|
||||
if !published || !present(t, st, needed) {
|
||||
t.Fatal("missed publication or removed its candidate")
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, st, n) {
|
||||
t.Fatalf("stale prepared batch applied effects before refusing: %s", n)
|
||||
}
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("refusal left activity: %+v %v", h.Activity, err)
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, cat, ref, cleanHolder); err != nil {
|
||||
t.Fatalf("fresh pass: %v", err)
|
||||
}
|
||||
if !present(t, st, needed) {
|
||||
t.Fatal("fresh pass removed the re-referenced candidate")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *timedBatchFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Name == layout.HeadName {
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActClean && f.start.IsZero() {
|
||||
f.start = time.Now()
|
||||
}
|
||||
if h.Activity.Kind != layout.ActClean && !f.start.IsZero() {
|
||||
f.maxHold = max(f.maxHold, time.Since(f.start))
|
||||
f.start = time.Time{}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *timedBatchFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if strings.Contains(dir, "/pool/") {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if err := f.Filer.DeleteEntry(ctx, dir, name, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.Contains(dir, "/pool/") {
|
||||
f.mu.Lock()
|
||||
f.deletes++
|
||||
f.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMaintenanceFiveSecondBatchLetsSnapshotDeleteFinish(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, _ := cleanFixture(t)
|
||||
// Existing orphan 2 plus 998 new candidates in shard0, and the existing
|
||||
// shard1 orphan: exactly 1000 slow removals; the live chunk stays intact.
|
||||
for i := uint64(4); i < 1002; i++ {
|
||||
data := bytes.Repeat([]byte{byte(i)}, 4096)
|
||||
n := layout.NameChunk(i, data)
|
||||
if err := layout.EnsureObject(ctx, st, n.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h, _, _ := st.ReadHead(ctx)
|
||||
h.Version = layout.HeadVersion1
|
||||
snap := h.Snapshots["s"]
|
||||
snap.Gen = h.Gen + 1
|
||||
h.Snapshots["s"] = snap
|
||||
if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
op, err := st.AdmitSnapshotDeleteOperation(ctx, "concurrent-delete", "s", SnapshotDeleteTarget(st, "s", 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
observed := &timedBatchFiler{Filer: cat.f, id: ref.ID}
|
||||
cat.f = observed
|
||||
deleteDone := make(chan error, 1)
|
||||
deleteCtx, deleteCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer deleteCancel()
|
||||
started := time.Now()
|
||||
var deletedAt time.Time
|
||||
go func() {
|
||||
// Ensure the first request meets the open slow batch.
|
||||
time.Sleep(time.Second)
|
||||
for {
|
||||
answer, err := cat.RunSnapshotDeleteOperation(deleteCtx, ref, op, nil)
|
||||
if err == nil && answer.State == "succeeded" {
|
||||
deletedAt = time.Now()
|
||||
deleteDone <- nil
|
||||
return
|
||||
}
|
||||
if err != nil && !errors.Is(err, layout.ErrBusy) && !errors.Is(err, layout.ErrPrecondition) {
|
||||
deleteDone <- err
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-deleteCtx.Done():
|
||||
deleteDone <- deleteCtx.Err()
|
||||
return
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
op, err = st.ReadSnapshotOperationHandle(deleteCtx, op.ID, op.Verb, op.Instance, op.Sequence)
|
||||
if err != nil {
|
||||
deleteDone <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
res, _, err := cleanVia(ctx, cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-deleteDone; err != nil {
|
||||
t.Fatalf("concurrent snapshot delete: %v; max session hold=%v", err, observed.maxHold)
|
||||
}
|
||||
t.Logf("max session hold=%v; concurrent delete completed at=%v; slow removals=%d", observed.maxHold, deletedAt.Sub(started), observed.deletes)
|
||||
if observed.maxHold > 5050*time.Millisecond || deletedAt.Sub(started) >= 30*time.Second || observed.deletes != 1000 || res.Removed != 1000 {
|
||||
// CleanResult has aggregate removals; all seeded slow deletions must
|
||||
// finish even when a timer cuts a short final page into more batches.
|
||||
t.Fatalf("hold=%v delete at=%v slow removals=%d result=%+v", observed.maxHold, deletedAt.Sub(started), observed.deletes, res)
|
||||
}
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
if !present(t, st, live) {
|
||||
t.Fatal("live chunk removed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An adversarial publisher wins every optimistic pool-page preparation, across
|
||||
// separate passes. Successful metadata pages before it must not erase that
|
||||
// same-page starvation history.
|
||||
type repeatedPreparationFiler struct {
|
||||
*timedBatchFiler
|
||||
armed atomic.Bool
|
||||
idleReads, publications int
|
||||
attackRevisits bool
|
||||
publish func()
|
||||
}
|
||||
|
||||
func (f *repeatedPreparationFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
f.mu.Lock()
|
||||
blocked := f.deletes == 0
|
||||
f.mu.Unlock()
|
||||
if blocked && (strings.Contains(dir, "/pool/") && strings.HasPrefix(name, "4-") || f.attackRevisits && strings.HasSuffix(dir, "/"+layout.RootDir)) {
|
||||
f.mu.Lock()
|
||||
outside := f.start.IsZero()
|
||||
f.mu.Unlock()
|
||||
if outside {
|
||||
f.armed.Store(true)
|
||||
}
|
||||
}
|
||||
if name == layout.HeadName && f.armed.Load() {
|
||||
e, err := f.Filer.LookupEntry(ctx, dir, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := DecodeLayoutHeadEntry(e, f.id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if h.Activity.Kind == layout.ActIdle {
|
||||
f.idleReads++
|
||||
if f.idleReads == 2 {
|
||||
f.armed.Store(false)
|
||||
f.publications++
|
||||
f.publish()
|
||||
}
|
||||
}
|
||||
}
|
||||
return f.timedBatchFiler.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestMaintenanceRepeatedPreparationPublicationFallsBackAfterThreeRefusals(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
data := bytes.Repeat([]byte{4}, 4096)
|
||||
needed := layout.NameChunk(4, data)
|
||||
if err := layout.EnsureObject(ctx, st, needed.Path(), data, "ended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &repeatedPreparationFiler{timedBatchFiler: &timedBatchFiler{Filer: cat.f, id: ref.ID}}
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
image := map[uint64]layout.Ref{1: {Owner: ref.Name, OwnerID: ref.ID, Chunk: live}}
|
||||
f.publish = func() {
|
||||
next := map[uint64]layout.Ref{1: image[1], 4: {Owner: ref.Name, OwnerID: ref.ID, Chunk: needed}}
|
||||
commitImage(t, st, ref.Name, "repeated-preparation", image, next, map[uint64][]byte{4: data}, uint64(f.publications+1), fmt.Sprintf("later-%d", f.publications))
|
||||
image = next
|
||||
}
|
||||
cat.f = f
|
||||
for attempt := 1; attempt <= 4; attempt++ {
|
||||
f.attackRevisits = attempt == 2 || attempt == 4
|
||||
f.armed.Store(false)
|
||||
f.idleReads = 0
|
||||
// Delay each preparation, including the fourth, to measure it in hold time.
|
||||
f.tagSeen = nil
|
||||
f.tagDelay = 2 * time.Second
|
||||
_, _, err := cleanVia(ctx, cat, ref, cleanHolder)
|
||||
if attempt <= 3 {
|
||||
cur := cat.cleaningCursor(ref)
|
||||
if cur.refusals != uint8(attempt) || cur.stuck.phase != 2 {
|
||||
t.Fatalf("attempt %d lost furthest pool history across revisit: count=%d stuck=%+v", attempt, cur.refusals, cur.stuck)
|
||||
}
|
||||
if !errors.Is(err, layout.ErrPrecondition) || f.deletes != 0 {
|
||||
t.Fatalf("attempt %d: want zero-effect preparation refusal, deletes=%d err=%v", attempt, f.deletes, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("fourth preparation starved instead of falling back: publications=%d err=%v", f.publications, err)
|
||||
}
|
||||
}
|
||||
if f.publications != 3 || f.deletes != len(orphans) || !f.preparationHeld || f.maxHold > 5*time.Second+50*time.Millisecond || f.maxHold < 2*time.Second {
|
||||
t.Fatalf("fallback witness: publications=%d deletes=%d preparationHeld=%v maxHold=%v", f.publications, f.deletes, f.preparationHeld, f.maxHold)
|
||||
}
|
||||
if !present(t, st, needed) {
|
||||
t.Fatal("fallback removed the re-referenced candidate")
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, st, n) {
|
||||
t.Fatalf("fallback left orphan %s", n)
|
||||
}
|
||||
}
|
||||
t.Logf("refusals=3 publications=%d preparation included in max hold=%v deletes=%d", f.publications, f.maxHold, f.deletes)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceFallbackPreparationSharesSessionCap(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
cat, ref, st, orphans := cleanFixture(t)
|
||||
cur := cat.cleaningCursor(ref)
|
||||
cur.refusals, cur.stuck = 3, cleanPosition{phase: 2}
|
||||
observed := &timedBatchFiler{Filer: cat.f, id: ref.ID, tagDelay: 6 * time.Second}
|
||||
cat.f = observed
|
||||
_, _, err := cleanVia(ctx, cat, ref, cleanHolder)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("over-budget preparation must stop before effects: %v", err)
|
||||
}
|
||||
if observed.deletes != 0 || !observed.preparationHeld || observed.maxHold > 5*time.Second+50*time.Millisecond || cur.refusals != 3 {
|
||||
t.Fatalf("preparation escaped session cap: hold=%v deletes=%d held=%v refusals=%d", observed.maxHold, observed.deletes, observed.preparationHeld, cur.refusals)
|
||||
}
|
||||
h, _, err := st.ReadHead(ctx)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("expired preparation left activity: %+v err=%v", h.Activity, err)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, st, n) {
|
||||
t.Fatalf("expired preparation removed candidate: %s", n)
|
||||
}
|
||||
}
|
||||
t.Logf("fallback read preparation stopped at session cap=%v; no effects", observed.maxHold)
|
||||
})
|
||||
}
|
||||
@@ -10,6 +10,11 @@ import (
|
||||
// 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) {
|
||||
done, err := c.acquirePublishers(ctx, v)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer done()
|
||||
s, r, err := c.open(v)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCleaningReportsProcessedObjects(t *testing.T) {
|
||||
c, v, st, orphans := cleanFixture(t)
|
||||
var mu sync.Mutex
|
||||
stages := map[uint64]bool{}
|
||||
ctx := layout.WithMaintenanceProgress(context.Background(), func(p layout.MaintenancePosition) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if p[0] != layout.MaintenanceSweep || p[2] == 0 || p[4] == 0 {
|
||||
t.Errorf("unscoped progress: %v", p)
|
||||
}
|
||||
stages[p[3]] = true
|
||||
})
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, st, n) {
|
||||
t.Fatal("orphan retained")
|
||||
}
|
||||
}
|
||||
for _, stage := range []uint64{1, 2, 3} {
|
||||
if !stages[stage] {
|
||||
t.Fatalf("missing completed stage %d: %v", stage, stages)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import (
|
||||
// pins it. "GAP" marks a reader that takes an absent HEAD for an empty
|
||||
// one; a change that treats an absent HEAD as unknown flips those probes.
|
||||
var headReaders = map[string]string{
|
||||
"core/frontend/chunkstore/clean_b.go RemoveUnreachableAll -> ReadHead": "absent HEAD refuses preparing a new batch without any effects (TestMaintenanceBatchPreparationAbsentHeadRefuses)",
|
||||
"core/frontend/chunkstore/clean_b.go endCleanBatch -> ReadHead": "absent HEAD does not settle an unknown batch close or permit re-entry (TestMaintenanceBatchUnknownCloseAbsentHeadRefuses)",
|
||||
"core/frontend/chunkstore/catalog_snapshot_delete_intent.go snapshotDeleteLogicalStep -> ReadHead": "absent HEAD refuses without unlink, pages or terminal receipt (TestSnapshotDeleteLogicalCommitAbsentHeadRefuses)",
|
||||
|
||||
"core/frontend/chunkstore/snapshot_operation_index.go readOperationIndex -> ReadHead": "missing HEAD gives an empty query only without INDEX; existing INDEX without HEAD refuses; deleting/deleted refuses before dead-incarnation lookup (TestSnapshotOperationDeleteFencesPausedPublications, TestSnapshotOperationCleanupRequiresDeletedHead)",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type cleanerBatchKey struct{}
|
||||
type cleanerBatchEndKey struct{}
|
||||
type cleanerBatch struct {
|
||||
held bool
|
||||
base Head
|
||||
execute func(context.Context, Head, func(context.Context) error) error
|
||||
}
|
||||
|
||||
// WithCleanerBatch prepares outside the exclusive activity. The executor must
|
||||
// begin at the prepared HEAD generation, or refuse without running effects.
|
||||
func WithCleanerBatch(ctx context.Context, base Head, execute func(context.Context, Head, func(context.Context) error) error) context.Context {
|
||||
return context.WithValue(ctx, cleanerBatchKey{}, cleanerBatch{base: base, execute: execute})
|
||||
}
|
||||
|
||||
// WithCleanBatchEnd is a control timer for the session, never a pass deadline.
|
||||
// It is inspected between completed candidate decisions, not used to cancel I/O.
|
||||
func WithCleanBatchEnd(ctx context.Context, end time.Time) context.Context {
|
||||
return context.WithValue(ctx, cleanerBatchEndKey{}, end)
|
||||
}
|
||||
|
||||
func hasCleanerBatch(ctx context.Context) bool {
|
||||
_, ok := ctx.Value(cleanerBatchKey{}).(cleanerBatch)
|
||||
return ok
|
||||
}
|
||||
|
||||
func runCleanerBatch(ctx context.Context, base Head, run func(context.Context) error) error {
|
||||
if batch, ok := ctx.Value(cleanerBatchKey{}).(cleanerBatch); ok {
|
||||
return batch.execute(ctx, base, run)
|
||||
}
|
||||
return run(ctx)
|
||||
}
|
||||
|
||||
func cleanBatchEnded(ctx context.Context) bool {
|
||||
end, ok := ctx.Value(cleanerBatchEndKey{}).(time.Time)
|
||||
return ok && !time.Now().Before(end)
|
||||
}
|
||||
|
||||
// WithHeldCleanerBatch prepares only after this pass has begun its activity.
|
||||
// Read-only preparation may have a deadline; the executor supplies the original
|
||||
// caller context to effects so the session timer never cancels a mutation.
|
||||
func WithHeldCleanerBatch(ctx context.Context, base Head, execute func(context.Context, Head, func(context.Context) error) error) context.Context {
|
||||
return context.WithValue(ctx, cleanerBatchKey{}, cleanerBatch{base: base, execute: execute, held: true})
|
||||
}
|
||||
@@ -224,6 +224,7 @@ func pendingDeleteIntent(h Head, expected *ListCursor) error {
|
||||
// over guest writes. Every object still passes the normal live-root and
|
||||
// conditional removal checks in Cleaner.removePlanned.
|
||||
func RunConsumeSnapshotDeleteIntent(ctx context.Context, st ListChainStore, r *Reader) (Head, error) {
|
||||
ctx = maintenanceReads(WithMaintenancePhase(ctx, MaintenanceIntent), 1)
|
||||
var after *ListCursor
|
||||
attempted := false
|
||||
h, err := runTransition(ctx, st, CauseListAdvance, func(h Head) (Head, bool, error) {
|
||||
|
||||
@@ -238,6 +238,9 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string {
|
||||
removals := func(n ast.Node) []string {
|
||||
var names []string
|
||||
ast.Inspect(n, func(n ast.Node) bool {
|
||||
if _, ok := n.(*ast.FuncLit); ok {
|
||||
return false // Its body is checked as a separate block below.
|
||||
}
|
||||
if c, ok := n.(*ast.CallExpr); ok {
|
||||
if sel, ok := c.Fun.(*ast.SelectorExpr); ok && (strings.HasPrefix(sel.Sel.Name, "Delete") || strings.HasPrefix(sel.Sel.Name, "Remove")) {
|
||||
names = append(names, sel.Sel.Name)
|
||||
@@ -338,6 +341,27 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string {
|
||||
return bad
|
||||
}
|
||||
|
||||
func TestRemoverGuardChecksBatchCallbackBodies(t *testing.T) {
|
||||
for _, guarded := range []bool{false, true} {
|
||||
gate := ""
|
||||
if guarded {
|
||||
gate = `if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil { return err }`
|
||||
}
|
||||
src := `package layout
|
||||
func (c *Cleaner) removePlanned() error {
|
||||
return runCleanerBatch(ctx, head, func(ctx C) error {
|
||||
` + gate + `
|
||||
if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil { return err }
|
||||
return nil
|
||||
})
|
||||
}`
|
||||
bad := removerOrderFindings(t, map[string]string{"remove.go": src})
|
||||
if guarded && len(bad) != 0 || !guarded && !strings.Contains(strings.Join(bad, "\n"), "without a mark gate immediately before it") {
|
||||
t.Fatalf("guarded=%v callback findings=%v", guarded, bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// deleteOrderFindings checks DeleteVolume's order in the sources: among its
|
||||
// top-level statements, the first use of each step comes after the
|
||||
// previous step's: Reserve, RunMarkDeleting, RunReleaseDependent,
|
||||
|
||||
@@ -736,6 +736,18 @@ func RunAbort(ctx context.Context, st HeadStore, me HolderID, session string, ca
|
||||
// changed it, written as cause. An absent HEAD is refused: no transition
|
||||
// creates one.
|
||||
func runTransition(ctx context.Context, st HeadStore, cause HeadWriteCause, t func(Head) (Head, bool, error)) (Head, error) {
|
||||
// Optional process-local scheduling covers the entire one-shot proposal,
|
||||
// including its HEAD read. Waiting only at CAS would stale its generation.
|
||||
// This hook supplies no authority and never retries or refreshes a proposal.
|
||||
if admission, ok := st.(interface {
|
||||
BeginHeadPublication(context.Context) (func(), error)
|
||||
}); ok {
|
||||
done, err := admission.BeginHeadPublication(ctx)
|
||||
if err != nil {
|
||||
return Head{}, err
|
||||
}
|
||||
defer done()
|
||||
}
|
||||
h, found, err := st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return Head{}, err
|
||||
|
||||
@@ -184,7 +184,10 @@ func TestHeadGenerationComparedOnlyByConditionalUpdate(t *testing.T) {
|
||||
// not raw filer HEAD generation. Pin both syntax and count: a new or removed
|
||||
// site forces review. No no-op-cut authority comparison is allowed here.
|
||||
allowed := map[string]int{
|
||||
"core/frontend/chunkstore/layout_verify.go VerifyLayout head.Gen != heads[p].Gen": 1, // read-only observation window; TestVerifyLayoutRequiresStableHeadForMissingAndOrphans
|
||||
"core/frontend/chunkstore/clean_b.go RemoveUnreachableAll fresh.Gen != closed.Gen": 1, // cache provenance; TestMaintenanceBatchDropsReachabilityAfterPublication
|
||||
"core/frontend/chunkstore/clean_b.go RemoveUnreachableAll opened.Gen != base.Gen+1": 1, // refuse stale preparation after begin; TestMaintenanceBatchDropsReachabilityAfterPublication
|
||||
"core/frontend/chunkstore/layout/remove.go removePlanned h.Gen != batch.base.Gen": 2, // close read/view race before preparing; TestMaintenanceBatchDropsReachabilityAfterPublication
|
||||
"core/frontend/chunkstore/layout_verify.go VerifyLayout head.Gen != heads[p].Gen": 1, // read-only observation window; TestVerifyLayoutRequiresStableHeadForMissingAndOrphans
|
||||
|
||||
"core/storage/chunk_head_belt.go confirmChunkHead got.Gen != want.Gen": 1, // publication confirmation
|
||||
"core/storage/chunk_layer.go captureLocked sc.headGen == l.head.Gen": 1, // staged image cache
|
||||
|
||||
@@ -67,6 +67,7 @@ func readListPage(ctx context.Context, r ListPageReader, volume VolumeID, c List
|
||||
if p.Kind != c.Kind || p.Producer != c.Producer || p.Generation != c.Generation || !sameTarget(p.Target, c.Target) {
|
||||
return ListPage{}, fmt.Errorf("%w: list continuation context", ErrIdentity)
|
||||
}
|
||||
reportMaintenanceRead(ctx)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
)
|
||||
|
||||
func TestListCursorGoldenBytes(t *testing.T) {
|
||||
@@ -483,3 +484,101 @@ func TestListWritesMatchExportedCensus(t *testing.T) {
|
||||
}
|
||||
check(CauseListAdvance, before, after)
|
||||
}
|
||||
|
||||
func TestMaintenanceListPreparationReportsOnlyAuthenticatedPages(t *testing.T) {
|
||||
s, c, p := chainFixture(t)
|
||||
if _, err := StageListPage(context.Background(), s, me, "s1", p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := 0
|
||||
ctx := maintenanceReads(WithMaintenanceProgress(context.Background(), func(MaintenancePosition) { count++ }), 2)
|
||||
if _, err := readListPage(ctx, s, p.VolumeID, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("completed page not reported: %d", count)
|
||||
}
|
||||
c.Producer = "foreign"
|
||||
if _, err := readListPage(ctx, s, p.VolumeID, c); !errors.Is(err, ErrIdentity) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatal("failed preparation earned progress")
|
||||
}
|
||||
}
|
||||
|
||||
type maintenanceOrderedTags struct {
|
||||
ObjectStore
|
||||
first string
|
||||
release <-chan struct{}
|
||||
secondDone chan struct{}
|
||||
failFirst bool
|
||||
}
|
||||
|
||||
func (s maintenanceOrderedTags) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) {
|
||||
if rel == s.first {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ObjectMeta{}, false, ctx.Err()
|
||||
case <-s.release:
|
||||
}
|
||||
if s.failFirst {
|
||||
return ObjectMeta{}, false, ErrPrecondition
|
||||
}
|
||||
} else {
|
||||
defer close(s.secondDone)
|
||||
}
|
||||
return s.ObjectStore.Stat(ctx, rel)
|
||||
}
|
||||
|
||||
func TestMaintenanceTagPositionCountsCompletedWorkOnly(t *testing.T) {
|
||||
for _, failed := range []bool{false, true} {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s, _, p := chainFixture(t)
|
||||
ref, err := StageListPage(context.Background(), s, me, "s1", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Entries = []string{RootName{Hash: Sum([]byte("other"))}.Path()}
|
||||
other, err := StageListPage(context.Background(), s, me, "s1", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, _ := ref.Path()
|
||||
release := make(chan struct{})
|
||||
second := make(chan struct{})
|
||||
obj := maintenanceOrderedTags{ObjectStore: s, first: first, release: release, secondDone: second, failFirst: failed}
|
||||
reports := make(chan MaintenancePosition, 4)
|
||||
ctx := WithMaintenanceProgress(context.Background(), func(p MaintenancePosition) { reports <- p })
|
||||
cleaner := NewCleaner(s, nil, obj, me, "not-open")
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); _, _ = cleaner.Page(ctx, ListDir, 0, []string{ref.Hash, other.Hash}) }()
|
||||
<-second
|
||||
synctest.Wait()
|
||||
select {
|
||||
case got := <-reports:
|
||||
if got[3] != 1 || got[4] != 1 {
|
||||
t.Errorf("completed later job not counted once: %v", got)
|
||||
}
|
||||
default:
|
||||
t.Error("pending earlier job hid completed work")
|
||||
}
|
||||
close(release)
|
||||
<-done
|
||||
if failed {
|
||||
if len(reports) != 0 {
|
||||
t.Fatal("failed job earned progress")
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case got := <-reports:
|
||||
if got[3] != 1 || got[4] != 2 {
|
||||
t.Fatalf("completed position=%v", got)
|
||||
}
|
||||
default:
|
||||
t.Fatal("completed job not reported")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type maintenanceProgressKey struct{}
|
||||
type maintenanceScopeKey struct{}
|
||||
type maintenanceReadKey struct{}
|
||||
|
||||
// MaintenancePosition is the finite pass's (phase, outer page, page, stage, position).
|
||||
// Positions are lexicographic, scheduling only, and never removal authority.
|
||||
type MaintenancePosition [5]uint64
|
||||
|
||||
const (
|
||||
MaintenanceRetention uint64 = 1
|
||||
MaintenanceIntent uint64 = 2
|
||||
MaintenanceSweep uint64 = 3
|
||||
)
|
||||
|
||||
func (p MaintenancePosition) After(old MaintenancePosition) bool {
|
||||
for i := range p {
|
||||
if p[i] != old[i] {
|
||||
return p[i] > old[i]
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// WithMaintenanceProgress observes strict advances; the observer retains only
|
||||
// its highest position. A failed request or retry of a position is not progress.
|
||||
func WithMaintenanceProgress(ctx context.Context, completed func(MaintenancePosition)) context.Context {
|
||||
return context.WithValue(ctx, maintenanceProgressKey{}, completed)
|
||||
}
|
||||
|
||||
func WithMaintenancePhase(ctx context.Context, phase uint64) context.Context {
|
||||
if !HasMaintenanceProgress(ctx) {
|
||||
return ctx
|
||||
}
|
||||
if p, ok := ctx.Value(maintenanceScopeKey{}).(MaintenancePosition); ok && p[0] == phase {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, maintenanceScopeKey{}, MaintenancePosition{phase})
|
||||
}
|
||||
|
||||
func maintenancePage(ctx context.Context, page uint64) context.Context {
|
||||
if !HasMaintenanceProgress(ctx) {
|
||||
return ctx
|
||||
}
|
||||
p, _ := ctx.Value(maintenanceScopeKey{}).(MaintenancePosition)
|
||||
p[2], p[3], p[4] = page, 0, 0
|
||||
return context.WithValue(ctx, maintenanceScopeKey{}, p)
|
||||
}
|
||||
|
||||
// ReportMaintenanceStep is called after work at a finite-list position completes.
|
||||
func ReportMaintenanceStep(ctx context.Context, stage, position uint64) {
|
||||
if f, ok := ctx.Value(maintenanceProgressKey{}).(func(MaintenancePosition)); ok && position != 0 {
|
||||
p, _ := ctx.Value(maintenanceScopeKey{}).(MaintenancePosition)
|
||||
p[3], p[4] = stage, position
|
||||
f(p)
|
||||
}
|
||||
}
|
||||
|
||||
// maintenanceReads numbers completed reads in one finite reachability walk.
|
||||
// It is reset for each page/replayed walk, never incremented on a request retry.
|
||||
func maintenanceReads(ctx context.Context, stage uint64) context.Context {
|
||||
if !HasMaintenanceProgress(ctx) {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, maintenanceReadKey{}, &maintenanceReadPosition{stage: stage})
|
||||
}
|
||||
|
||||
type maintenanceReadPosition struct {
|
||||
stage uint64
|
||||
done atomic.Uint64
|
||||
}
|
||||
|
||||
func reportMaintenanceRead(ctx context.Context) {
|
||||
if p, ok := ctx.Value(maintenanceReadKey{}).(*maintenanceReadPosition); ok {
|
||||
ReportMaintenanceStep(ctx, p.stage, p.done.Add(1))
|
||||
}
|
||||
}
|
||||
|
||||
func HasMaintenanceProgress(ctx context.Context) bool {
|
||||
_, ok := ctx.Value(maintenanceProgressKey{}).(func(MaintenancePosition))
|
||||
return ok
|
||||
}
|
||||
|
||||
// WithMaintenanceIntentPage scopes a successfully advancing persisted-intent
|
||||
// cursor in the finite chain. Request retries retain the same page number.
|
||||
func WithMaintenanceIntentPage(ctx context.Context, page uint64) context.Context {
|
||||
if !HasMaintenanceProgress(ctx) {
|
||||
return ctx
|
||||
}
|
||||
ctx = WithMaintenancePhase(ctx, MaintenanceIntent)
|
||||
return context.WithValue(ctx, maintenanceScopeKey{}, MaintenancePosition{MaintenanceIntent, page})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Reachability completes six distinct metadata reads before any removal step.
|
||||
// Each request is shorter than its bound; their finite walk exceeds W=1min.
|
||||
func TestMaintenanceReachabilityProgressesAcrossTheWindow(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
m := &memStore{obj: map[string][]byte{}}
|
||||
refs := map[uint64]string{}
|
||||
for i := uint64(0); i < 5; i++ {
|
||||
refs[i*ShardSize] = "live"
|
||||
}
|
||||
rn := putImage(t, m, "v", refs, nil)
|
||||
r, err := NewReader(vbase, VolumeDir("v", vid("v", 0)), func(ctx context.Context, p string) ([]byte, bool, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, false, ctx.Err()
|
||||
case <-time.After(15 * time.Second):
|
||||
}
|
||||
return m.fetch(ctx, p)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var positions []MaintenancePosition
|
||||
start := time.Now()
|
||||
last := start
|
||||
ctx := maintenanceReads(WithMaintenanceProgress(context.Background(), func(p MaintenancePosition) {
|
||||
if time.Since(last) != 15*time.Second {
|
||||
t.Errorf("completed read interval %v", time.Since(last))
|
||||
}
|
||||
last = time.Now()
|
||||
positions = append(positions, p)
|
||||
}), 2)
|
||||
if err := r.EachRef(ctx, rn, AllShards, func(uint64, Ref) bool { return true }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(positions) != 6 || time.Since(start) != 90*time.Second {
|
||||
t.Fatalf("reachability progress: reads=%d elapsed=%v", len(positions), time.Since(start))
|
||||
}
|
||||
for i, p := range positions {
|
||||
if p[3] != 2 || p[4] != uint64(i+1) {
|
||||
t.Fatalf("non-advancing read position: %v", positions)
|
||||
}
|
||||
}
|
||||
before := len(positions)
|
||||
if _, err := r.Open(ctx, RootName{Hash: Sum([]byte("missing"))}); !errors.Is(err, ErrMissing) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(positions) != before {
|
||||
t.Fatal("failed read earned progress")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -176,6 +176,7 @@ func (r *Reader) Open(ctx context.Context, rn RootName) (*Image, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: root %s: %v", ErrCorrupt, rn, err)
|
||||
}
|
||||
reportMaintenanceRead(ctx)
|
||||
return &Image{r: r, root: root}, nil
|
||||
}
|
||||
|
||||
@@ -197,6 +198,7 @@ func (img *Image) Segment(ctx context.Context, shard uint64) (seg Segment, ok bo
|
||||
if seg.Shard != shard {
|
||||
return Segment{}, false, fmt.Errorf("%w: segment %s holds shard %d", ErrCorrupt, n, seg.Shard)
|
||||
}
|
||||
reportMaintenanceRead(ctx)
|
||||
return seg, true, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Cleaner is one clean(session)'s removal plan. Tags are read before each
|
||||
@@ -15,6 +16,7 @@ type Cleaner struct {
|
||||
// intent is set only by the persisted delete-intent consumer. Ordinary
|
||||
// full-sweep cleaners retain their holder + clean-session authority.
|
||||
intent *ListCursor
|
||||
page uint64 // completed/attempted pages in this finite sweep; not request retries
|
||||
tagParallel int
|
||||
st HeadStore
|
||||
r *Reader
|
||||
@@ -33,11 +35,18 @@ func NewCleaner(st HeadStore, r *Reader, os ObjectStore, me HolderID, session st
|
||||
return &Cleaner{st: st, r: r, os: os, me: me, session: session, tagParallel: 32}
|
||||
}
|
||||
|
||||
// ResetReachability starts a newly entered clean batch. The finite page ordinal
|
||||
// remains scheduling state; every safety decision is rebuilt from fresh HEAD.
|
||||
func (c *Cleaner) ResetReachability() {
|
||||
c.roots, c.rootsRead, c.metadata, c.chunks = nil, false, nil, nil
|
||||
}
|
||||
|
||||
// RemovalResult advances through names examined (including live objects), not
|
||||
// merely deleted names. A failed candidate is left for the next pass to retry.
|
||||
type RemovalResult struct {
|
||||
Names []string
|
||||
After string
|
||||
More bool // control timer yielded before all supplied candidates were decided
|
||||
}
|
||||
|
||||
// ListRetirementSkipReason reports opaque work that this binary must preserve.
|
||||
@@ -92,7 +101,8 @@ func (c *Cleaner) Page(ctx context.Context, kind string, shard uint64, names []s
|
||||
}
|
||||
rels = append(rels, rel)
|
||||
}
|
||||
return c.removePlanned(ctx, rels, kind, shard)
|
||||
c.page++
|
||||
return c.removePlanned(maintenancePage(ctx, c.page), rels, kind, shard)
|
||||
}
|
||||
|
||||
// removePlanned is the single mark/delete writer for all content-named objects:
|
||||
@@ -111,6 +121,8 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string,
|
||||
// Bounded parallel tag reads finish before HEAD is read. Their original order
|
||||
// determines the first error, independent of completion order.
|
||||
var wg sync.WaitGroup
|
||||
var completed atomic.Uint64
|
||||
trackProgress := HasMaintenanceProgress(ctx)
|
||||
jobs := make(chan int)
|
||||
for range min(c.tagParallel, len(rels)) {
|
||||
wg.Add(1)
|
||||
@@ -118,6 +130,12 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string,
|
||||
defer wg.Done()
|
||||
for i := range jobs {
|
||||
tags[i].meta, tags[i].found, tags[i].err = c.os.Stat(ctx, rels[i])
|
||||
// Each finite-list job is dispatched once. Request retries occur
|
||||
// inside Stat; only its final successful return advances this
|
||||
// phase. A slow earlier job cannot hide later completed work.
|
||||
if trackProgress && tags[i].err == nil {
|
||||
ReportMaintenanceStep(ctx, 1, completed.Add(1))
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -146,7 +164,22 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string,
|
||||
if err := h.holderErr(c.me); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if h.Activity != (Activity{Kind: ActClean, Session: c.session}) {
|
||||
if hasCleanerBatch(ctx) {
|
||||
batch := ctx.Value(cleanerBatchKey{}).(cleanerBatch)
|
||||
if batch.held {
|
||||
if h.Activity != (Activity{Kind: ActClean, Session: c.session}) {
|
||||
return out, ErrNoSession
|
||||
}
|
||||
if h.Gen != batch.base.Gen {
|
||||
return out, ErrPrecondition
|
||||
}
|
||||
} else if h.Activity.Kind != ActIdle {
|
||||
return out, ErrBusy
|
||||
}
|
||||
if h.Gen != batch.base.Gen {
|
||||
c.ResetReachability()
|
||||
}
|
||||
} else if h.Activity != (Activity{Kind: ActClean, Session: c.session}) {
|
||||
return out, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, c.session)
|
||||
}
|
||||
}
|
||||
@@ -171,6 +204,7 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string,
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx = maintenanceReads(ctx, 2)
|
||||
live := map[string]bool{}
|
||||
if kind == ListDir {
|
||||
// Reserved producer chains are opaque to this binary. Do not retire
|
||||
@@ -223,39 +257,51 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string,
|
||||
}
|
||||
live = c.metadata
|
||||
}
|
||||
for i, rel := range rels {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
tag := tags[i]
|
||||
if !tag.found || live[rel] {
|
||||
report := func(index int) { ReportMaintenanceStep(ctx, 3, uint64(index+1)) }
|
||||
err = runCleanerBatch(ctx, h, func(ctx context.Context) error {
|
||||
for i, rel := range rels {
|
||||
if cleanBatchEnded(ctx) {
|
||||
out.More = true
|
||||
return nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
tag := tags[i]
|
||||
if !tag.found || live[rel] {
|
||||
out.After = rel
|
||||
report(i)
|
||||
continue
|
||||
}
|
||||
if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
if c.intent != nil {
|
||||
return err
|
||||
}
|
||||
out.After = rel
|
||||
report(i)
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("layout: mark %s: %w", rel, err)
|
||||
}
|
||||
if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
if c.intent != nil {
|
||||
return err
|
||||
}
|
||||
out.After = rel
|
||||
report(i)
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("layout: delete %s: %w", rel, err)
|
||||
}
|
||||
out.Names = append(out.Names, rel)
|
||||
out.After = rel
|
||||
continue
|
||||
report(i)
|
||||
}
|
||||
if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
if c.intent != nil {
|
||||
return out, err
|
||||
}
|
||||
out.After = rel
|
||||
continue
|
||||
}
|
||||
return out, fmt.Errorf("layout: mark %s: %w", rel, err)
|
||||
}
|
||||
if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
if c.intent != nil {
|
||||
return out, err
|
||||
}
|
||||
out.After = rel
|
||||
continue
|
||||
}
|
||||
return out, fmt.Errorf("layout: delete %s: %w", rel, err)
|
||||
}
|
||||
out.Names = append(out.Names, rel)
|
||||
out.After = rel
|
||||
}
|
||||
return out, nil
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RemoveUnreachable is the chunk-only compatibility boundary. A full pass uses
|
||||
|
||||
@@ -35,10 +35,11 @@ type sessionStore interface {
|
||||
}
|
||||
|
||||
type LayoutRemote struct {
|
||||
st sessionStore
|
||||
r *layout.Reader
|
||||
vol VolumeRef
|
||||
me layout.HolderID
|
||||
admission *cleanAdmission
|
||||
st sessionStore
|
||||
r *layout.Reader
|
||||
vol VolumeRef
|
||||
me layout.HolderID
|
||||
|
||||
// headV11: commits write a v1.1 HEAD (SetHeadFormat, at attach), at
|
||||
// the format level headLevel (the HEAD write guard's input);
|
||||
@@ -158,7 +159,7 @@ func NewLayoutRemote(cat *BCatalog, v VolumeRef, me layout.HolderID) (*LayoutRem
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &LayoutRemote{st: st, r: r, vol: v, me: me}, nil
|
||||
return &LayoutRemote{st: st, r: r, vol: v, me: me, admission: &cat.cleaningCursor(v).admission}, nil
|
||||
}
|
||||
|
||||
// SetSnapshot names the snapshot the next commit at or past position from
|
||||
@@ -237,9 +238,18 @@ func (l *LayoutRemote) openSessionLocked(ctx context.Context) error {
|
||||
// beginSessionLocked opens a new session (no session is open) and returns
|
||||
// the HEAD its begin wrote.
|
||||
func (l *LayoutRemote) beginSessionLocked(ctx context.Context) (layout.Head, error) {
|
||||
// Preserve own-cleaner cancellation/join before waiting on another batch.
|
||||
// Its cancellation prevents that pass from re-entering while we join it.
|
||||
if err := l.stopCleaningLocked(ctx); err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
if l.admission != nil {
|
||||
done, err := l.admission.publisher(ctx)
|
||||
if err != nil {
|
||||
return layout.Head{}, layoutRemoteErr(err)
|
||||
}
|
||||
defer done()
|
||||
}
|
||||
if _, err := l.rollBackLocked(ctx); err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
@@ -1311,15 +1321,42 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context,
|
||||
|
||||
// Resume only the dedicated delete intent. A generic list is consumed by
|
||||
// its own protocol; membership alone must not grant delete authority.
|
||||
var intentPage uint64
|
||||
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)
|
||||
intentPage++
|
||||
// Intent consumption publishes a cursor; it is publisher interest,
|
||||
// not a clean activity, and never nests a clean-batch admission.
|
||||
var releaseIntent func()
|
||||
if l.admission != nil {
|
||||
releaseIntent, err = l.admission.publisher(cctx)
|
||||
if err != nil {
|
||||
return layoutRemoteErr(err)
|
||||
}
|
||||
}
|
||||
h, err = layout.RunConsumeSnapshotDeleteIntent(layout.WithMaintenanceIntentPage(cctx, intentPage), l.st, l.r)
|
||||
if releaseIntent != nil {
|
||||
releaseIntent()
|
||||
}
|
||||
if err != nil {
|
||||
return layoutRemoteErr(err)
|
||||
}
|
||||
}
|
||||
// Acquire outside l.mu: a cut may need that mutex to cancel/join us.
|
||||
// The catalog releases this lease at its initial durable close, before
|
||||
// acquiring any per-page lease; defer covers non-catalog/error callbacks.
|
||||
if l.admission != nil {
|
||||
release, err := l.admission.batch(cctx)
|
||||
if err != nil {
|
||||
return layoutRemoteErr(err)
|
||||
}
|
||||
initial := &cleanAdmissionLease{done: release, gate: l.admission}
|
||||
defer initial.release()
|
||||
cctx = context.WithValue(cctx, initialCleanAdmissionKey{}, initial)
|
||||
cctx = context.WithValue(cctx, heldCleanAdmissionKey{}, initial)
|
||||
}
|
||||
bh, err := layout.RunBeginClean(cctx, l.st, l.me, c)
|
||||
if err != nil {
|
||||
return layoutRemoteErr(err)
|
||||
|
||||
@@ -3,6 +3,7 @@ package chunkstore
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -97,3 +98,27 @@ func TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins(t *testing.T) {
|
||||
t.Fatalf("cancelled work lost its continuation: head=%+v err=%v deletes=%v", h, err, cost.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceIntentCursorAdvancesAcrossPages(t *testing.T) {
|
||||
cat, ref, cost := largeIntentCatalog(t, 1024) // a real two-page persisted intent
|
||||
remote, err := NewLayoutRemote(cat, ref, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
pages := map[uint64]bool{}
|
||||
ctx := layout.WithMaintenanceProgress(context.Background(), func(p layout.MaintenancePosition) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if p[0] != layout.MaintenanceIntent || p[1] == 0 {
|
||||
t.Errorf("intent lost finite cursor scope: %v", p)
|
||||
}
|
||||
pages[p[1]] = true
|
||||
})
|
||||
if err := remote.Clean(ctx, func(context.Context, layout.HolderID, string) error { return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pages[1] || !pages[2] || len(pages) != 2 || len(cost.deletes) != 4 {
|
||||
t.Fatalf("intent progress pages=%v effects=%v", pages, cost.deletes)
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,12 @@ var ErrLegacyStore = errors.New("chunkstore: legacy store format; recreate the v
|
||||
// Objects carry their immutable bytes as file chunks; metadata updates preserve
|
||||
// those chunks, and deletion delegates their reclamation to the filer.
|
||||
type LayoutStore struct {
|
||||
headWrites *headWriteCounters
|
||||
f Filer
|
||||
b Blobs
|
||||
root string
|
||||
id layout.VolumeID
|
||||
publicationAdmission *cleanAdmission // only catalog publishing-step views
|
||||
headWrites *headWriteCounters
|
||||
f Filer
|
||||
b Blobs
|
||||
root string
|
||||
id layout.VolumeID
|
||||
}
|
||||
|
||||
func NewLayoutStore(f Filer, b Blobs, root string, id layout.VolumeID) (*LayoutStore, error) {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maintenanceRequestTimeout bounds a single metadata or blob operation,
|
||||
// independent of the pass's completed-object inactivity window.
|
||||
const maintenanceRequestTimeout = 30 * time.Second
|
||||
|
||||
// maintenanceCall retries only read-only requests; mutations must preserve an
|
||||
// unanswered request as unknown for their existing caller settlement.
|
||||
func maintenanceCall[T any](ctx context.Context, call func(context.Context) (T, error)) (T, error) {
|
||||
if !layout.HasMaintenanceProgress(ctx) {
|
||||
return call(ctx)
|
||||
}
|
||||
for {
|
||||
request, cancel := context.WithTimeout(ctx, maintenanceRequestTimeout)
|
||||
value, err := call(request)
|
||||
cancel()
|
||||
if err == nil || ctx.Err() != nil || !(errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded) {
|
||||
return value, err
|
||||
}
|
||||
// A failed read is not progress. Repeat the same read-only position;
|
||||
// only its caller can report a completed finite-work step.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
var zero T
|
||||
return zero, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
func maintenanceError(ctx context.Context, call func(context.Context) error) error {
|
||||
_, err := maintenanceMutation(ctx, func(ctx context.Context) (struct{}, error) { return struct{}{}, call(ctx) })
|
||||
return err
|
||||
}
|
||||
|
||||
// maintenanceMutation bounds one invocation but never retries it. A timeout
|
||||
// may mean applied-without-reply; retrying here could turn it into EXISTS or a
|
||||
// failed precondition and defeat the caller's unknown-outcome settlement.
|
||||
func maintenanceMutation[T any](ctx context.Context, call func(context.Context) (T, error)) (T, error) {
|
||||
if !layout.HasMaintenanceProgress(ctx) {
|
||||
return call(ctx)
|
||||
}
|
||||
request, cancel := context.WithTimeout(ctx, maintenanceRequestTimeout)
|
||||
defer cancel()
|
||||
return call(request)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"path"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
type maintenanceDeadlineClient struct {
|
||||
filerpb.SeaweedFilerClient
|
||||
calls int
|
||||
deadlines []time.Duration
|
||||
}
|
||||
|
||||
func (c *maintenanceDeadlineClient) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filerpb.LookupDirectoryEntryResponse, error) {
|
||||
c.calls++
|
||||
dl, ok := ctx.Deadline()
|
||||
if ok {
|
||||
c.deadlines = append(c.deadlines, time.Until(dl))
|
||||
}
|
||||
if c.calls < 3 {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return &filerpb.LookupDirectoryEntryResponse{Entry: &filerpb.Entry{Name: r.Name}}, nil
|
||||
}
|
||||
func TestMaintenanceLookupRetriesItsOwnDeadlineWithoutProgress(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
progress := 0
|
||||
ctx = layout.WithMaintenanceProgress(ctx, func(layout.MaintenancePosition) { progress++ })
|
||||
client := &maintenanceDeadlineClient{}
|
||||
sw := &SWFS{fc: client}
|
||||
_, err := sw.LookupEntry(ctx, "/v/pool/0", "chunk")
|
||||
if err != nil || client.calls != 3 {
|
||||
t.Fatalf("request did not retry independently of the pass: calls=%d err=%v", client.calls, err)
|
||||
}
|
||||
for _, d := range client.deadlines {
|
||||
if d != 30*time.Second {
|
||||
t.Fatalf("per-call deadline=%v; want 30s", d)
|
||||
}
|
||||
}
|
||||
if progress != 0 {
|
||||
t.Fatal("request retries renewed object progress")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOrdinaryLookupKeepsItsCallerDeadline(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
client := &maintenanceDeadlineClient{calls: 2}
|
||||
sw := &SWFS{fc: client}
|
||||
if _, err := sw.LookupEntry(ctx, "/v/pool/0", "chunk"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(client.deadlines) != 1 || client.deadlines[0] != 3*time.Minute {
|
||||
t.Fatalf("non-maintenance request changed: %v", client.deadlines)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The first exclusive create lands, but its reply is lost. A second call would
|
||||
// answer EXISTS; that must not prove the first call's fid was unused.
|
||||
type maintenanceLostCreateClient struct {
|
||||
filerpb.SeaweedFilerClient
|
||||
f Filer
|
||||
calls int
|
||||
deadline time.Duration
|
||||
}
|
||||
|
||||
func (c *maintenanceLostCreateClient) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest, _ ...grpc.CallOption) (*filerpb.CreateEntryResponse, error) {
|
||||
c.calls++
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
c.deadline = time.Until(dl)
|
||||
}
|
||||
if err := c.f.CreateEntry(ctx, r.Directory, r.Entry, r.OExcl); err != nil {
|
||||
if errors.Is(err, ErrExists) {
|
||||
return &filerpb.CreateEntryResponse{ErrorCode: filerpb.FilerError_ENTRY_ALREADY_EXISTS}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
<-ctx.Done()
|
||||
return nil, status.Error(codes.DeadlineExceeded, "applied, reply lost")
|
||||
}
|
||||
|
||||
type maintenanceCreateFiler struct {
|
||||
Filer
|
||||
sw *SWFS
|
||||
}
|
||||
|
||||
func (f maintenanceCreateFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error {
|
||||
return f.sw.CreateEntry(ctx, dir, e, exclusive)
|
||||
}
|
||||
func TestMaintenanceUnknownCreateKeepsLinkedUploadAndSettles(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s, f, base := layoutStoreFixture(t)
|
||||
blobs := &layoutCleanupBlobs{fakeBlobs: base}
|
||||
s.b = blobs
|
||||
client := &maintenanceLostCreateClient{f: f}
|
||||
s.f = maintenanceCreateFiler{Filer: f, sw: &SWFS{fc: client}}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
ctx = layout.WithMaintenanceProgress(ctx, func(layout.MaintenancePosition) { t.Error("mutation attempt earned progress") })
|
||||
raw := []byte("keep the applied exclusive create")
|
||||
n := layout.NameChunk(3, raw)
|
||||
err := s.Create(ctx, n.Path(), raw, "writer")
|
||||
if len(blobs.deleted) != 0 {
|
||||
t.Fatalf("linked fid reclaimed: %v", blobs.deleted)
|
||||
}
|
||||
if status.Code(err) != codes.DeadlineExceeded || errors.Is(err, layout.ErrExists) || client.calls != 1 || client.deadline != 30*time.Second {
|
||||
t.Fatalf("unknown create changed outcome: err=%v calls=%d deadline=%v", err, client.calls, client.deadline)
|
||||
}
|
||||
got, found, err := s.Fetch(ctx, path.Join(s.root, n.Path()))
|
||||
if err != nil || !found || !bytes.Equal(got, raw) {
|
||||
t.Fatalf("linked data lost: %q %v %v", got, found, err)
|
||||
}
|
||||
if err := layout.EnsureObject(ctx, s, n.Path(), raw, "writer"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
puts, _, stored := blobs.counts()
|
||||
if puts != 1 || stored != 1 || client.calls != 1 {
|
||||
t.Fatalf("settlement repeated mutation: puts=%d stored=%d calls=%d", puts, stored, client.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type maintenanceLostAssignClient struct {
|
||||
filerpb.SeaweedFilerClient
|
||||
calls int
|
||||
}
|
||||
|
||||
func (c *maintenanceLostAssignClient) AssignVolume(ctx context.Context, _ *filerpb.AssignVolumeRequest, _ ...grpc.CallOption) (*filerpb.AssignVolumeResponse, error) {
|
||||
c.calls++
|
||||
<-ctx.Done()
|
||||
return nil, status.Error(codes.DeadlineExceeded, "assignment applied, reply lost")
|
||||
}
|
||||
func TestMaintenanceBlobPutDoesNotRepeatUnknownAssignment(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
ctx = layout.WithMaintenanceProgress(ctx, func(layout.MaintenancePosition) { t.Error("unknown assignment is not progress") })
|
||||
client := &maintenanceLostAssignClient{}
|
||||
sw := &SWFS{fc: client}
|
||||
start := time.Now()
|
||||
_, err := sw.Put(ctx, []byte("payload"))
|
||||
if status.Code(err) != codes.DeadlineExceeded || client.calls != 1 || time.Since(start) != 30*time.Second {
|
||||
t.Fatalf("assignment repeated: calls=%d elapsed=%v err=%v", client.calls, time.Since(start), err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -132,22 +132,35 @@ func (c *BCatalog) Retain(ctx context.Context, v VolumeRef, now time.Time, dryRu
|
||||
snaps = append(snaps, retain.Snapshot{Name: n, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresNs: sn.Meta.ExpiresNs, Labels: sn.Meta.Labels})
|
||||
}
|
||||
res := RetainResult{Policy: p, Decisions: retain.Plan(p, snaps, now), Deleted: []string{}, DryRun: dryRun}
|
||||
for _, d := range res.Decisions {
|
||||
ctx = layout.WithMaintenancePhase(ctx, layout.MaintenanceRetention)
|
||||
for i, d := range res.Decisions {
|
||||
report := func() {
|
||||
layout.ReportMaintenanceStep(ctx, 1, uint64(i+1))
|
||||
}
|
||||
if d.Keep {
|
||||
report()
|
||||
continue
|
||||
}
|
||||
if dryRun {
|
||||
res.Deleted = append(res.Deleted, d.Name)
|
||||
continue
|
||||
}
|
||||
if _, err := layout.RunRetireSnapshot(ctx, s, d.Name, now.UnixNano()); err != nil {
|
||||
done, err := c.acquirePublishers(ctx, v)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
_, err = layout.RunRetireSnapshot(ctx, s, d.Name, now.UnixNano())
|
||||
done()
|
||||
if err != nil {
|
||||
if errors.Is(err, layout.ErrPinned) || errors.Is(err, layout.ErrHasDependents) {
|
||||
res.Refused = append(res.Refused, d.Name)
|
||||
report()
|
||||
continue
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
res.Deleted = append(res.Deleted, d.Name)
|
||||
report()
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -111,93 +111,101 @@ func (c *SWFS) Close() error {
|
||||
|
||||
// LookupEntry implements Filer.
|
||||
func (c *SWFS) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
resp, err := c.fc.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
|
||||
if err != nil {
|
||||
if st, ok := status.FromError(err); ok {
|
||||
if st.Code() == codes.NotFound ||
|
||||
(st.Code() == codes.Unknown && strings.Contains(st.Message(), filerNotFoundText)) {
|
||||
return nil, ErrNotFound
|
||||
return maintenanceCall(ctx, func(ctx context.Context) (*filerpb.Entry, error) {
|
||||
resp, err := c.fc.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
|
||||
if err != nil {
|
||||
if st, ok := status.FromError(err); ok {
|
||||
if st.Code() == codes.NotFound ||
|
||||
(st.Code() == codes.Unknown && strings.Contains(st.Message(), filerNotFoundText)) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: lookup %s/%s: %w", dir, name, err)
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: lookup %s/%s: %w", dir, name, err)
|
||||
}
|
||||
if resp.GetEntry() == nil {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return resp.Entry, nil
|
||||
if resp.GetEntry() == nil {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return resp.Entry, nil
|
||||
})
|
||||
}
|
||||
|
||||
// CreateEntry implements Filer. A failed o_excl or condition is reported by
|
||||
// the filer in CreateEntryResponse.ErrorCode with a nil gRPC error.
|
||||
func (c *SWFS) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
resp, err := c.fc.CreateEntry(ctx, &filerpb.CreateEntryRequest{Directory: dir, Entry: e, OExcl: oExcl})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return fmt.Errorf("%w: create %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
return maintenanceError(ctx, func(ctx context.Context) error {
|
||||
resp, err := c.fc.CreateEntry(ctx, &filerpb.CreateEntryRequest{Directory: dir, Entry: e, OExcl: oExcl})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return fmt.Errorf("%w: create %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
}
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %w", dir, e.GetName(), err)
|
||||
}
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %w", dir, e.GetName(), err)
|
||||
}
|
||||
switch resp.GetErrorCode() {
|
||||
case filerpb.FilerError_OK:
|
||||
if resp.GetError() != "" {
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s", dir, e.GetName(), resp.GetError())
|
||||
switch resp.GetErrorCode() {
|
||||
case filerpb.FilerError_OK:
|
||||
if resp.GetError() != "" {
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s", dir, e.GetName(), resp.GetError())
|
||||
}
|
||||
return nil
|
||||
case filerpb.FilerError_ENTRY_ALREADY_EXISTS:
|
||||
return fmt.Errorf("%w: %s/%s", ErrExists, dir, e.GetName())
|
||||
case filerpb.FilerError_PRECONDITION_FAILED:
|
||||
return fmt.Errorf("%w: create %s/%s", ErrPrecondition, dir, e.GetName())
|
||||
default:
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s (%s)", dir, e.GetName(), resp.GetError(), resp.GetErrorCode())
|
||||
}
|
||||
return nil
|
||||
case filerpb.FilerError_ENTRY_ALREADY_EXISTS:
|
||||
return fmt.Errorf("%w: %s/%s", ErrExists, dir, e.GetName())
|
||||
case filerpb.FilerError_PRECONDITION_FAILED:
|
||||
return fmt.Errorf("%w: create %s/%s", ErrPrecondition, dir, e.GetName())
|
||||
default:
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s (%s)", dir, e.GetName(), resp.GetError(), resp.GetErrorCode())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateEntry implements Filer. A failed expected_extended comes back as gRPC
|
||||
// FailedPrecondition. Any other error is ambiguous (the write may or may not
|
||||
// have applied) and is returned unwrapped from the sentinels.
|
||||
func (c *SWFS) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
return fmt.Errorf("%w: update %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
case codes.NotFound:
|
||||
return fmt.Errorf("%w: update %s/%s", ErrNotFound, dir, e.GetName())
|
||||
}
|
||||
return fmt.Errorf("chunkstore: update %s/%s: %w", dir, e.GetName(), err)
|
||||
return maintenanceError(ctx, func(ctx context.Context) error {
|
||||
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
return fmt.Errorf("%w: update %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
case codes.NotFound:
|
||||
return fmt.Errorf("%w: update %s/%s", ErrNotFound, dir, e.GetName())
|
||||
}
|
||||
return fmt.Errorf("chunkstore: update %s/%s: %w", dir, e.GetName(), err)
|
||||
})
|
||||
}
|
||||
|
||||
// ListEntries implements Filer: one ListEntries stream of at most limit
|
||||
// entries. The filer's not-found styles (gRPC NotFound, or its raw sentinel
|
||||
// crossing as Unknown) mean an empty listing; any other error fails it.
|
||||
func (c *SWFS) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
|
||||
stream, err := c.fc.ListEntries(ctx, &filerpb.ListEntriesRequest{
|
||||
Directory: dir, Prefix: prefix, StartFromFileName: startAfter, InclusiveStartFrom: false, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: list %s: %w", dir, err)
|
||||
}
|
||||
var out []*filerpb.Entry
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return out, nil
|
||||
}
|
||||
return maintenanceCall(ctx, func(ctx context.Context) ([]*filerpb.Entry, error) {
|
||||
stream, err := c.fc.ListEntries(ctx, &filerpb.ListEntriesRequest{
|
||||
Directory: dir, Prefix: prefix, StartFromFileName: startAfter, InclusiveStartFrom: false, Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) && len(out) == 0 {
|
||||
if isFilerNotFound(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: list %s: %w", dir, err)
|
||||
}
|
||||
if resp.GetEntry() != nil {
|
||||
out = append(out, resp.Entry)
|
||||
var out []*filerpb.Entry
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return out, nil
|
||||
}
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) && len(out) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: list %s: %w", dir, err)
|
||||
}
|
||||
if resp.GetEntry() != nil {
|
||||
out = append(out, resp.Entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteEntry implements Filer. The filer reclaims the file's chunks; the
|
||||
@@ -206,19 +214,21 @@ func (c *SWFS) ListEntries(ctx context.Context, dir, prefix, startAfter string,
|
||||
// FailedPrecondition; other failures are a gRPC error or the response's
|
||||
// Error string, and are returned unwrapped from the sentinels.
|
||||
func (c *SWFS) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
resp, err := c.fc.DeleteEntry(ctx, &filerpb.DeleteEntryRequest{
|
||||
Directory: dir, Name: name, IsDeleteData: true, IsRecursive: false, ExpectedExtended: expected,
|
||||
})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return fmt.Errorf("%w: delete %s/%s: %v", ErrPrecondition, dir, name, err)
|
||||
return maintenanceError(ctx, func(ctx context.Context) error {
|
||||
resp, err := c.fc.DeleteEntry(ctx, &filerpb.DeleteEntryRequest{
|
||||
Directory: dir, Name: name, IsDeleteData: true, IsRecursive: false, ExpectedExtended: expected,
|
||||
})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return fmt.Errorf("%w: delete %s/%s: %v", ErrPrecondition, dir, name, err)
|
||||
}
|
||||
return fmt.Errorf("chunkstore: delete %s/%s: %w", dir, name, err)
|
||||
}
|
||||
return fmt.Errorf("chunkstore: delete %s/%s: %w", dir, name, err)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
return fmt.Errorf("chunkstore: delete %s/%s: %s", dir, name, resp.GetError())
|
||||
}
|
||||
return nil
|
||||
if resp.GetError() != "" {
|
||||
return fmt.Errorf("chunkstore: delete %s/%s: %s", dir, name, resp.GetError())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func isFilerNotFound(err error) bool {
|
||||
@@ -246,26 +256,28 @@ func assignErr(prefix string, err error) error {
|
||||
// auto-compress only fires for types it is sure about; octet-stream is
|
||||
// cleared to "" first, storage/needle/needle_parse_upload.go:116-119).
|
||||
func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
|
||||
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Collection: c.cfg.Collection,
|
||||
Replication: c.cfg.Replication,
|
||||
Path: c.cfg.AssignPath,
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
return maintenanceMutation(ctx, func(ctx context.Context) (string, error) {
|
||||
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Collection: c.cfg.Collection,
|
||||
Replication: c.cfg.Replication,
|
||||
Path: c.cfg.AssignPath,
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
})
|
||||
if err != nil {
|
||||
return "", assignErr("chunkstore: assign", err)
|
||||
}
|
||||
if ar.GetError() != "" {
|
||||
return "", assignErr("chunkstore: assign", errors.New(ar.GetError()))
|
||||
}
|
||||
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
|
||||
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
|
||||
}
|
||||
if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ar.FileId, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", assignErr("chunkstore: assign", err)
|
||||
}
|
||||
if ar.GetError() != "" {
|
||||
return "", assignErr("chunkstore: assign", errors.New(ar.GetError()))
|
||||
}
|
||||
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
|
||||
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
|
||||
}
|
||||
if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ar.FileId, nil
|
||||
}
|
||||
|
||||
// Get implements Blobs: resolve the fid's volume through the filer, then GET
|
||||
@@ -274,36 +286,38 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
|
||||
// answers 404: cached locations can be stale after a volume moves, so their
|
||||
// 404s are followed by one fresh lookup.
|
||||
func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) {
|
||||
vid, _, ok := strings.Cut(fid, ",")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("chunkstore: bad fid %q", fid)
|
||||
}
|
||||
urls, cached, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, allNotFound, lastErr := c.getFromAll(ctx, urls, fid)
|
||||
if lastErr == nil {
|
||||
return b, nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.vidCache, vid)
|
||||
c.mu.Unlock()
|
||||
if allNotFound && cached {
|
||||
if urls, _, err = c.lookupVolume(ctx, vid); err != nil {
|
||||
return maintenanceCall(ctx, func(ctx context.Context) ([]byte, error) {
|
||||
vid, _, ok := strings.Cut(fid, ",")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("chunkstore: bad fid %q", fid)
|
||||
}
|
||||
urls, cached, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b, allNotFound, lastErr = c.getFromAll(ctx, urls, fid); lastErr == nil {
|
||||
b, allNotFound, lastErr := c.getFromAll(ctx, urls, fid)
|
||||
if lastErr == nil {
|
||||
return b, nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.vidCache, vid)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
if allNotFound {
|
||||
lastErr = &blobNotFoundError{lastErr}
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr)
|
||||
if allNotFound && cached {
|
||||
if urls, _, err = c.lookupVolume(ctx, vid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b, allNotFound, lastErr = c.getFromAll(ctx, urls, fid); lastErr == nil {
|
||||
return b, nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.vidCache, vid)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
if allNotFound {
|
||||
lastErr = &blobNotFoundError{lastErr}
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr)
|
||||
})
|
||||
}
|
||||
|
||||
// getFromAll tries each location in turn. On failure lastErr is the last
|
||||
@@ -400,32 +414,34 @@ var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected")
|
||||
// and retries later; no response body is used to infer success.
|
||||
// SeaweedFS writeDeleteResult returns 202 after ReplicatedDelete completes.
|
||||
func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
|
||||
vid, needle, ok := strings.Cut(fid, ",")
|
||||
if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") {
|
||||
return fmt.Errorf("chunkstore: bad deletion fid %q", fid)
|
||||
}
|
||||
urls, _, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, host := range urls {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, "http://"+host+"/"+fid, nil)
|
||||
return maintenanceError(ctx, func(ctx context.Context) error {
|
||||
vid, needle, ok := strings.Cut(fid, ",")
|
||||
if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") {
|
||||
return fmt.Errorf("chunkstore: bad deletion fid %q", fid)
|
||||
}
|
||||
urls, _, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
for _, host := range urls {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, "http://"+host+"/"+fid, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Drain before close so the connection is reused.
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusBadRequest {
|
||||
return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
|
||||
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
// Drain before close so the connection is reused.
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusBadRequest {
|
||||
return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
|
||||
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// ErrMaintenanceNoProgress is a pass that exhausted its inactivity window.
|
||||
// Cancellation still joins the callback before the next pass can start.
|
||||
var ErrMaintenanceNoProgress = errors.New("durable: maintenance no_progress")
|
||||
|
||||
// maintenancePass has no total deadline. Only strict advancement of the finite
|
||||
// pass cursor renews the window. Its progress state is constant-sized.
|
||||
func maintenancePass(ctx context.Context, layer storage.ChunkLayer, current func() bool, window time.Duration, fn func(context.Context) error) error {
|
||||
passCtx, cancel := context.WithCancelCause(ctx)
|
||||
defer cancel(nil)
|
||||
var mu sync.Mutex
|
||||
last := time.Now()
|
||||
var highest layout.MaintenancePosition
|
||||
closed := false
|
||||
var timer *time.Timer
|
||||
stall := func() { cancel(fmt.Errorf("%w: %w", ErrMaintenanceNoProgress, context.DeadlineExceeded)) }
|
||||
timer = time.AfterFunc(window, func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if closed {
|
||||
return
|
||||
}
|
||||
if left := window - time.Since(last); left > 0 {
|
||||
timer.Reset(left)
|
||||
return
|
||||
}
|
||||
stall()
|
||||
})
|
||||
passCtx = layout.WithMaintenanceProgress(passCtx, func(position layout.MaintenancePosition) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if closed || passCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if time.Since(last) >= window {
|
||||
stall()
|
||||
return
|
||||
}
|
||||
if !position.After(highest) {
|
||||
return
|
||||
}
|
||||
highest = position
|
||||
last = time.Now()
|
||||
timer.Reset(window)
|
||||
if slot, _ := ctx.Value(maintenanceContextKey{}).(*maintenanceSlot); slot != nil {
|
||||
slot.mu.Lock()
|
||||
slot.result.Processed++
|
||||
slot.mu.Unlock()
|
||||
}
|
||||
})
|
||||
// This watcher belongs only to maintenance. It never holds the progress
|
||||
// mutex while consulting storage, and is joined before the pass returns.
|
||||
watchCtx, stopWatch := context.WithCancel(passCtx)
|
||||
watchDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(watchDone)
|
||||
tick := time.NewTicker(chunkSchedulePoll)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-watchCtx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if layer.Fenced() || !current() {
|
||||
cancel(context.Canceled)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := fn(passCtx)
|
||||
stopWatch()
|
||||
<-watchDone
|
||||
mu.Lock()
|
||||
if passCtx.Err() == nil && time.Since(last) >= window {
|
||||
stall()
|
||||
}
|
||||
closed = true
|
||||
timer.Stop()
|
||||
cause := context.Cause(passCtx)
|
||||
mu.Unlock()
|
||||
if errors.Is(cause, ErrMaintenanceNoProgress) {
|
||||
return cause
|
||||
}
|
||||
if err == nil {
|
||||
return cause
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Exercises the running provider loop and its public pass result, not a timer alone.
|
||||
func TestMaintenanceProgressingPastOneMinuteCompletes(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
layer := maintenanceStubLayer{}
|
||||
slot := &maintenanceSlot{}
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": {chunk: layer, maintenance: slot}}, cfg: ProviderConfig{
|
||||
ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: time.Minute,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
for i := 0; i < 6; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(15 * time.Second):
|
||||
}
|
||||
layout.ReportMaintenanceStep(ctx, 1, uint64(i+1))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
kick := make(chan struct{}, 1)
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, kick, nil)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
kick <- struct{}{}
|
||||
time.Sleep(95 * time.Second)
|
||||
synctest.Wait()
|
||||
got := slot.status()
|
||||
if got.PassesOK < 1 || got.InProgress || got.LastPass.Processed != 6 {
|
||||
t.Fatalf("progressing 90s pass must complete beyond the 1min window: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceRepeatedPositionDoesNotHideAStall(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
start := time.Now()
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
layout.ReportMaintenanceStep(ctx, 1, 1)
|
||||
guard := time.After(2 * time.Minute)
|
||||
for {
|
||||
select {
|
||||
case <-guard:
|
||||
return errors.New("duplicate-progress test guard")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(10 * time.Second):
|
||||
layout.ReportMaintenanceStep(ctx, 1, 1)
|
||||
}
|
||||
}
|
||||
})
|
||||
if !errors.Is(err, ErrMaintenanceNoProgress) || time.Since(start) != time.Minute {
|
||||
t.Fatalf("repeated object renewed stall: elapsed=%v err=%v", time.Since(start), err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceSilentPassReturnsTypedNoProgress(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
start := time.Now()
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
<-ctx.Done()
|
||||
layout.ReportMaintenanceStep(ctx, 1, 1)
|
||||
// Even a late completion and a callback that loses its cancellation error cannot report success.
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, ErrMaintenanceNoProgress) || time.Since(start) != time.Minute {
|
||||
t.Fatalf("silent pass: elapsed=%v err=%v", time.Since(start), err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceReplayedPhaseCannotRenewWindow(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
start := time.Now()
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
old := layout.WithMaintenancePhase(ctx, layout.MaintenanceRetention)
|
||||
layout.ReportMaintenanceStep(old, 1, 100)
|
||||
time.Sleep(30 * time.Second)
|
||||
next := layout.WithMaintenancePhase(ctx, layout.MaintenanceSweep)
|
||||
layout.ReportMaintenanceStep(next, 1, 1)
|
||||
guard := time.After(2 * time.Minute)
|
||||
for {
|
||||
select {
|
||||
case <-guard:
|
||||
return errors.New("replay-progress test guard")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(10 * time.Second):
|
||||
layout.ReportMaintenanceStep(old, 1, 999)
|
||||
}
|
||||
}
|
||||
})
|
||||
if !errors.Is(err, ErrMaintenanceNoProgress) || time.Since(start) != 90*time.Second {
|
||||
t.Fatalf("replayed phase renewed: %v %v", time.Since(start), err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceFiniteStagesCanCompleteAcrossWindow(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
start := time.Now()
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
for stage := uint64(1); stage <= 3; stage++ {
|
||||
time.Sleep(30 * time.Second)
|
||||
layout.ReportMaintenanceStep(ctx, stage, 1)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || time.Since(start) != 90*time.Second {
|
||||
t.Fatalf("finite phase advance: %v %v", time.Since(start), err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMaintenanceProgressStateDoesNotAllocatePerObject(t *testing.T) {
|
||||
allocations := func(objects uint64) float64 {
|
||||
return testing.AllocsPerRun(1, func() {
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
for i := uint64(1); i <= objects; i++ {
|
||||
layout.ReportMaintenanceStep(ctx, 1, i)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
small, cap := allocations(32), allocations(2_900_000)
|
||||
t.Logf("watchdog allocations: 32 positions %.0f; 2900000 positions %.0f", small, cap)
|
||||
if cap > small+32 {
|
||||
t.Fatalf("progress allocates with object count: small %.0f cap %.0f", small, cap)
|
||||
}
|
||||
}
|
||||
|
||||
type maintenanceFenceAfterAdmission struct {
|
||||
maintenanceStubLayer
|
||||
fenced atomic.Bool
|
||||
}
|
||||
|
||||
func (l *maintenanceFenceAfterAdmission) Fenced() bool { return l.fenced.Load() }
|
||||
func TestMaintenanceFenceWithNilSettlementDoesNotCountSuccess(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
layer := &maintenanceFenceAfterAdmission{}
|
||||
slot := &maintenanceSlot{}
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": {chunk: layer, maintenance: slot}}, cfg: ProviderConfig{
|
||||
ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: time.Minute,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error { layer.fenced.Store(true); <-ctx.Done(); return nil },
|
||||
}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
kick := make(chan struct{}, 1)
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, kick, nil)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
kick <- struct{}{}
|
||||
time.Sleep(time.Second)
|
||||
synctest.Wait()
|
||||
got := slot.status()
|
||||
if got.PassesOK != 0 || got.InProgress || got.LastPass == nil || got.LastPass.Error != context.Canceled.Error() {
|
||||
t.Fatalf("fenced nil settlement reported success: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Sample live bytes while the observer/context and watchdog are still alive.
|
||||
// Allocation counts alone would miss one large preallocated retention array.
|
||||
func TestMaintenanceProgressRetainedBytesStayBounded(t *testing.T) {
|
||||
measure := func(objects uint64) int64 {
|
||||
runtime.GC()
|
||||
var before, live runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
err := maintenancePass(context.Background(), maintenanceStubLayer{}, func() bool { return true }, time.Minute, func(ctx context.Context) error {
|
||||
for i := uint64(1); i <= objects; i++ {
|
||||
layout.ReportMaintenanceStep(ctx, 1, i)
|
||||
}
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&live)
|
||||
runtime.KeepAlive(ctx) // retain the observer, including any bad hidden history
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return int64(live.HeapAlloc) - int64(before.HeapAlloc)
|
||||
}
|
||||
small, cap := measure(32), measure(2_900_000)
|
||||
const noiseAndRuntimeBudget = int64(1 << 20)
|
||||
t.Logf("live watchdog HeapAlloc delta: 32 positions %d B; 2900000 positions %d B", small, cap)
|
||||
if small > noiseAndRuntimeBudget || cap > noiseAndRuntimeBudget || cap-small > noiseAndRuntimeBudget {
|
||||
t.Fatalf("progress retains volume-sized history: small=%d B cap=%d B budget=%d B", small, cap, noiseAndRuntimeBudget)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,6 +20,8 @@ type MaintenanceStatus struct {
|
||||
|
||||
// MaintenancePassStatus describes the last completed or failed pass.
|
||||
type MaintenancePassStatus struct {
|
||||
Processed int64 `json:"processed"` // strict completed-work cursor advances in this pass
|
||||
ErrorCode string `json:"errorCode,omitempty"` // no_progress when the inactivity window ends
|
||||
SkipReason layout.ListRetirementSkipReason `json:"skipReason,omitempty"` // conservative list-page retirement skip; never changes serving or the pass outcome
|
||||
AtNs int64 `json:"atNs"` // unix ns when the pass ended
|
||||
Planned int64 `json:"planned"` // all objects considered for removal
|
||||
@@ -52,6 +55,7 @@ func ReportMaintenance(ctx context.Context, result MaintenancePassStatus) {
|
||||
}
|
||||
slot.mu.Lock()
|
||||
defer slot.mu.Unlock()
|
||||
result.Processed = slot.result.Processed
|
||||
slot.result = result
|
||||
}
|
||||
func (m *maintenanceSlot) begin() {
|
||||
@@ -66,6 +70,9 @@ func (m *maintenanceSlot) end(err error) {
|
||||
m.result.AtNs = time.Now().UnixNano()
|
||||
if err != nil {
|
||||
m.result.Error = err.Error()
|
||||
if errors.Is(err, ErrMaintenanceNoProgress) {
|
||||
m.result.ErrorCode = "no_progress"
|
||||
}
|
||||
} else {
|
||||
m.s.PassesOK++
|
||||
}
|
||||
|
||||
@@ -233,8 +233,9 @@ type ProviderConfig struct {
|
||||
// Maintenance runs serially for an attached healthy volume. Zero interval disables
|
||||
// it. Callback ownership ends only after cancellation and worker settlement.
|
||||
ChunkMaintenanceInterval time.Duration
|
||||
ChunkMaintenanceTimeout time.Duration
|
||||
ChunkMaintenance func(context.Context, string) error
|
||||
// ChunkMaintenanceTimeout is the no-progress window, not a total pass bound.
|
||||
ChunkMaintenanceTimeout time.Duration
|
||||
ChunkMaintenance func(context.Context, string) error
|
||||
// ChunkSnapshotPeriod schedules a named snapshot of each attached
|
||||
// healthy volume on its stable per-volume grid after HEAD's latest snapshot
|
||||
// (zero disables it; no history means due now). ChunkScheduledSnapshot
|
||||
|
||||
@@ -1436,26 +1436,24 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
|
||||
if timeout <= 0 {
|
||||
timeout = time.Minute
|
||||
}
|
||||
err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error {
|
||||
p.mu.Lock()
|
||||
h := p.volumes[volumeID]
|
||||
var slot *maintenanceSlot
|
||||
if h != nil && h.chunk == layer {
|
||||
slot = h.maintenance
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if slot == nil {
|
||||
return p.cfg.ChunkMaintenance(passCtx, volumeID)
|
||||
}
|
||||
p.mu.Lock()
|
||||
h := p.volumes[volumeID]
|
||||
var slot *maintenanceSlot
|
||||
if h != nil && h.chunk == layer {
|
||||
slot = h.maintenance
|
||||
}
|
||||
p.mu.Unlock()
|
||||
passCtx := ctx
|
||||
if slot != nil {
|
||||
slot.begin()
|
||||
err := p.cfg.ChunkMaintenance(context.WithValue(passCtx, maintenanceContextKey{}, slot), volumeID)
|
||||
observedErr := err
|
||||
if observedErr == nil {
|
||||
observedErr = passCtx.Err()
|
||||
}
|
||||
slot.end(observedErr)
|
||||
return err
|
||||
passCtx = context.WithValue(ctx, maintenanceContextKey{}, slot)
|
||||
}
|
||||
err := maintenancePass(passCtx, layer, current, timeout, func(passCtx context.Context) error {
|
||||
return p.cfg.ChunkMaintenance(passCtx, volumeID)
|
||||
})
|
||||
if slot != nil {
|
||||
slot.end(err)
|
||||
}
|
||||
if err == nil && observed != nil {
|
||||
seen = observed
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenancePassHasOneDeadline(t *testing.T) {
|
||||
func TestMaintenancePassHasOneNoProgressWindow(t *testing.T) {
|
||||
entered := make(chan error, 1)
|
||||
three := make(chan struct{})
|
||||
var completed atomic.Int32
|
||||
@@ -136,7 +136,7 @@ func TestMaintenancePassHasOneDeadline(t *testing.T) {
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
<-ctx.Done()
|
||||
select {
|
||||
case entered <- ctx.Err():
|
||||
case entered <- context.Cause(ctx):
|
||||
default:
|
||||
}
|
||||
if completed.Add(1) == 3 {
|
||||
@@ -175,7 +175,7 @@ func TestMaintenancePassHasOneDeadline(t *testing.T) {
|
||||
}
|
||||
select {
|
||||
case err := <-entered:
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
if !errors.Is(err, durable.ErrMaintenanceNoProgress) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -427,6 +427,8 @@ func chunkErrorCode(err error) (int, string, bool) {
|
||||
return http.StatusServiceUnavailable, chunkstore.CodeRemoteFull, true
|
||||
case errors.Is(err, layout.ErrQueueFull):
|
||||
return http.StatusConflict, chunkstore.CodeQueueFull, true
|
||||
case errors.Is(err, layout.ErrBusy):
|
||||
return http.StatusConflict, "layout_busy", true
|
||||
case errors.Is(err, storage.ErrChunkRemoteUnavailable):
|
||||
return http.StatusServiceUnavailable, chunkstore.CodeRemoteUnavailable, true
|
||||
case errors.Is(err, durable.ErrNotChunkVolume), errors.Is(err, durable.ErrVolumeNotOpen):
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestSnapshotDeleteLayoutBusyIsTypedRetryable(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
status int
|
||||
}{
|
||||
{"open clean transaction", fmt.Errorf("delete: %w", layout.ErrBusy), "layout_busy", http.StatusConflict},
|
||||
{"queue full remains specific", layout.ErrQueueFull, "queue_full", http.StatusConflict},
|
||||
{"unknown publication wins", errors.Join(storage.ErrChunkCASOutcomeUnknown, layout.ErrBusy), "outcome_unknown", http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := chunkServer(t, &fakeChunkControl{err: tc.err}, true)
|
||||
w := serve(t, s, http.MethodPost, "/chunk/snapshot/delete", `{"volumeID":"v1","name":"s11"}`, "")
|
||||
var answer chunkErrorBody
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &answer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != tc.status || answer.Code != tc.code || !answer.Retryable {
|
||||
t.Fatalf("delete answer: HTTP %d %+v; want HTTP %d %s retryable", w.Code, answer, tc.status, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -542,7 +542,7 @@ open) re-arms after 30 s instead of the interval. The cleaning is on by default
|
||||
Tests: `TestMaintenanceKickRunsAPassNow`, `TestMaintenanceKickedBusyPassRetriesSoon`,
|
||||
`TestDefaultConfigCleansAfterEachSnapshotDelete`. Detach/fence/Close cancels and joins before
|
||||
catalog/storage release; only a still-current handle may re-arm after safe abort.
|
||||
A pass has one minute for retention and the cleaning; retention failure skips the cleaning.
|
||||
A pass has no total deadline. Its one-minute no-progress window renews only on a strict advance of this pass's finite (phase, cursor) work position; a stalled pass answers `no_progress`. Each remote request has a separate 30 s deadline; request attempts never renew the window. The existing cursor resumes later; retention failure skips cleaning.
|
||||
A scoped GC pass traces the whole catalog but mutates only its target volume,
|
||||
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
|
||||
|
||||
@@ -1125,6 +1125,9 @@ Notes:
|
||||
| `INV-HOST-CUT-BUDGET-001` | A cooperating cut process holds a host OS slot from its admission, before staging or the capture barrier: see M7 free → admitted. | M7 free → admitted | `core/hostlimit/limiter.go` `Admit`; `core/storage/chunk_cut_budget.go`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`); `TestHostCutLimitDoesNotGateGuestIO` (`core/frontend/durable/host_limit_test.go`) | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE |
|
||||
| `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE |
|
||||
| `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE |
|
||||
| `INV-MAINTENANCE-BATCH-001` | Cleaning releases HEAD activity after min(1000 decisions, 5 s), checked between decisions. Preparation normally stays outside; re-entry validates its HEAD. Unknown close settles before cursor advancement. Busy answers are typed retryable layout_busy. | M8 Running → Running | `core/frontend/chunkstore/clean_b.go` `endCleanBatch`; `core/frontend/chunkstore/layout/remove.go` `ResetReachability` | `TestMaintenanceFiveSecondBatchLetsSnapshotDeleteFinish`, `TestMaintenanceSlowPreparationDoesNotHoldSession`, `TestMaintenanceBatchRefusesPublicationAfterPreparation`, `TestMaintenanceBatchPreparationAbsentHeadRefuses`, `TestMaintenanceLongPassReleasesLayoutBetweenBatches`, `TestMaintenanceBatchDropsReachabilityAfterPublication`, `TestMaintenanceBatchSettlesUnknownCloseBeforeReentry`, `TestMaintenanceDelayedClosePublicationInvalidatesNextPage`, `TestSnapshotDeleteLayoutBusyIsTypedRetryable`, `TestSnapshotDeleteCLILayoutBusyIsTypedRetryable`, `TestSnapshotDeleteCLIRetriesBusyWithSameIdentityWithinWindow` | SnapshotRemoval BeginClean/EndClean; StaleClean r2 159-161; r2.950(2), r2.955 | STUB |
|
||||
| `INV-MAINTENANCE-LIVENESS-001` | Three refusals without advancing the stuck page arm activity-held preparation for every revisit until that position advances. Its reads share the session hold cap. A waiting same-catalog publisher enters before the next batch; cancellation withdraws its mark. | M8 Running -> Running | `core/frontend/chunkstore/clean_b.go` `RemoveUnreachableAll`; `core/frontend/chunkstore/clean_admission.go`; `core/frontend/chunkstore/layout_remote.go` `beginSessionLocked` | `TestMaintenanceRepeatedPreparationPublicationFallsBackAfterThreeRefusals`, `TestMaintenanceFallbackPreparationSharesSessionCap`, `TestMaintenanceWaitingPublisherRunsBeforeNextBatch`, `TestMaintenanceCancelledPublisherWithdrawsItsMark`, `TestMaintenanceRetainPublisherPrecedesANewCleanPass`, `TestMaintenanceNestedCatalogPublishersDoNotSelfDeadlock`, `TestMaintenancePartialMultiVolumeAdmissionUnwindsOnCancellation`, `TestMaintenanceReleasedBatchContextCannotBypassANewBatch`, `TestMaintenanceCrossVolumeCallbackDoesNotWaitWhileHoldingAClean`, `TestBCatalog_OperatorSnapshotDeleteDuringACleaning` | CleanBatch r2 NoStarve / HoldCap / PubWaitOne; r2.956 | STUB |
|
||||
| `INV-MAINTENANCE-NO-PROGRESS-001` | Maintenance has no total deadline. Only a strict advance of the finite (phase, cursor) work position renews its window; requests are separately bounded. No progress for the window fails typed no_progress; cancellation joins before release and the existing cursor resumes later. | M8 Running → Armed | `core/frontend/durable/maintenance_progress.go` `maintenancePass`; `core/frontend/chunkstore/layout/remove.go` `removePlanned`; `core/frontend/chunkstore/maintenance_request.go` `maintenanceCall` | `TestMaintenanceProgressingPastOneMinuteCompletes`, `TestMaintenanceRepeatedPositionDoesNotHideAStall`, `TestMaintenanceSilentPassReturnsTypedNoProgress`, `TestCleaningReportsProcessedObjects`, `TestRealMaintenanceProgressingPastOneMinuteCompletes`, `TestRealMaintenancePreparationAndRemovalEachOutliveWindow`, `TestMaintenanceListPreparationReportsOnlyAuthenticatedPages`, `TestMaintenanceReachabilityProgressesAcrossTheWindow`, `TestMaintenanceLookupRetriesItsOwnDeadlineWithoutProgress`, `TestMaintenanceReplayedPhaseCannotRenewWindow`, `TestMaintenanceFiniteStagesCanCompleteAcrossWindow`, `TestMaintenanceTagPositionCountsCompletedWorkOnly`, `TestMaintenanceIntentCursorAdvancesAcrossPages`, `TestMaintenanceProgressStateDoesNotAllocatePerObject`, `TestMaintenanceProgressRetainedBytesStayBounded`, `TestMaintenanceFenceWithNilSettlementDoesNotCountSuccess`, `TestMaintenanceUnknownCreateKeepsLinkedUploadAndSettles`, `TestMaintenanceBlobPutDoesNotRepeatUnknownAssignment` | CutTime window rule; GRID-v11-r8 maintenance pass × wall time | STUB |
|
||||
| `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE |
|
||||
| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE |
|
||||
| `INV-HOST-CUT-YIELD-001` | A Normal hold at least YieldAfter old yields its slot at its cut's next staging batch only while another cut on the host holds a live ticket it has not judged stalled; the attempt ends as yielded, never a failure, and keeps what it staged. A lone or urgent hold never yields. | M7 admitted → released (yielded) | `core/hostlimit/limiter.go` `ShouldYield`, `waiterLive`; `core/storage/chunk_layer.go` `stage`; `core/storage/chunk_cut_budget.go` `ErrCutYielded`, `budgetYield`; `core/frontend/durable/provider_chunk.go` `cutPolicy.after` | `TestShouldYieldOnlyAfterSWithALiveWaiter` (`core/hostlimit/yield_test.go`); `TestCutYieldsAtABatchBoundaryAndKeepsItsStaging` (`core/storage/chunk_cut_yield_test.go`); `TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart` (`core/frontend/durable/cut_loop_yield_test.go`) | SlotShareN (yield on the waiting probe, a new ticket at the back); SlotShare rows 189 to 193 | ACTIVE |
|
||||
@@ -1200,7 +1203,7 @@ Notes:
|
||||
|
||||
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
|
||||
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneNoProgressWindow`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
|
||||
| `INV-MAINT-KICK-001` | A snapshot deleted through the holder's control route kicks one maintenance pass at once; kicks coalesce into one pending pass, and no kick is queued without a running loop. | M8 Armed → Due | `provider_chunk.go` `KickMaintenance`, `chunkMaintenanceLoop`; `chunk_control.go` `DeleteSnapshot` | `TestMaintenanceKickRunsAPassNow`, `TestMaintenanceKicksDuringAPassCoalesce`, `TestKickMaintenanceReachesOnlyARunningLoop`, `TestChunkControlSnapshotDeleteKicksTheCleaning`, `TestDefaultConfigCleansAfterEachSnapshotDelete` | `MaintenanceOwner` `OneOwner` | ACTIVE |
|
||||
| `INV-MAINT-KICK-RETRY-001` | A kicked pass refused as busy keeps the kick and re-arms after 30 s; only a pass that is not refused clears it. The delay only paces retries: whether a pass may clean is decided by HEAD's activity, never by the timer. | M8 Running → Armed (busy) | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceKickedBusyPassRetriesSoon` | `MaintenanceOwner` `NoLostKick` | ACTIVE |
|
||||
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and the scheduled-snapshot worker and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass`, `TestScheduledSnapshotLoop_StopJoinsTheAttempt` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
|
||||
@@ -1349,7 +1352,7 @@ Notes:
|
||||
| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload`, `TestMaintenanceUnknownCreateKeepsLinkedUploadAndSettles` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-START-LAYOUT-ID-001` | The launcher's full layout id must match VOLUME and HEAD, even when id8 collides; mismatch is ErrIdentity and startup exits 78 without claiming or serving. The flag comes from the master's volume record. | M9 Start refusal | `core/frontend/chunkstore/layout_create.go` `ReadVolumeRecord`; `core/frontend/chunkstore/layout_store.go` `ReadHead`; `core/frontend/durable/provider_startup.go`; `cmd/blockvolume/process_exit.go`; `core/lifecycle/workload_plan.go` | `TestLayoutIDMismatchIsTypedAndExits78`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads` | K1; full identity, not the directory suffix | ACTIVE |
|
||||
| `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-HEAD-ID-001` | HEAD is decoded only for the volume whose VOLUME carries its volume id; a HEAD of another id, left by an interrupted delete or an old restore under a reused name, is ErrIdentity; a holder without a claim id is malformed. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `DecodeHead`, `Head.check` | `TestDecodeHead_RefusesAnotherVolumesHead`, `TestHead_HolderNeedsAClaimID` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Maintenance admission boundaries
|
||||
|
||||
Admission is process-local scheduling for one `BCatalog` and a full volume
|
||||
identity. It never adds an activity-idle guard or replaces a holder check,
|
||||
session, conditional HEAD write, or conditional Mark/Delete. Retain and legacy
|
||||
snapshot deletion remain legal during `ActClean` in the kernel.
|
||||
|
||||
## Publisher entries
|
||||
|
||||
A publisher is a same-catalog non-cleaner HEAD publication, including one the
|
||||
kernel permits during cleaning. Register for an acquisition or one bounded
|
||||
publication, never for the surrounding multi-step operation.
|
||||
|
||||
| Entry | Registration lifetime |
|
||||
|---|---|
|
||||
| `LayoutRemote.beginSessionLocked` | session acquisition, after cancelling and joining its own cleaner |
|
||||
| `BCatalog.Retain` | each individual `RunRetireSnapshot`; planning and other retirements hold no interest |
|
||||
| `BCatalog.DeleteSnapshot` | one legacy delete transition |
|
||||
| `BCatalog.RunSnapshotDeleteOperation` | its publishing store registers each read/compute/CAS transition; receipt reads, receipt settlement, callbacks and intent staging hold no interest |
|
||||
| `BCatalog.Restore` | publishing store views register each source or target transition; root copying and dependency enumeration hold no interest |
|
||||
| `BCatalog.ReleaseTarget` | each source/target transition |
|
||||
| `BCatalog.DeleteVolume` | each target or discovered source transition; object enumeration and reclamation hold no interest |
|
||||
| `BCatalog.CleanSnapshotDeletePage` | one bounded intent-page continuation |
|
||||
| `LayoutRemote.Clean` intent loop | one bounded intent-page continuation at a time, before opening clean activity |
|
||||
|
||||
`publishingStore` is a shallow view with shared backends and counters. Its optional
|
||||
`BeginHeadPublication` hook is called by `runTransition` before reading HEAD and
|
||||
released after the single compute/CAS, no-op or error. `UpdateHead` does not
|
||||
register again. Waiting only at CAS would make the read generation stale when
|
||||
the preceding clean batch closes. The hook does not retry or change an externally
|
||||
supplied expected base; an already prepared intent can still refuse a stale base
|
||||
and must be resumed through its original caller protocol.
|
||||
Plain `Store` views remain unchanged
|
||||
for low-level/authority users. Multi-volume operations never hold several
|
||||
admissions while copying or enumerating; each publication releases before the
|
||||
next one. The scheduling state per volume is O(1).
|
||||
|
||||
## Clean entries and transfer
|
||||
|
||||
| Entry | Admission lifetime |
|
||||
|---|---|
|
||||
| `LayoutRemote.Clean` initial `RunBeginClean` | acquired outside the remote mutex, before initial activity |
|
||||
| `RemoveUnreachableAll` initial `endCleanBatch` | releases initial admission after durable close/settlement, before any page admission |
|
||||
| optimistic and armed page batches | before Begin until close/settlement |
|
||||
|
||||
The initial lease uses `sync.Once`; the remote defers the same release for errors
|
||||
and non-catalog callbacks. Publisher and clean acquisition never nest. No
|
||||
storage call runs with the admission mutex held. Cancellation withdraws the
|
||||
publisher mark.
|
||||
|
||||
A3: a synchronous reference-removing call carrying this exact live batch context
|
||||
is **unregistered**, rather than waiting on itself. SnapshotRemoval monotonicity
|
||||
keeps the cached superset safe; an armed batch's held-generation check fails
|
||||
safe after such a publication. The original kernel checks remain unchanged.
|
||||
The callback is not given layout authority. A released context cannot bypass a
|
||||
later batch. A callback holding a different volume's clean lease does not wait
|
||||
on a held clean admission; it returns retryable `layout_busy`.
|
||||
|
||||
## Explicit scope and liveness assumptions
|
||||
|
||||
- A2: publisher preference is not FIFO. Cleaning liveness assumes registrations
|
||||
do not overlap continuously. An overlapping stream can delay an armed batch;
|
||||
no unsafe effect follows, and its maintenance window can end the pass.
|
||||
- Other processes/catalogs (offline CLI or another holder) have no shared waiter;
|
||||
they retain typed `layout_busy` and their own command window.
|
||||
- Authority transitions (claim, fence, takeover), rollback and stop settlement
|
||||
are outside scheduling. Stop first joins maintenance. Cleaner-owned activity
|
||||
writes, non-publishing calls and direct low-level users are also excluded.
|
||||
- Fresh volume creation has no attached cleaner. No new exclusive-create retry
|
||||
is introduced.
|
||||
|
||||
## Controls
|
||||
|
||||
`TestMaintenanceRetainPublisherPrecedesANewCleanPass` pauses the individual
|
||||
retirement after it registers: a real new `LayoutRemote.Clean` must let it publish
|
||||
first, then transfer initial admission to real catalog page batches.
|
||||
`TestMaintenanceRetainPlanningDoesNotRegister` proves planning does not hold the
|
||||
mark. `TestMaintenancePublishingStoreScopesOneConditionalWrite` proves reads and
|
||||
plain stores remain unregistered, a read/compute/CAS publication waits and registers,
|
||||
and its interest ends on return. Existing delete-during-clean and released-token
|
||||
controls preserve A3 and the original kernel semantics. These native controls do
|
||||
not claim Linux/race or scale qualification.
|
||||
|
||||
`TestMaintenanceReleasePublicationReadsAfterBatchClose` opens a real clean
|
||||
activity, then starts the real dependent-release kernel transition. It must
|
||||
wait before reading HEAD, survive the close's generation advance, and remove
|
||||
the dependent successfully. The old CAS-only registration fails this control
|
||||
with ErrPrecondition. No stale-proposal retry is introduced.
|
||||
|
||||
The A3 control observes the publisher count INSIDE the actual backend HEAD CAS,
|
||||
so a transient register/release cannot pass it. `TestMaintenancePublisherInterestHeldThroughBackendCAS`
|
||||
pauses the actual backend CAS and asserts a next clean batch cannot enter until
|
||||
that call returns. Both a transient-A3-registration mutant and a release-just-
|
||||
before-CAS mutant fail their named controls.
|
||||
@@ -647,7 +647,7 @@ and the volume does not serve. A monitor that only watches for failed units does
|
||||
holder itself (the schedule's retention) and every `--chunk-maintenance-interval` (default 1 h). A snapshot deleted
|
||||
with `ops chunk snapshot-delete` is cleaned at the next pass, so its space can take up to that interval to return;
|
||||
when freeing space on a full store, allow for it. `--chunk-maintenance-gc=false` turns it off, and then nothing
|
||||
removes them. The disk space returns when SeaweedFS vacuums its volumes.
|
||||
removes them. The disk space returns when SeaweedFS vacuums its volumes. A maintenance pass has no total time limit: each strict advance of the finite (phase, cursor) work position renews its one-minute inactivity window. A stalled pass reports `no_progress` and the next pass resumes its cursor; each remote request is bounded separately at 30 seconds. Compatibility cleaning normally prepares outside its HEAD activity, then closes that activity after at most 1,000 candidate decisions or 5 seconds, checked between completed decisions; an in-flight operation keeps its own request bound. It continues from the remaining cursor without ending the pass. After an intervening HEAD write it rebuilds reachability and rejects preparation that raced a publication. After three preparation refusals without passing the stuck cursor position, the whole retry pass prepares under activity; read-only preparation shares the 5-second hold budget. Root/segment revisits do not erase the refusal history. Same-catalog publishers go before the next cleaning batch; an independent CLI has no shared waiter. A concurrent layout operation reports retryable `layout_busy`, and snapshot-delete resumes its captured operation within its own command window.
|
||||
- **Node reattach events under mutual TLS.** Node reattach events are not recorded in the cluster event log under
|
||||
mutual TLS: a CSI node's certificate is `viewer`, so blockmaster refuses the event and the node logs one line per
|
||||
reattach.
|
||||
|
||||
@@ -80,3 +80,5 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
|
||||
is unchanged) and a usage error.
|
||||
- v1.1 answers the reverse case, a store or HEAD written by a later version, with a final exit 78
|
||||
(`store_format_newer`, `head_newer_version`), which the unit does not restart.
|
||||
|
||||
Maintenance cleaning now uses a one-minute inactivity window renewed by strict advances of the finite (phase, cursor) work position, with separate 30-second remote-request deadlines. A stalled pass reports `no_progress` and resumes at its existing cursor on the next pass; a large progressing pass has no total deadline.
|
||||
@@ -275,6 +275,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
|
||||
| `Volumes[].Chunk.Maintenance.inProgress` | bool | a maintenance callback is running |
|
||||
| `Volumes[].Chunk.Maintenance.currentStartNs` | int64 | unix ns start of the running pass; zero when idle |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass` | object | absent until a pass ends (omitted when empty) |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass.processed` | int64 | strict completed-work cursor advances in this pass |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass.errorCode` | string | no_progress when the inactivity window ends (omitted when empty) |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass.skipReason` | ListRetirementSkipReason (string) | conservative list-page retirement skip; never changes serving or the pass outcome (omitted when empty) |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass.atNs` | int64 | unix ns when the pass ended |
|
||||
| `Volumes[].Chunk.Maintenance.lastPass.planned` | int64 | all objects considered for removal |
|
||||
|
||||
Reference in new issue
Block a user