Merge pull request #123 from seaweedfs/feat/chunk-gc-copy-sweep

storage: settle copy intents through permanent publication claims
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-15 10:33:48 -08:00
commit 6daca22e2f
6 files changed
+1111

No files matched your search

@@ -0,0 +1,29 @@
# Chunk garbage collection (W5, library slice)
`NewCollector(catalog, blobDeleter, config).Run(ctx)` traces every volume returned by the catalog, every HEAD, every snapshot (including unnamed attempt entries), and every live upload/copy intent. Use a deadline-bound context. Supply `IssuedEpoch` from the authoritative blockmaster reader, not lease expiry or a host-local projection. There is no automatic scheduler or destructive CLI in this slice.
A capture intent can expire only when its age strictly exceeds IntentTTL, the blockmaster has issued a higher epoch, and the actual remote HEAD has advanced to a higher epoch no greater than the issued one. Unknown authority retains it. Snapshot/fork copy intents never expire by epoch. `SweepCopies(ctx)` may settle an attempt past its recorded deadline only by claiming its final immutable publication target through Catalog.AbortSnapshot/AbortFork. Snapshot targets are `snaps/<name>/<attempt>`; fork targets are HEAD, never VOLUME. A confirmed permanent aborted target or a validated published target settles the intent. Unknown claim/read retains it. The deadline admits a claim but never by itself releases protection. Old copy intents without deadline metadata remain protected.
An immutable binding becomes a candidate only when its creation time is strictly older than Grace and no root names it. Reclamation requires another successful mark at least Grace after its first observation with the same binding bytes. A rooted candidate is forgotten; failed marks and collector restart discard coverage. Grace must exceed the catalog operation deadline plus the measured mark duration. Backward clock movement refuses the pass.
Before physical deletion the binding receives a conditional `swb.gc.deleted=1` tombstone; after every resolved replica deletion succeeds it becomes `done`. Bindings are never removed or rebound. Failed/uncertain blob deletion returns an error and retains the fid for a conservative retry after fresh marks. The SeaweedFS adapter deletes the exact fid, accepts only HTTP 200/204/404, and propagates transport/other HTTP failures. Authenticated deployments must supply a BlobDeleter with their write authorization; this patch does not add an auth provisioning path.
Unbound needles (upload succeeded but key binding never persisted) are RETAINED. The existing interfaces cannot enumerate/count them, so `UnknownUnbound=true` reports that limitation instead of a fabricated zero. No sweep is attempted.
## Scope and follow-ups
This first Draft implements the GC core and the real Capture/intent/HEAD caller regression. Retention (newest N plus logarithmic age buckets), workspace tombstoning, CLI scheduling and a concrete blockmaster client binding remain follow-up W5 slices. Unnamed deleting snapshot attempts root their keys until their deleting timestamp is older than grace; normal two-mark/upload-age admission still applies afterward. The immutable attempt record is never removed, even after reclaim. Active unnamed attempts remain roots. This is not complete workspace lifecycle acceptance.
## Lock order
The new Collector mutex serializes its own passes and candidate state; it never enters WAL, publication, shard or chunk-layer locks. Remote calls execute only while holding that collector-local mutex. Producer Capture already uploads after releasing its capture/publication barrier, so GC adds no edge to the storage lock graph. The epoch-reader and BlobDeleter must not re-enter this Collector. Multiple collectors may repeat idempotent physical deletes, but each must independently satisfy the two-mark grace rule.
## Evidence boundary
The assertion RED is an initial GC candidate that already implemented HEAD/snapshot tracing and two marks but omitted intent roots; the base has no GC API to test. It is NOT claimed as a GC bug reproduced on unmodified main. The same test holds the shipping Capture before CAS after real immutable uploads, runs two GC marks, resumes CAS, and reads exact bytes through ChunkRemote. Filer/needle services are deterministic adapters; no SeaweedFS process, hardware, lab or cloud acceptance is claimed.
## Copy-sweep integration
The follow-up branch merges W2 #119 b51713e with #117 5f010ca (the #121 parent). The sole capture conflict keeps #117's pre-upload intent list and cleanup semantics, and retains #119's typed `ErrChunkRemoteUnavailable` wrapper on upload failure. No capture intent is swept through the copy protocol. Name reuse creates a new snapshot attempt; permanent old attempt tombstones continue refusing late old inserts. Volume IDs cannot be reused.
The first copy-sweep RED uses the prior retain-forever behavior (a no-op SweepCopies seam), not a claimed bug on an unmodified main. The same real Catalog caller turns GREEN with permanent-target claims. Tests cover a pending snapshot across name reuse, a fork with VOLUME already present and HEAD held, published unnamed/deleting attempts, unknown claim recovery, and the retained stalled-Capture case. Deterministic remote services only; no lab/cloud actions.
@@ -0,0 +1,286 @@
package chunkstore
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net/url"
"path"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/protobuf/proto"
)
const extGCDeleted = "swb.gc.deleted"
// BlobDeleter deletes one immutable needle. Missing needles are success.
// Implementations must not reuse a deleted fid.
type BlobDeleter interface {
DeleteBlob(context.Context, string) error
}
// GCConfig binds a collector to the authoritative blockmaster epoch reader.
// IssuedEpoch must read the highest epoch issued for this volume, never a
// lease expiry or a cached guess. Unknown authority retains the intent.
type GCConfig struct {
Grace, IntentTTL time.Duration
IssuedEpoch func(context.Context, string) (uint64, error)
Now func() time.Time
}
type GCResult struct {
Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int
// Pre-binding needles cannot be enumerated by this API. They are retained;
// UnknownUnbound is true rather than inventing a report-only count.
UnknownUnbound bool
}
type gcCandidate struct {
since time.Time
digest [32]byte
}
type gcBinding struct {
volume string
entry *filerpb.Entry
digest [32]byte
}
type gcIntent struct {
remote *ChunkRemote
intent storage.ChunkIntent
}
// Collector traces all catalog roots. Calls are serialized per collector;
// restarting loses candidates, which adds delay rather than authorizing a
// deletion. No WAL, publication or shard lock is held during remote I/O.
// Different collectors may duplicate idempotent blob deletes but cannot
// shorten either collector's independent two-mark grace requirement.
type Collector struct {
cat *Catalog
blobs BlobDeleter
cfg GCConfig
mu sync.Mutex
candidates map[string]gcCandidate
last time.Time
}
func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) {
if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil {
return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority")
}
if cfg.Now == nil {
cfg.Now = time.Now
}
return &Collector{cat: cat, blobs: blobs, cfg: cfg, candidates: map[string]gcCandidate{}}, nil
}
// Run completes a mark before any chunk deletion. Any failed mark discards
// previous candidates. Roots include active and deleting snapshots until
// the catalog has actually removed them; this collector never infers their
// absence from an age or a retention label.
func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
g.mu.Lock()
defer g.mu.Unlock()
result.UnknownUnbound = true
defer func() {
if err != nil {
g.candidates = map[string]gcCandidate{}
}
}()
start := g.cfg.Now()
if !g.last.IsZero() && start.Before(g.last) {
return result, errors.New("chunkstore: GC clock moved backwards")
}
roots := map[string]bool{}
var bindings []gcBinding
var expired []gcIntent
volumes, err := g.cat.ListVolumes(ctx)
if err != nil {
return result, err
}
result.Volumes = len(volumes)
for _, vol := range volumes {
r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol))
if e != nil {
return result, e
}
h, e := r.GetHead(ctx)
if e != nil {
return result, e
}
addHead := func(head storage.ChunkHead) error {
for _, ref := range head.Chunks {
dir, name, e := r.keyLocation(ref.Key)
if e != nil {
return e
}
roots[path.Join(dir, name)] = true
}
return nil
}
if e = addHead(h); e != nil {
return result, e
}
after := ""
for {
snaps, next, e := g.cat.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, IncludeDeleting: true, Limit: maxListLimit})
if e != nil {
return result, e
}
for _, snap := range snaps {
if e = addHead(snap.Head()); e != nil {
return result, e
}
}
if next == "" {
break
}
if next <= after {
return result, errors.New("chunkstore: non-advancing snapshot listing")
}
after = next
}
attempts, e := g.snapshotAttemptHeads(ctx, vol, start)
if e != nil {
return result, e
}
for _, head := range attempts {
if e = addHead(head); e != nil {
return result, e
}
}
intents, e := r.ListIntents(ctx)
if e != nil {
return result, e
}
for _, in := range intents {
result.Intents++
if in.CreatedNs <= 0 || in.CreatedNs > start.UnixNano() {
return result, errors.New("chunkstore: invalid intent creation time")
}
expire := false
if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL {
issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol)
// Catalog copy intents are retained: their exclusive creates
// are not epoch-fenced. For a capture, both the authority
// and the actual CAS domain must have
// advanced. Mere lease loss, or issuance without takeover,
// cannot authorize expiry of a paused publisher's intent.
expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued
}
if expire {
expired = append(expired, gcIntent{r, in})
} else {
for _, key := range in.Keys {
dir, name, e := r.keyLocation(key)
if e != nil {
return result, e
}
roots[path.Join(dir, name)] = true
}
}
}
pageAfter := ""
for {
page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage)
if e != nil {
return result, e
}
for _, entry := range page {
if entry.GetName() <= pageAfter || entry.GetIsDirectory() || len(entry.GetChunks()) != 0 || string(entry.Extended[extKind]) != kindChunkKey || len(entry.Extended[extFid]) == 0 || entry.Attributes == nil || entry.Attributes.Crtime <= 0 {
return result, fmt.Errorf("chunkstore: invalid GC binding %s/%s", r.keyDir(), entry.GetName())
}
key, e := url.PathUnescape(entry.GetName())
if e != nil {
return result, e
}
dir, name, e := r.keyLocation(key)
if e != nil || dir != r.keyDir() || name != entry.GetName() {
return result, errors.New("chunkstore: noncanonical GC binding")
}
raw, e := proto.MarshalOptions{Deterministic: true}.Marshal(entry)
if e != nil {
return result, e
}
bindings = append(bindings, gcBinding{vol, entry, sha256.Sum256(raw)})
pageAfter = entry.GetName()
}
if len(page) < listPage {
break
}
}
}
if g.cfg.Now().Sub(start)+g.cat.deadline() >= g.cfg.Grace {
return result, errors.New("chunkstore: GC mark exceeded grace safety margin")
}
// An intent is retired only after the complete mark and confirmed fencing.
for _, x := range expired {
if err = x.remote.DeleteIntent(ctx, x.intent.ID); err != nil {
return result, err
}
result.ExpiredIntents++
}
nextCandidates := map[string]gcCandidate{}
for _, b := range bindings {
p := path.Join(g.cat.base, b.volume, keysDir, b.entry.Name)
if roots[p] {
if len(b.entry.Extended[extGCDeleted]) != 0 {
return result, fmt.Errorf("chunkstore: root references reclaimed binding %s", p)
}
continue
}
if string(b.entry.Extended[extGCDeleted]) == "done" {
continue
}
created := time.Unix(b.entry.Attributes.Crtime, 0)
if !start.After(created.Add(g.cfg.Grace)) {
continue
}
candidate, seen := g.candidates[p]
if !seen || candidate.digest != b.digest {
candidate = gcCandidate{start, b.digest}
}
result.Candidates++
if start.Sub(candidate.since) < g.cfg.Grace {
nextCandidates[p] = candidate
continue
}
// Preserve the immutable binding forever: removing it would allow Put
// to rebind a key that once existed. The tombstone also permits retry
// after a failed physical delete without losing the fid.
if string(b.entry.Extended[extGCDeleted]) != "1" {
e := proto.Clone(b.entry).(*filerpb.Entry)
e.Extended[extGCDeleted] = []byte("1")
expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: b.entry.Extended[extFid], extGCDeleted: nil}
if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, expected); err != nil {
return result, err
}
}
if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil {
return result, err
}
e := proto.Clone(b.entry).(*filerpb.Entry)
e.Extended[extGCDeleted] = []byte("done")
if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, map[string][]byte{extFid: b.entry.Extended[extFid], extGCDeleted: []byte("1")}); err != nil {
return result, err
}
result.Reclaimed++
}
g.candidates = nextCandidates
g.last = start
return result, nil
}
// nilBlobs is used only for read-only metadata traversal, never chunk I/O.
type nilBlobs struct{}
func (nilBlobs) Put(context.Context, []byte) (string, error) {
return "", errors.New("chunkstore: metadata-only remote")
}
func (nilBlobs) Get(context.Context, string) ([]byte, error) {
return nil, errors.New("chunkstore: metadata-only remote")
}
@@ -0,0 +1,180 @@
package chunkstore
import (
"context"
"errors"
"fmt"
"path"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// SweepCopies settles expired copy attempts using permanent publication
// target claims; a deadline only admits a claim, never releases protection.
// It shares the collector pass mutex but acquires no storage locks.
func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) {
g.mu.Lock()
defer g.mu.Unlock()
now := g.cfg.Now()
vols, err := g.cat.ListVolumes(ctx)
if err != nil {
return 0, err
}
type copyAttempt struct {
vol string
remote *ChunkRemote
in storage.ChunkIntent
}
var pending []copyAttempt
for _, vol := range vols {
r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol))
if e != nil {
return 0, e
}
intents, e := r.ListIntents(ctx)
if e != nil {
return 0, e
}
for _, in := range intents {
if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") {
continue
}
if in.CreatedNs <= 0 || in.CreatedNs > now.UnixNano() {
return 0, errors.New("chunkstore: invalid copy intent creation time")
}
if in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs {
continue
}
pending = append(pending, copyAttempt{vol, r, in})
}
}
for _, a := range pending {
if err = ctx.Err(); err != nil {
return settled, err
}
if strings.HasPrefix(a.in.Holder, "snapshot:") {
parts := strings.Split(strings.TrimPrefix(a.in.Holder, "snapshot:"), "/")
if len(parts) != 3 || parts[0] != a.vol || CheckSnapshotName(parts[1]) != nil || !storage.ValidChunkIntentID(parts[2]) {
return settled, fmt.Errorf("chunkstore: malformed snapshot intent %s", a.in.ID)
}
// Claim the final attempt, never the reusable name record.
if _, err = g.cat.AbortSnapshot(ctx, a.vol, parts[1], parts[2]); err != nil {
return settled, err
}
dir := path.Join(g.cat.base, a.vol, snapsDir, parts[1])
e, readErr := g.cat.f.LookupEntry(ctx, dir, parts[2])
if readErr != nil {
return settled, readErr
}
info, _, readErr := decodeSnap(path.Join(dir, parts[2]), e)
if readErr != nil {
return settled, readErr
}
if info.VolumeID != a.vol || info.Name != parts[1] || (info.State != SnapAborted && string(e.Extended[extAttempt]) != parts[2]) {
return settled, errors.New("chunkstore: copy claim identity mismatch")
}
} else {
parts := strings.SplitN(strings.TrimPrefix(a.in.Holder, "fork:"), "/", 2)
if len(parts) != 2 || parts[0] != a.vol || parts[1] == "" {
return settled, fmt.Errorf("chunkstore: malformed fork intent %s", a.in.ID)
}
v, ok, readErr := g.cat.ReadVolume(ctx, a.vol)
if readErr != nil {
return settled, readErr
}
if !ok || v.Origin != OriginFork || v.Fork == nil || v.Fork.RequestID != parts[1] {
return settled, errors.New("chunkstore: fork intent has no matching target VOLUME")
}
if _, err = g.cat.AbortFork(ctx, a.vol); err != nil {
return settled, err
}
h, ok, readErr := g.cat.ReadHead(ctx, a.vol)
if readErr != nil {
return settled, readErr
}
if !ok || h.Gen == 0 {
return settled, errors.New("chunkstore: fork claim did not settle the publishing HEAD")
}
}
// Both a valid published immutable entry and a valid permanent aborted
// entry settle this attempt. Unknown claim/read never drops its intent.
if err = a.remote.DeleteIntent(ctx, a.in.ID); err != nil {
return settled, err
}
settled++
}
return settled, nil
}
func (g *Collector) gcEntries(ctx context.Context, dir string) ([]*filerpb.Entry, error) {
var out []*filerpb.Entry
after := ""
for {
page, err := g.cat.f.ListEntries(ctx, dir, "", after, listPage)
if err != nil {
return nil, err
}
for _, e := range page {
if e.GetName() <= after || path.Base(e.GetName()) != e.GetName() {
return nil, errors.New("chunkstore: invalid/non-advancing GC directory listing")
}
after = e.Name
out = append(out, e)
}
if len(page) < listPage {
return out, nil
}
}
}
// snapshotAttemptHeads includes unnamed attempts left behind by DeleteSnapshot.
// Attempt entries are permanent. A deleting attempt stops rooting its keys
// only after its deleting timestamp ages past grace; ordinary two marks
// still apply afterward. An aborted attempt roots no keys.
func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now time.Time) ([]storage.ChunkHead, error) {
root := path.Join(g.cat.base, vol, snapsDir)
dirs, err := g.gcEntries(ctx, root)
if err != nil {
return nil, err
}
var heads []storage.ChunkHead
for _, dir := range dirs {
if !dir.GetIsDirectory() || CheckSnapshotName(dir.Name) != nil {
return nil, errors.New("chunkstore: invalid snapshot attempt directory")
}
entries, err := g.gcEntries(ctx, path.Join(root, dir.Name))
if err != nil {
return nil, err
}
for _, e := range entries {
if !storage.ValidChunkIntentID(e.Name) {
return nil, errors.New("chunkstore: invalid snapshot attempt identity")
}
info, _, err := decodeSnap(path.Join(root, dir.Name, e.Name), e)
if err != nil {
return nil, err
}
if info.VolumeID != vol || info.Name != dir.Name || (info.State != SnapAborted && string(e.Extended[extAttempt]) != e.Name) {
return nil, errors.New("chunkstore: snapshot attempt names another volume/name")
}
if info.State == SnapAborted {
continue
}
if info.State == SnapDeleting {
ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64)
if err != nil || ns <= 0 || ns > now.UnixNano() {
return nil, errors.New("chunkstore: invalid deleted snapshot timestamp")
}
if now.Sub(time.Unix(0, ns)) > g.cfg.Grace {
continue
}
}
heads = append(heads, info.Head())
}
}
return heads, nil
}
@@ -0,0 +1,197 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/storage"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
func snapshotDir(t *testing.T, f *fakeFiler, vol, name string) {
t.Helper()
if e := f.CreateEntry(context.Background(), path.Join(catBase, vol, snapsDir), &filerpb.Entry{Name: name, IsDirectory: true}, true); e != nil {
t.Fatal(e)
}
}
func TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31)})
snapshotDir(t, f, "v1", "s1")
holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/")
if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown {
t.Fatalf("held snapshot: %v", e)
}
oldPath := snapPath(t, f, "v1", "s1")
if count, e := g.SweepCopies(ctx); e != nil || count != 0 {
t.Fatalf("early sweep: %d %v", count, e)
}
*now = now.Add(DefaultOpDeadline + time.Second)
if count, e := g.SweepCopies(ctx); e != nil || count != 1 {
t.Fatalf("dead copy intent not settled by tombstone claim: count=%d err=%v", count, e)
}
if ins := intentsOf(t, f, "v1"); len(ins) != 0 {
t.Fatalf("intent retained after target claimed: %+v", ins)
}
e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath))
if err != nil || string(e.Extended[extSnapState]) != SnapAborted {
t.Fatalf("permanent claim missing: %v", err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "new"}, h); err != nil {
t.Fatal(err)
}
if p := snapPath(t, f, "v1", "s1"); p == oldPath {
t.Fatal("reused permanent attempt path")
}
if applied := f.releaseDeferredCreates(); applied != 0 {
t.Fatalf("late old snapshot insert landed after name reuse: %d", applied)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "newfork", RequestID: "fork"}); err != nil {
t.Fatal(err)
}
// The new name resolves to its new published attempt, never old tombstone.
info, err := c.readSnap(ctx, "v1", "s1")
if err != nil || info.Head().Gen != h.Gen {
t.Fatalf("new snapshot: %+v %v", info, err)
}
}
func TestGC_CopySweepClaimsForkHEADNotExistingVolume(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)})
snapshotDir(t, f, "v1", "s1")
if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); e != nil {
t.Fatal(e)
}
if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil {
t.Fatal(e)
}
holdFirst(f, path.Join(catBase, "v2", headName))
if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "dead"}); CodeOf(e) != CodeOutcomeUnknown {
t.Fatalf("held fork: %v", e)
}
if _, ok, e := c.ReadVolume(ctx, "v2"); e != nil || !ok {
t.Fatalf("fixture lacks existing VOLUME: %v", e)
}
if _, ok, e := c.ReadHead(ctx, "v2"); e != nil || ok {
t.Fatalf("held fork already published: %v %v", ok, e)
}
*now = now.Add(DefaultOpDeadline + time.Second)
count, e := g.SweepCopies(ctx)
if e != nil || count != 1 {
t.Fatalf("fork sweep: %d %v", count, e)
}
head, ok, e := c.ReadHead(ctx, "v2")
if e != nil || !ok || head.State != storage.ChunkHeadAborted {
t.Fatalf("final HEAD not claimed: %+v %v", head, e)
}
if n := f.releaseDeferredCreates(); n != 0 {
t.Fatalf("late fork HEAD published over claim: %d", n)
}
if _, e := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(e) != CodeForkIncomplete {
t.Fatalf("aborted target attached: %v", e)
}
if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "new"}); CodeOf(e) != CodeTargetExists {
t.Fatalf("volume id reused: %v", e)
}
}
type retainCopyIntent struct{ Filer }
func (f retainCopyIntent) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
if path.Base(dir) == intentsDir {
return errors.New("cleanup response unavailable")
}
return f.Filer.DeleteEntry(ctx, dir, name, expected)
}
func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x51)})
snapshotDir(t, f, "v1", "s1")
c.f = retainCopyIntent{f}
if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "published"}, h); e != nil {
t.Fatal(e)
}
c.f = f
oldPath := snapPath(t, f, "v1", "s1")
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1"}); e != nil {
t.Fatal(e)
}
*now = now.Add(DefaultOpDeadline + time.Second)
if count, e := g.SweepCopies(ctx); e != nil || count != 1 {
t.Fatalf("published copy claim: %d %v", count, e)
}
e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath))
if err != nil || string(e.Extended[extSnapState]) != SnapActive {
t.Fatalf("published snapshot was overwritten: %v", err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
// The name is gone, but its immutable attempt remains a root throughout grace.
if list, _, e := c.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: true}); e != nil || len(list) != 0 {
t.Fatalf("name still listed: %+v %v", list, e)
}
for i := 0; i < 2; i++ {
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("unnamed deleting attempt lost grace: %+v %v", result, e)
}
*now = now.Add(time.Minute)
}
for _, ref := range h.Chunks {
if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x51)) {
t.Fatalf("snapshot bytes lost: %v", e)
}
}
*now = now.Add(2 * time.Hour)
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("first unrooted mark: %+v %v", result, e)
}
*now = now.Add(time.Hour)
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 {
t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e)
}
if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil {
t.Fatal("permanent attempt entry removed", e)
}
}
func TestGC_CopyClaimUnknownRetainsIntent(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x61)})
snapshotDir(t, f, "v1", "s1")
holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/")
if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown {
t.Fatal(e)
}
*now = now.Add(DefaultOpDeadline + time.Second)
f.failCreate = func(string) error { return errors.New("claim outcome unknown") }
if n, e := g.SweepCopies(ctx); e == nil || n != 0 {
t.Fatalf("unknown claim accepted: %d %v", n, e)
}
if ins := intentsOf(t, f, "v1"); len(ins) != 1 {
t.Fatalf("unknown claim released root: %+v", ins)
}
f.failCreate = nil
if n, e := g.SweepCopies(ctx); e != nil || n != 1 {
t.Fatalf("claim recovery: %d %v", n, e)
}
}
@@ -0,0 +1,390 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type gcBlobs struct{ *fakeBlobs }
func (b gcBlobs) DeleteBlob(_ context.Context, fid string) error {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.data, fid)
return nil
}
type heldGCRemote struct {
*ChunkRemote
entered chan struct{}
release chan struct{}
}
func (r *heldGCRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) {
close(r.entered)
select {
case <-r.release:
case <-ctx.Done():
return 0, ctx.Err()
}
return r.ChunkRemote.CASHead(ctx, v, h)
}
func gcFixture(t *testing.T) (*fakeFiler, gcBlobs, *Catalog, *Collector, *time.Time) {
t.Helper()
f, b := newFakeFiler(), gcBlobs{newFakeBlobs()}
c := newCat(t, f)
if e := f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); e != nil {
t.Fatal(e)
}
if _, e := c.EnsureVolume(context.Background(), "v1", catGeo); e != nil {
t.Fatal(e)
}
now := time.Now().Add(24 * time.Hour)
g, e := NewCollector(c, b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }})
if e != nil {
t.Fatal(e)
}
return f, b, c, g, &now
}
func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
remote, e := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if e != nil {
t.Fatal(e)
}
held := &heldGCRemote{remote, make(chan struct{}), make(chan struct{})}
p := filepath.Join(t.TempDir(), "volume")
s, e := storage.CreateWALStore(p, 64, 4096)
if e != nil {
t.Fatal(e)
}
defer s.Close()
if _, e = s.Recover(); e != nil {
t.Fatal(e)
}
layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")})
if e != nil {
t.Fatal(e)
}
want := bytes.Repeat([]byte{0x71}, 4096)
if _, e = s.Write(0, want); e != nil {
t.Fatal(e)
}
done := make(chan error, 1)
go func() { _, e := layer.Capture(ctx); done <- e }()
select {
case <-held.entered:
case <-ctx.Done():
t.Fatal("cut never reached post-upload CAS")
}
// Always release the owned cut before Close, including a failing assertion.
released := false
defer func() {
if !released {
close(held.release)
<-done
}
}()
for i := 0; i < 2; i++ {
result, e := g.Run(ctx)
if e != nil {
t.Fatal(e)
}
t.Logf("mark %d: %+v", i+1, result)
*now = now.Add(time.Hour + time.Second)
}
close(held.release)
released = true
if e := <-done; e != nil {
t.Fatal(e)
}
h, e := remote.GetHead(ctx)
if e != nil || h.Gen == 0 {
t.Fatalf("published HEAD: %+v %v", h, e)
}
for _, ref := range h.Chunks {
got, e := remote.Get(ctx, ref.Key)
if e != nil || !bytes.Equal(got[:min(len(got), 4096)], want) {
t.Fatalf("published HEAD references deleted or corrupt stalled-cut chunk: key=%q bytes=%d err=%v", ref.Key, len(got), e)
}
}
}
func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if e := r.Put(ctx, "orphan", []byte("exact orphan")); e != nil {
t.Fatal(e)
}
if _, e := g.Run(ctx); e != nil {
t.Fatal(e)
}
*now = now.Add(time.Hour - time.Second)
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("early second mark: %+v %v", result, e)
}
if _, e := r.Get(ctx, "orphan"); e != nil {
t.Fatal("orphan deleted before grace", e)
}
*now = now.Add(2 * time.Second)
result, e := g.Run(ctx)
if e != nil || result.Reclaimed != 1 {
t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e)
}
if _, e := r.Get(ctx, "orphan"); e == nil {
t.Fatal("reclaimed orphan remains readable")
}
fresh, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if e := fresh.Put(ctx, "orphan", []byte("reused")); !errors.Is(e, storage.ErrChunkKeyExists) {
t.Fatalf("immutable key reused after GC: %v", e)
}
// A freshly uploaded chunk cannot enter its first candidate mark yet.
*now = time.Now()
next, e := NewCollector(g.cat, b, g.cfg)
if e != nil {
t.Fatal(e)
}
if e := r.Put(ctx, "young", []byte("young")); e != nil {
t.Fatal(e)
}
if result, e := next.Run(ctx); e != nil || result.Candidates != 0 {
t.Fatalf("young upload admitted: %+v %v", result, e)
}
}
func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) {
for _, tc := range []struct {
name string
issued, head uint64
age time.Duration
authorityErr bool
expire bool
}{
{"current-holder-old-intent", 1, 1, 2 * time.Hour, false, false},
{"higher-issued-but-no-takeover", 2, 1, 2 * time.Hour, false, false},
{"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false},
{"unknown-authority", 2, 2, 2 * time.Hour, true, false},
{"TTL-not-exceeded", 2, 2, time.Hour, false, false},
{"higher-issued-and-fenced", 2, 2, time.Hour + time.Nanosecond, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if e := r.Put(ctx, "inflight", []byte("protected")); e != nil {
t.Fatal(e)
}
id, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: "h1", Keys: []string{"inflight"}})
if e != nil {
t.Fatal(e)
}
ins, e := r.ListIntents(ctx)
if e != nil || len(ins) != 1 {
t.Fatalf("intent: %+v %v", ins, e)
}
*now = time.Unix(0, ins[0].CreatedNs).Add(tc.age)
// A real remote HEAD fence. The publisher's original expected version
// can no longer install after epoch 2 was published.
cur, e := r.GetHead(ctx)
if e != nil {
t.Fatal(e)
}
old := storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}
if _, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: tc.head, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); e != nil {
t.Fatal(e)
}
g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) {
if tc.authorityErr {
return 0, errors.New("authority unavailable")
}
return tc.issued, nil
}
result, e := g.Run(ctx)
if e != nil {
t.Fatal(e)
}
ins, e = r.ListIntents(ctx)
if e != nil {
t.Fatal(e)
}
if (len(ins) == 0) != tc.expire {
t.Fatalf("intent %s expired=%v want=%v; %+v", id, len(ins) == 0, tc.expire, result)
}
if result.Reclaimed != 0 {
t.Fatal("one mark reclaimed bytes")
}
if tc.expire {
_, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: 1, Holder: "h1"})
if !errors.Is(e, storage.ErrChunkHeadPrecondition) {
t.Fatalf("expired publisher can still CAS: %v", e)
}
}
})
}
}
type failingGCListing struct {
Filer
fail bool
}
func (f *failingGCListing) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) {
if f.fail {
return nil, errors.New("listing unavailable")
}
return f.Filer.ListEntries(ctx, dir, prefix, after, limit)
}
func TestGC_FailedMarkAndRestartNeverReuseCoverage(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil {
t.Fatal(e)
}
wrapper := &failingGCListing{Filer: f}
c.f = wrapper
if _, e := g.Run(ctx); e != nil {
t.Fatal(e)
}
*now = now.Add(2 * time.Hour)
wrapper.fail = true
if _, e := g.Run(ctx); e == nil {
t.Fatal("failed listing accepted")
}
wrapper.fail = false
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("failed mark preserved coverage: %+v %v", result, e)
}
fresh, e := NewCollector(c, b, g.cfg)
if e != nil {
t.Fatal(e)
}
*now = now.Add(2 * time.Hour)
if result, e := fresh.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("restart inferred prior mark: %+v %v", result, e)
}
}
func TestGC_SnapshotAndQualifiedForkAreRoots(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x21)})
if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil {
t.Fatal(e)
}
if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil {
t.Fatal(e)
}
if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); e != nil {
t.Fatal(e)
}
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", Chunks: map[uint64]storage.ChunkRef{}}); e != nil {
t.Fatal(e)
}
for i := 0; i < 2; i++ {
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("rooted data reclaimed: %+v %v", result, e)
}
*now = now.Add(2 * time.Hour)
}
for _, ref := range h.Chunks {
if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x21)) {
t.Fatalf("shared bytes: %v", e)
}
}
}
func TestGC_CopyIntentSurvivesTakeover(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
for _, holder := range []string{"snapshot:v1/s1/req", "fork:v1/req"} {
if _, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: holder, Keys: []string{"k"}}); e != nil {
t.Fatal(e)
}
}
cur, e := r.GetHead(ctx)
if e != nil {
t.Fatal(e)
}
if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new"}); e != nil {
t.Fatal(e)
}
g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil }
*now = now.Add(24 * time.Hour)
if result, e := g.Run(ctx); e != nil || result.ExpiredIntents != 0 {
t.Fatalf("epochless copy publication lost its protection: %+v %v", result, e)
}
intents, e := r.ListIntents(ctx)
if e != nil || len(intents) != 2 {
t.Fatalf("copy intents: %+v %v", intents, e)
}
}
func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) {
for _, status := range []int{200, 204, 404, 401, 500} {
t.Run(http.StatusText(status), func(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != "DELETE" || r.URL.Path != "/7,01abcdef" {
t.Errorf("unexpected delete %s %s", r.Method, r.URL.Path)
}
w.WriteHeader(status)
}))
defer server.Close()
c := &SWFS{http: server.Client(), vidCache: map[string][]string{"7": {strings.TrimPrefix(server.URL, "http://")}}}
e := c.DeleteBlob(context.Background(), "7,01abcdef")
if (e == nil) != (status == 200 || status == 204 || status == 404) {
t.Fatalf("status %d: %v", status, e)
}
if calls != 1 {
t.Fatalf("calls %d", calls)
}
for _, bad := range []string{"7,../bad", "7,a?bad", "7,a%2fb", "", ",a"} {
if e := c.DeleteBlob(context.Background(), bad); e == nil {
t.Errorf("invalid fid accepted: %q", bad)
}
}
if calls != 1 {
t.Fatal("invalid fid dispatched HTTP")
}
})
}
}
func TestGC_UnboundNeedleRetainedAndCountUnknown(t *testing.T) {
_, b, _, g, now := gcFixture(t)
ctx := context.Background()
fid, e := b.Put(ctx, []byte("pre-binding orphan"))
if e != nil {
t.Fatal(e)
}
for i := 0; i < 3; i++ {
result, e := g.Run(ctx)
if e != nil || !result.UnknownUnbound || result.Reclaimed != 0 {
t.Fatalf("unbound inventory claim: %+v %v", result, e)
}
*now = now.Add(2 * time.Hour)
}
if got, e := b.Get(ctx, fid); e != nil || string(got) != "pre-binding orphan" {
t.Fatalf("unbound orphan deleted: %q %v", got, e)
}
}
@@ -319,3 +319,32 @@ var (
_ Filer = (*SWFS)(nil)
_ Blobs = (*SWFS)(nil)
)
// DeleteBlob removes an immutable needle from every resolved replica. A
// partial/unknown result is an error, so GC retains its binding tombstone
// and retries later; no response body is used to infer success.
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)
if err != nil {
return err
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
}
}
return nil
}