Merge pull request #142 from seaweedfs/feat/chunk-retention

chunkstore: snapshot retention and space accounting (part 1)
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-15 16:47:14 -08:00
commit 9c29ee9c42
16 files changed
+2596 -28

No files matched your search

+31 -7
View File
@@ -44,7 +44,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) {
func runOpsChunk(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc", false)
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain", false)
}
switch args[0] {
case "gc":
@@ -63,6 +63,10 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int {
return chunkFork(args[1:], stdout, stderr)
case "show":
return chunkShow(args[1:], stdout, stderr)
case "usage":
return chunkUsage(args[1:], stdout, stderr)
case "retain":
return chunkRetain(args[1:], stdout, stderr)
default:
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false)
}
@@ -170,9 +174,10 @@ func chunkCut(args []string, stdout, stderr io.Writer) int {
func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("snapshot", stderr)
var (
volumeID, statusAddr, name, requestID, consistency string
expiresAtNs int64
timeout time.Duration
volumeID, statusAddr, name, requestID, consistency, class string
expiresAtNs int64
timeout, expires time.Duration
pin bool
)
labels := labelFlags{}
fs.StringVar(&volumeID, "volume", "", "volume id")
@@ -180,7 +185,10 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
fs.StringVar(&name, "name", "", "snapshot name")
fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)")
fs.StringVar(&consistency, "consistency", "crash", "crash, or app when the guest was frozen by the caller")
fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "stored for the retention policy; not enforced here")
fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "pins the snapshot until this time (unix ns); retention expires it afterwards")
fs.DurationVar(&expires, "expires", 0, "pins the snapshot for this long from now (sets --expires-at-ns)")
fs.StringVar(&class, "class", "", "retention class: semantic (an automatic checkpoint, expired by the policy) or pinned (kept until deleted)")
fs.BoolVar(&pin, "pin", false, "shorthand for --class pinned")
fs.Var(labels, "label", "key=value label (repeatable)")
fs.DurationVar(&timeout, "timeout", 60*time.Second, "operation bound (capped at the server's OpDeadline)")
if err := fs.Parse(args); err != nil {
@@ -189,12 +197,28 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
if volumeID == "" || statusAddr == "" || name == "" {
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume, --status-addr and --name are required", false)
}
if pin {
if class != "" && class != chunkstore.SnapshotClassPinned {
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--pin conflicts with --class "+class, false)
}
class = chunkstore.SnapshotClassPinned
}
if expires < 0 || expires > 0 && expiresAtNs != 0 {
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--expires must be positive and does not combine with --expires-at-ns", false)
}
if expires > 0 {
expiresAtNs = time.Now().Add(expires).UnixNano()
}
if requestID == "" {
requestID = newRequestID()
fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s (reuse it to retry)\n", requestID)
}
return chunkPost("snapshot", statusAddr, "/chunk/snapshot", timeout, map[string]any{"volumeID": volumeID, "name": name,
"requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs}, stdout, stderr)
body := map[string]any{"volumeID": volumeID, "name": name,
"requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs}
if class != "" {
body["class"] = class // only when set: the request otherwise keeps its spec fields
}
return chunkPost("snapshot", statusAddr, "/chunk/snapshot", timeout, body, stdout, stderr)
}
func chunkDetach(args []string, stdout, stderr io.Writer) int {
+127
View File
@@ -0,0 +1,127 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
)
// chunkUsage: sw-block ops chunk usage --volume v --chunk-filer host:port
// prints the volume's space accounting and retention policy (from
// manifests and filer listings; no chunk data reads).
func chunkUsage(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("usage", stderr)
var (
volumeID, filer, base string
timeout time.Duration
)
fs.StringVar(&volumeID, "volume", "", "volume id")
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
fs.DurationVar(&timeout, "timeout", 60*time.Second, "filer timeout")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if volumeID == "" {
return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false)
}
cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr)
if exit >= 0 {
return exit
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
u, err := cat.Usage(ctx, volumeID)
return chunkResult("usage", u, err, stdout, stderr)
}
// chunkRetain: sw-block ops chunk retain --volume v --chunk-filer host:port
// [--dry-run] applies the volume's retention policy (deletes the expired
// snapshots; GC reclaims their chunks). With --set-policy it stores the
// policy given by the --keep-* flags on the VOLUME entry instead.
func chunkRetain(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("retain", stderr)
var (
volumeID, filer, base string
timeout, keepYounger time.Duration
dryRun, setPolicy bool
keepNewest, keepHourly, keepDaily, keepWeekly int
)
fs.StringVar(&volumeID, "volume", "", "volume id")
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
fs.DurationVar(&timeout, "timeout", 5*time.Minute, "bound for this pass")
fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing")
fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it")
fs.IntVar(&keepNewest, "keep-newest", chunkstore.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots")
fs.DurationVar(&keepYounger, "keep-younger", chunkstore.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this")
fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours")
fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days")
fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if volumeID == "" || timeout <= 0 {
return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required and --timeout must be positive", false)
}
if setPolicy && dryRun {
return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false)
}
cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr)
if exit >= 0 {
return exit
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if setPolicy {
p := chunkstore.RetentionPolicy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly}
if err := cat.SetRetentionPolicy(ctx, volumeID, p); err != nil {
return chunkResult("retain", nil, err, stdout, stderr)
}
return chunkResult("retain", map[string]any{"volumeID": volumeID, "policy": p, "policySet": true}, nil, stdout, stderr)
}
res, err := cat.Retain(ctx, volumeID, dryRun)
if err != nil && res.VolumeID != "" {
// The pass stopped part way: report what it did (confirmed
// deletions, the failing snapshot with whether its outcome is
// uncertain, what it never reached) with the error, and fail.
return retainPartial(res, err, stdout, stderr)
}
return chunkResult("retain", res, err, stdout, stderr)
}
// retainOutput is a retention result together with the error that
// stopped it.
type retainOutput struct {
chunkstore.RetentionResult
Error *chunkErrBody `json:"error,omitempty"`
}
func retainPartial(res chunkstore.RetentionResult, err error, stdout, stderr io.Writer) int {
body := chunkErrBody{Code: chunkstore.CodeOf(err), Message: err.Error(), Retryable: true}
var ce *chunkstore.CatalogError
if errors.As(err, &ce) {
body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable}
}
if body.Code == "" {
body.Code = codeInternalCLI
}
fmt.Fprintf(stderr, "sw-block ops chunk retain: %s: %s (deleted %d, not attempted %d)\n", body.Code, body.Message, len(res.Deleted), len(res.NotAttempted))
out, mErr := json.Marshal(retainOutput{RetentionResult: res, Error: &body})
if mErr != nil {
fmt.Fprintf(stderr, "sw-block ops chunk retain: %v\n", mErr)
return chunkExitFailed
}
if wErr := writeAll(stdout, append(out, '\n')); wErr != nil {
fmt.Fprintf(stderr, "sw-block ops chunk retain: write the result: %v\n", wErr)
}
return chunkExitFailed
}
@@ -0,0 +1,97 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// failingFiler fails the UpdateEntry calls fail picks, after or before
// applying them.
type failingFiler struct {
*chunkstore.MemFiler
fail func(dir, name string) bool
afterApply bool
}
func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
if f.fail != nil && f.fail(dir, e.GetName()) {
if f.afterApply {
if err := f.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil {
return err
}
return errors.New("response lost")
}
return errors.New("filer unavailable")
}
return f.MemFiler.UpdateEntry(ctx, dir, e, expected)
}
// retain that fails part way prints what it confirmed, the failing
// snapshot (uncertain) and what it never reached, with the error, and
// exits nonzero; a lost response is finished by the next run.
func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) {
ctx := context.Background()
ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()}
prev := dialChunkFiler
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil }
t.Cleanup(func() { dialChunkFiler = prev })
cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI)
if err != nil {
t.Fatal(err)
}
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
t.Fatal(err)
}
base := time.Now().Add(-48 * time.Hour)
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
for i := 0; i < 4; i++ {
at := base.Add(time.Duration(i) * time.Minute)
cat.SetClock(func() time.Time { return at })
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i)}, head); err != nil {
t.Fatal(err)
}
}
filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"}
if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "0", "--keep-younger", "0s"}, filer...)...); code != 0 {
t.Fatalf("set policy: %d %q %q", code, out, errs)
}
// Expired newest first: s3, s2, s1, s0. The mark of s2 fails.
ff.fail = func(dir, _ string) bool { return strings.HasSuffix(dir, "/snaps/s2") }
type partial struct {
chunkstore.RetentionResult
Error *chunkErrBody `json:"error"`
}
code, out, errs := runChunk(append([]string{"retain"}, filer...)...)
var p partial
if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Error == nil || p.Failed == nil {
t.Fatalf("failing retain: exit %d %q %q; want nonzero with the partial result", code, out, errs)
}
if strings.Join(p.Deleted, ",") != "s3" || p.Failed.Name != "s2" || !p.Failed.Uncertain || strings.Join(p.NotAttempted, ",") != "s1,s0" {
t.Fatalf("partial result: %+v", p)
}
if !strings.Contains(errs, "deleted 1, not attempted 2") {
t.Fatalf("stderr %q; want the counts", errs)
}
ff.afterApply = true // the mark lands, its response is lost
code, out, _ = runChunk(append([]string{"retain"}, filer...)...)
if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Failed == nil || p.Failed.Name != "s2" || !p.Failed.Uncertain {
t.Fatalf("lost response: exit %d %q", code, out)
}
ff.fail = nil
code, out, errs = runChunk(append([]string{"retain"}, filer...)...)
var done chunkstore.RetentionResult
if code != 0 || json.Unmarshal([]byte(out), &done) != nil || strings.Join(done.Deleted, ",") != "s1,s0,s2" {
t.Fatalf("rerun: %d %q %q; want s1, s0 and the half-deleted s2", code, out, errs)
}
}
@@ -0,0 +1,90 @@
package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// snapshot --pin / --class / --expires send the retention class and the
// expiry; conflicting flags are refused before any request.
func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) {
srv, got := chunkServer(t, 200, `{"volumeID":"v1","name":"s1"}`)
before := time.Now()
if code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "r", "--pin", "--expires", "1h"); code != 0 {
t.Fatalf("snapshot --pin --expires: %d %q", code, errs)
}
body := (*got)[0].body
exp, _ := body["expiresAtNs"].(float64)
if body["class"] != chunkstore.SnapshotClassPinned || exp < float64(before.Add(time.Hour).UnixNano())-1e9 {
t.Fatalf("pinned request: %+v", body)
}
for _, args := range [][]string{
{"--pin", "--class", "semantic"},
{"--expires", "1h", "--expires-at-ns", "5"},
{"--expires", "-1s"},
} {
a := append([]string{"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s2"}, args...)
if code, out, _ := runChunk(a...); code == 0 || !strings.Contains(out, codeBadRequestCLI) {
t.Fatalf("snapshot %v: exit %d %q; want a bad request", args, code, out)
}
}
if len(*got) != 1 {
t.Fatalf("refused flags still sent requests: %d", len(*got))
}
}
// usage and retain run catalog-direct against the filer: set a policy,
// dry-run, apply, and see the accounting follow.
func TestOpsChunk_UsageAndRetain(t *testing.T) {
ctx := context.Background()
mem := chunkstore.NewMemFiler()
prev := dialChunkFiler
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
t.Cleanup(func() { dialChunkFiler = prev })
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
if err != nil {
t.Fatal(err)
}
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
t.Fatal(err)
}
old := time.Now().Add(-48 * time.Hour)
cat.SetClock(func() time.Time { return old })
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
for i := 0; i < 5; i++ {
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil {
t.Fatal(err)
}
}
filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"}
if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "2", "--keep-younger", "1m"}, filer...)...); code != 0 || !strings.Contains(out, `"policySet":true`) {
t.Fatalf("set policy: %d %q %q", code, out, errs)
}
code, out, errs := runChunk(append([]string{"retain", "--dry-run"}, filer...)...)
var dry chunkstore.RetentionResult
if code != 0 || json.Unmarshal([]byte(out), &dry) != nil || !dry.DryRun || dry.Expired != 3 || len(dry.Deleted) != 0 {
t.Fatalf("dry run: %d %q %q", code, out, errs)
}
code, out, errs = runChunk(append([]string{"retain"}, filer...)...)
var applied chunkstore.RetentionResult
if code != 0 || json.Unmarshal([]byte(out), &applied) != nil || len(applied.Deleted) != 3 || applied.Kept != 2 {
t.Fatalf("retain: %d %q %q", code, out, errs)
}
code, out, errs = runChunk(append([]string{"usage"}, filer...)...)
var u chunkstore.VolumeUsage
if code != 0 || json.Unmarshal([]byte(out), &u) != nil || len(u.Snapshots) != 2 || u.Policy.KeepNewest != 2 || !u.PolicySet {
t.Fatalf("usage: %d %q %q", code, out, errs)
}
if code, out, _ := runChunk("retain", "--volume", "v1", "--chunk-filer", "f:1", "--set-policy", "--dry-run"); code == 0 || !strings.Contains(out, codeBadRequestCLI) {
t.Fatalf("--set-policy --dry-run: %d %q; want a bad request", code, out)
}
}
+119 -18
View File
@@ -35,6 +35,8 @@ import (
"strings"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -196,6 +198,9 @@ type snapDoc struct {
Parent *Parent `json:"parent"`
Labels map[string]string `json:"labels"`
ExpiresAtNs int64 `json:"expires_at_ns"`
// Class is the retention class: "semantic", "pinned", or "" for a
// snapshot made before classes existed (see retention.go).
Class string `json:"class,omitempty"`
}
// SnapshotInfo describes one snapshot, with the field names of the HTTP API
@@ -215,6 +220,9 @@ type SnapshotInfo struct {
Parent *Parent `json:"parent"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Replayed bool `json:"replayed"`
Class string `json:"class"`
attempt string // the attempt the name resolved to, when read by name
head storage.ChunkHead
geo Geometry
@@ -231,6 +239,9 @@ type SnapshotRequest struct {
Consistency string // "crash" (default) or "app"
ExpiresAtNs int64
CreatedBy string
// Class is the retention class: "semantic" or "pinned" ("" leaves it
// unset, which retention treats as unpinned).
Class string
// SourceReadAt is when the caller obtained the HEAD it snapshots (the
// cut's return); OpDeadline counts from it. Zero means now.
SourceReadAt time.Time
@@ -275,6 +286,9 @@ type Catalog struct {
// OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero).
OpDeadline time.Duration
now func() time.Time
// retainHook, when set, runs at the named stages of a Retain pass (a
// test seam for interleavings; see hookPlanned).
retainHook func(stage, name string)
}
// NewCatalog returns the catalog for the chunk base directory base (the
@@ -599,6 +613,7 @@ func (c *Catalog) resolveSnap(ctx context.Context, vol, name string) (snapRef, b
if err != nil {
return snapRef{}, false, err
}
info.attempt = rec.Attempt
ref.entry, ref.info = e, info
return ref, true, nil
}
@@ -651,7 +666,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) {
VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN,
CreatedNs: doc.CreatedNs, State: state, ChunkCount: len(head.Chunks), ManifestBytes: len(e.GetContent()),
Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs,
head: head, geo: doc.Geometry,
Class: doc.Class, head: head, geo: doc.Geometry,
}, doc.RequestID, nil
}
@@ -801,6 +816,9 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
if consistency == "" {
consistency = "crash"
}
if err := ValidateSnapshotClass(req.Class); err != nil {
return SnapshotInfo{}, err
}
if head.Gen == 0 {
return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no published HEAD to snapshot", vol)
}
@@ -824,7 +842,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
}
doc := snapDoc{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, CreatedNs: c.now().UnixNano(),
CreatedBy: req.CreatedBy, Consistency: consistency, Head: headEnt.Content, Geometry: v.Geometry, Parent: v.Parent,
Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs}
Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs, Class: req.Class}
body, err := json.Marshal(doc)
if err != nil {
return SnapshotInfo{}, err
@@ -1035,18 +1053,17 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string,
}
continue // re-read: the path now holds a tombstone or the late snapshot
case ref.info.State == SnapActive:
e := ref.entry
e.Extended[extSnapState] = []byte(SnapDeleting)
e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10))
err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{
extSnapState: []byte(SnapActive),
extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)),
})
if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) {
continue
}
// The one mark path shared with retention: a live fork claim
// refuses (claude05's ruling, 23:58Z).
m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt)
if err != nil {
return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name)
return "", err
}
switch m {
case markClaimed:
return "", claimedErr(vol, name, live)
case markGone:
continue
}
}
// The attempt is deleting or aborted: free the name.
@@ -1150,14 +1167,14 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
}
}
// Claim the parent before using it (review of #142): one conditional
// write on the parent attempt's entry, which retention's delete mark
// is conditioned against (see retention.go).
readAt := c.now()
snap, err := c.readSnap(ctx, req.Source, req.Snapshot)
snap, err := c.claimForkParent(ctx, req)
if err != nil {
return ForkResult{}, err
}
if snap.State == SnapDeleting {
return ForkResult{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot)
}
if snap.geo == (Geometry{}) {
return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot)
}
@@ -1245,15 +1262,99 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
return ForkResult{}, err
}
if h.State == storage.ChunkHeadAborted {
c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands
c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands
c.dropForkClaim(ctx, req, snap.attempt) // and this fork never needs the parent again
return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target)
}
if outcome != createUnsettled {
c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good
}
c.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it
return forkResult(existing, outcome != createdNow), nil
}
// claimForkParent adds fork req's claim to the parent attempt its
// snapshot name resolves to, conditioned on the entry being active with
// the claims read, and returns that snapshot. A parent deleting is
// refused (snapshot_deleting); a claim already there is reused.
func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) {
root, err := c.volRoot(req.Source)
if err != nil {
return SnapshotInfo{}, err
}
token := forkClaim(req.Target, req.RequestID)
dir := path.Join(root, snapsDir, req.Snapshot)
for try := 0; try < 5; try++ {
ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot)
if err != nil {
return SnapshotInfo{}, err
}
if !ok || ref.entry == nil || ref.info.State == SnapAborted {
return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot)
}
if ref.info.State == SnapDeleting {
return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot)
}
claims := decodeClaims(ref.entry)
for _, cl := range claims {
if cl == token {
return ref.info, nil
}
}
raw := ref.entry.Extended[extSnapClaims]
next := proto.Clone(ref.entry).(*filerpb.Entry)
setClaims(next, append(claims, token))
err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: raw})
if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) {
continue // a mark, another claim or a delete landed: read again
}
if err != nil {
// The claim may have landed; a retry finds and reuses it.
return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, err, "fork %s: claim on %s/%s outcome unknown; retry with the same request id", req.Target, req.Source, req.Snapshot)
}
return ref.info, nil
}
return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot)
}
// dropForkClaim removes fork req's claim from its parent attempt once the
// fork no longer needs it (best effort: retention treats a claim whose
// target has a HEAD as dead anyway).
func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt string) {
root, err := c.volRoot(req.Source)
if err != nil || attempt == "" {
return
}
token := forkClaim(req.Target, req.RequestID)
dir := path.Join(root, snapsDir, req.Snapshot)
for try := 0; try < 3; try++ {
e, err := c.f.LookupEntry(ctx, dir, attempt)
if err != nil {
return
}
claims := decodeClaims(e)
kept := claims[:0:0]
for _, cl := range claims {
if cl != token {
kept = append(kept, cl)
}
}
if len(kept) == len(claims) {
return
}
c.hook(hookClaimDrop, req.Snapshot)
// Conditioned on the state read too (review of f42e723): a
// delete that marked the entry meanwhile must never be undone by
// this stale copy. A lost condition re-reads a fresh copy.
raw := e.Extended[extSnapClaims]
next := proto.Clone(e).(*filerpb.Entry)
setClaims(next, kept)
if err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}); !errors.Is(err, ErrPrecondition) {
return
}
}
}
// AbortFork settles a dead fork for a GC sweep (W5 ruling, 2026-11-15
// 17:30Z): it claims the target's HEAD, the fork's publishing entry, with
// an exclusive create of an aborted HEAD tombstone. claimed is true when
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"errors"
"path"
"sort"
"strings"
"testing"
@@ -166,6 +167,22 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) {
t.Fatalf("request id reused for another snapshot: %v, want target_exists", err)
}
// The fork claims s1, so an explicit delete is refused (claude05's
// ruling, 2026-11-15 23:58Z). The image binding below still guards a
// fork made before claims existed: drop the claim as such a fork would
// never have written one.
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); CodeOf(err) != CodeSnapshotClaimed {
t.Fatalf("delete of a claimed parent: %v, want snapshot_claimed", err)
}
ref, _, err := c.resolveSnap(ctx, "v1", "s1")
if err != nil || ref.entry == nil {
t.Fatalf("read s1: %v", err)
}
delete(ref.entry.Extended, extSnapClaims)
if err := f.UpdateEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), ref.entry, nil); err != nil {
t.Fatal(err)
}
// s1 is deleted and recreated over a newer source image.
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name
t.Fatal(err)
@@ -0,0 +1,653 @@
package chunkstore
import (
"context"
"encoding/json"
"errors"
"fmt"
"path"
"sort"
"strconv"
"strings"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Snapshot retention (claude05's rulings, 2026-11-15 22:53Z).
//
// A snapshot has a class, stored with it:
// - "semantic": an automatic checkpoint (e.g. an agent's per-step
// checkpoint). Governed by count, age and the log-spaced keeps.
// - "pinned": an explicit keep. It is never expired by count or age,
// only by its own ExpiresAtNs or an explicit delete. A snapshot with
// ExpiresAtNs set is pinned whatever its class.
// - "" (snapshots made before classes existed): treated as unpinned.
//
// The policy is stored on the VOLUME entry. Retain keeps
//
// newest KeepNewest unpinned
// + every pinned snapshot not yet past its ExpiresAtNs
// + every snapshot younger than KeepYounger (a creation time in the
// future, from clock skew, counts as young)
// + the log-spaced keeps (below)
// + every snapshot a fork still needs
//
// and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs
// is treated as unpinned. GC reclaims the chunks.
//
// Log-spaced keeps use rolling windows anchored at now: window k of a
// period P holds the snapshots whose age is in [k*P, (k+1)*P). For
// KeepHourly = H, the newest snapshot of each of windows 0..H-1 is kept
// (likewise daily and weekly). So at 10:30 with KeepHourly = 1 only the
// newest snapshot of 09:30..10:30 is kept, not one per clock hour.
//
// Deletion is bound to the exact attempt planned (review of #142): the
// attempt's own entry is marked deleting conditionally, and the name
// record is removed only while it still names that attempt, so a
// same-name replacement made after planning is never touched.
//
// Fork parents (codex01's design, review of #142 round 2). Protection is
// one conditional write on the parent attempt's own entry, nothing else:
//
// - Fork, before it reads the parent, adds its claim (target/request)
// to the entry's claims, conditioned on {state active, claims as read}.
// A parent already deleting is refused.
// - Retain marks an attempt deleting only conditioned on {state active,
// gen, no claims}. A lost condition re-reads and decides again.
//
// The two writes hit the same entry, so one of them sees the other: either
// the claim landed first and retain keeps the snapshot (fork_held), or the
// mark landed first and the fork refuses before installing anything.
//
// A claim is removed by the fork once its HEAD is installed. Retain removes
// (conditionally) only claims that can never matter again: the target has
// a HEAD (the fork completed, or a sweep aborted it), or the target's
// VOLUME belongs to another request (this one can never publish there).
// Any other claim keeps the snapshot, however old: a fork that died before
// publishing its VOLUME holds it until the fork is retried to completion or
// settled by AbortFork. Forks published before claims existed are still
// found by the fork-record scan (forkParentsNeeded).
//
// An explicit DeleteSnapshot goes through the same check and mark
// (markDeleting): it refuses a live claim with snapshot_claimed.
//
// A pass stopped after a mark (e.g. a lost response) leaves the attempt
// deleting with its name still held; the next pass (and its dry run) lists
// it and frees the name. A deleting attempt cannot gain claims.
const (
SnapshotClassSemantic = "semantic"
SnapshotClassPinned = "pinned"
CodeInvalidClass = "invalid_class"
CodeInvalidPolicy = "invalid_policy"
// CodeSnapshotClaimed: an explicit delete of a snapshot a fork still
// claims (claude05's ruling, 23:58Z). Not retryable as such: it clears
// when the fork publishes its HEAD or is aborted.
CodeSnapshotClaimed = "snapshot_claimed"
DefaultKeepNewest = 10
DefaultKeepYounger = time.Hour
extRetention = "retention"
extRetentionRev = "retention_rev"
extSnapClaims = "swb.snap.claims"
)
// ValidateSnapshotClass refuses a class other than "", "semantic" and
// "pinned" (invalid_class).
func ValidateSnapshotClass(class string) error {
switch class {
case "", SnapshotClassSemantic, SnapshotClassPinned:
return nil
}
return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned)
}
// Pinned reports whether the snapshot is an explicit keep.
func (s SnapshotInfo) Pinned() bool {
return s.Class == SnapshotClassPinned || s.ExpiresAtNs > 0
}
// RetentionPolicy is a volume's snapshot retention policy.
type RetentionPolicy struct {
KeepNewest int `json:"keepNewest"`
KeepYoungerNs int64 `json:"keepYoungerNs"`
KeepHourly int `json:"keepHourly"`
KeepDaily int `json:"keepDaily"`
KeepWeekly int `json:"keepWeekly"`
}
// DefaultRetentionPolicy is the policy of a volume that never set one.
func DefaultRetentionPolicy() RetentionPolicy {
return RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger)}
}
func (p RetentionPolicy) validate() error {
if p.KeepNewest < 0 || p.KeepYoungerNs < 0 || p.KeepHourly < 0 || p.KeepDaily < 0 || p.KeepWeekly < 0 {
return catErr(CodeInvalidPolicy, false, nil, "retention policy %+v: counts and durations must not be negative", p)
}
return nil
}
// ReadRetentionPolicy returns vol's policy; set is false (and the policy
// is DefaultRetentionPolicy) when none was ever set.
func (c *Catalog) ReadRetentionPolicy(ctx context.Context, vol string) (RetentionPolicy, bool, error) {
e, _, err := c.volumeEntry(ctx, vol)
if err != nil {
return RetentionPolicy{}, false, err
}
return decodeRetention(e)
}
func decodeRetention(e *filerpb.Entry) (RetentionPolicy, bool, error) {
raw := e.Extended[extRetention]
if len(raw) == 0 {
return DefaultRetentionPolicy(), false, nil
}
var p RetentionPolicy
if err := json.Unmarshal(raw, &p); err != nil {
return RetentionPolicy{}, false, catErr(CodeInvalidPolicy, false, err, "stored retention policy is unreadable")
}
return p, true, nil
}
// volumeEntry reads vol's VOLUME entry; a volume without one is
// not_chunk_volume.
func (c *Catalog) volumeEntry(ctx context.Context, vol string) (*filerpb.Entry, string, error) {
root, err := c.volRoot(vol)
if err != nil {
return nil, "", err
}
e, err := c.f.LookupEntry(ctx, root, volumeName)
if errors.Is(err, ErrNotFound) {
return nil, "", catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol)
}
if err != nil {
return nil, "", remoteErr(err, "read VOLUME of %s", vol)
}
return e, root, nil
}
// SetRetentionPolicy stores p on vol's VOLUME entry. Only the policy's
// extended attributes change; the volume document is untouched. The update
// is conditional on the policy revision read, so of two concurrent setters
// one wins and the other gets a retryable remote error.
func (c *Catalog) SetRetentionPolicy(ctx context.Context, vol string, p RetentionPolicy) error {
if err := p.validate(); err != nil {
return err
}
e, root, err := c.volumeEntry(ctx, vol)
if err != nil {
return err
}
rev := string(e.Extended[extRetentionRev])
n, _ := strconv.ParseUint(rev, 10, 64)
body, err := json.Marshal(p)
if err != nil {
return err
}
next := proto.Clone(e).(*filerpb.Entry)
if next.Extended == nil {
next.Extended = map[string][]byte{}
}
next.Extended[extRetention] = body
next.Extended[extRetentionRev] = []byte(strconv.FormatUint(n+1, 10))
if err := c.f.UpdateEntry(ctx, root, next, map[string][]byte{extRetentionRev: []byte(rev)}); err != nil {
return remoteErr(err, "set the retention policy of %s", vol)
}
return nil
}
// RetentionDecision is one snapshot's fate under a policy.
type RetentionDecision struct {
Name string `json:"name"`
Attempt string `json:"attempt"`
CreatedNs int64 `json:"createdNs"`
Class string `json:"class"`
Pinned bool `json:"pinned"`
Keep bool `json:"keep"`
Reasons []string `json:"reasons"` // why it is kept; "expired" when it goes
}
// The reasons a snapshot is kept.
const (
keepNewest = "newest"
keepPinned = "pinned"
keepYoung = "younger_than_policy"
keepHourly = "hourly"
keepDaily = "daily"
keepWeekly = "weekly"
keepForkParent = "fork_parent"
reasonExpired = "expired"
)
// planRetention decides, from one listing, which snapshots policy keeps at
// now. needed names the snapshots a fork still needs. Unpinned snapshots
// are ranked newest first; equal creation times rank by name, so the plan
// is deterministic.
func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision {
ordered := append([]SnapshotInfo(nil), snaps...)
sort.SliceStable(ordered, func(i, j int) bool {
if ordered[i].CreatedNs != ordered[j].CreatedNs {
return ordered[i].CreatedNs > ordered[j].CreatedNs
}
return ordered[i].Name < ordered[j].Name
})
nowNs := now.UnixNano()
out := make([]RetentionDecision, len(ordered))
unpinned := 0
windows := map[string]bool{}
for i, s := range ordered {
pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs)
d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned}
if pinned {
d.Reasons = append(d.Reasons, keepPinned)
} else {
if unpinned < p.KeepNewest {
d.Reasons = append(d.Reasons, keepNewest)
}
unpinned++
}
age := time.Duration(nowNs - s.CreatedNs)
if age < time.Duration(p.KeepYoungerNs) {
d.Reasons = append(d.Reasons, keepYoung)
}
for _, lk := range []struct {
reason string
period time.Duration
count int
}{
{keepHourly, time.Hour, p.KeepHourly},
{keepDaily, 24 * time.Hour, p.KeepDaily},
{keepWeekly, 7 * 24 * time.Hour, p.KeepWeekly},
} {
if lk.count <= 0 || age < 0 {
continue
}
k := int64(age / lk.period) // the rolling window holding this age
if k >= int64(lk.count) {
continue
}
key := fmt.Sprintf("%s/%d", lk.reason, k)
if !windows[key] { // ordered newest first: the first seen is the window's newest
windows[key] = true
d.Reasons = append(d.Reasons, lk.reason)
}
}
if needed[s.Name] {
d.Reasons = append(d.Reasons, keepForkParent)
}
d.Keep = len(d.Reasons) > 0
if !d.Keep {
d.Reasons = []string{reasonExpired}
}
out[i] = d
}
return out
}
// RetentionFailure is the deletion that stopped a Retain pass.
type RetentionFailure struct {
Name string `json:"name"`
Attempt string `json:"attempt"`
Code string `json:"code"`
Message string `json:"message"`
// Uncertain is set when the failing call was a mutation whose outcome
// is unknown (e.g. the response was lost): the snapshot may or may
// not be marked deleting. It is false when the pass failed before
// changing anything for this snapshot.
Uncertain bool `json:"uncertain"`
}
// RetentionResult is the outcome of one Retain pass.
type RetentionResult struct {
VolumeID string `json:"volumeID"`
Policy RetentionPolicy `json:"policy"`
PolicySet bool `json:"policySet"`
DryRun bool `json:"dryRun"`
Decisions []RetentionDecision `json:"decisions"`
Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run)
Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone
ForkHeld []string `json:"forkHeld"` // planned, but a fork took a hold meanwhile: kept
Failed *RetentionFailure `json:"failed,omitempty"`
// NotAttempted lists the expired snapshots not reached because the
// pass stopped at Failed.
NotAttempted []string `json:"notAttempted"`
Kept int `json:"kept"`
Expired int `json:"expired"`
}
// Retain applies vol's retention policy at the catalog clock's now. A dry
// run plans and writes nothing. Otherwise each expired snapshot's planned
// attempt is deleted (deleteRetainedAttempt). The first failure stops the
// pass; the result then still reports every confirmed deletion, the
// failure (with whether its outcome is uncertain), and what was not
// attempted, together with the error.
func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (RetentionResult, error) {
e, _, err := c.volumeEntry(ctx, vol)
if err != nil {
return RetentionResult{}, err
}
p, set, err := decodeRetention(e)
if err != nil {
return RetentionResult{}, err
}
listed, err := c.listSnapshots(ctx, vol, true)
if err != nil {
return RetentionResult{}, err
}
var snaps, unfinished []SnapshotInfo
for _, s := range listed {
if s.State == SnapDeleting {
unfinished = append(unfinished, s) // a pass stopped after its mark
} else {
snaps = append(snaps, s)
}
}
needed, err := c.forkParentsNeeded(ctx, vol)
if err != nil {
return RetentionResult{}, err
}
res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun,
Deleted: []string{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}}
res.Decisions = planRetention(p, snaps, needed, c.now())
var expired []RetentionDecision
for _, d := range res.Decisions {
if d.Keep {
res.Kept++
continue
}
res.Expired++
expired = append(expired, d)
}
for _, s := range unfinished {
d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Reasons: []string{SnapDeleting}}
res.Decisions = append(res.Decisions, d)
res.Expired++
expired = append(expired, d)
}
if dryRun {
return res, nil
}
c.hook(hookPlanned, "")
for i, d := range expired {
outcome, uncertain, err := c.deleteRetainedAttempt(ctx, vol, d.Name, d.Attempt)
if err != nil {
res.Failed = &RetentionFailure{Name: d.Name, Attempt: d.Attempt, Code: codeOrRemote(err), Message: err.Error(), Uncertain: uncertain}
for _, rest := range expired[i+1:] {
res.NotAttempted = append(res.NotAttempted, rest.Name)
}
return res, err
}
switch outcome {
case retainDeleted:
res.Deleted = append(res.Deleted, d.Name)
case retainReplaced:
res.Replaced = append(res.Replaced, d.Name)
case retainForkHeld:
res.ForkHeld = append(res.ForkHeld, d.Name)
}
}
return res, nil
}
func codeOrRemote(err error) string {
if code := CodeOf(err); code != "" {
return code
}
return CodeRemoteUnavailable
}
type retainOutcome int
const (
retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed
retainReplaced // the planned attempt is gone; another attempt holds the name
retainForkHeld // a live fork claim is on the attempt: kept, nothing written
)
// deleteRetainedAttempt deletes the planned attempt of vol/name and only
// that attempt. uncertain reports, with an error, that the failing call
// was a mutation whose outcome is unknown.
func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt string) (retainOutcome, bool, error) {
root, err := c.volRoot(vol)
if err != nil {
return 0, false, err
}
m, _, uncertain, err := c.markDeleting(ctx, vol, name, attempt)
if err != nil {
return 0, uncertain, err
}
if m == markClaimed {
return retainForkHeld, false, nil
}
return c.freeName(ctx, root, name, attempt)
}
type markResult int
const (
markDone markResult = iota // this call marked the attempt deleting
markGone // the attempt's entry is gone
markSettled // already deleting or aborted (no fork can claim it)
markClaimed // a live fork claim is on it: nothing written
)
// markDeleting marks attempt of vol/name deleting under the fork-claim
// rule, the one path for retention and explicit delete: the mark is
// conditioned on {state active, gen, no claims}; dead claims are cleared
// conditionally first; a lost condition re-reads and decides again. live
// lists the live claims when the result is markClaimed. uncertain
// reports, with an error, a mutation whose outcome is unknown.
func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, []string, bool, error) {
root, err := c.volRoot(vol)
if err != nil {
return 0, nil, false, err
}
dir := path.Join(root, snapsDir, name)
for try := 0; try < 5; try++ {
e, err := c.f.LookupEntry(ctx, dir, attempt)
if errors.Is(err, ErrNotFound) {
return markGone, nil, false, nil
}
if err != nil {
return 0, nil, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt)
}
if string(e.Extended[extSnapState]) != SnapActive {
return markSettled, nil, false, nil
}
raw := string(e.Extended[extSnapClaims])
claims := decodeClaims(e)
live, err := c.liveClaims(ctx, vol, name, claims)
if err != nil {
return 0, nil, false, err
}
if len(live) > 0 {
return markClaimed, live, false, nil
}
c.hook(hookChecked, name)
next := proto.Clone(e).(*filerpb.Entry)
if len(claims) > 0 {
// Every claim is dead: clear them, then decide again.
delete(next.Extended, extSnapClaims)
err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)})
if err != nil && !errors.Is(err, ErrPrecondition) && !errors.Is(err, ErrNotFound) {
return 0, nil, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt)
}
continue
}
next.Extended[extSnapState] = []byte(SnapDeleting)
next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10))
err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{
extSnapState: []byte(SnapActive),
extSnapGen: e.Extended[extSnapGen],
extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins
})
if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) {
continue // a claim, a delete or a replacement landed: decide again
}
if err != nil {
return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt)
}
c.hook(hookMarked, name)
return markDone, nil, false, nil
}
return 0, nil, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt)
}
// claimedErr is snapshot_claimed naming the claiming fork volumes.
func claimedErr(vol, name string, live []string) error {
targets := make([]string, 0, len(live))
for _, cl := range live {
t, _, _ := strings.Cut(cl, "/")
targets = append(targets, t)
}
return catErr(CodeSnapshotClaimed, false, nil, "snapshot %s/%s is the parent of incomplete fork %s; it can be deleted once that fork completes or is aborted", vol, name, strings.Join(targets, ", "))
}
// Test seams: hook stages in a Retain pass.
const (
hookPlanned = "planned" // after planning, before any deletion
hookChecked = "checked" // an attempt's claims were read and none is live, before its mark
hookMarked = "marked" // an attempt is marked deleting, before its name is freed
// hookClaimDrop: a completed fork read its parent entry to drop its
// claim, before the conditional write.
hookClaimDrop = "claim-drop"
)
func (c *Catalog) hook(stage, name string) {
if c.retainHook != nil {
c.retainHook(stage, name)
}
}
// freeName removes the name record of name only while it names attempt.
func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (retainOutcome, bool, error) {
err := c.f.DeleteEntry(ctx, path.Join(root, snapNamesDir), name, map[string][]byte{extAttempt: []byte(attempt)})
switch {
case err == nil || errors.Is(err, ErrNotFound):
return retainDeleted, false, nil
case errors.Is(err, ErrPrecondition):
return retainReplaced, false, nil
}
return 0, true, remoteErr(err, "remove the name record %s", name)
}
// forkClaim is the claim a fork puts on its parent attempt.
func forkClaim(target, requestID string) string { return target + "/" + requestID }
func decodeClaims(e *filerpb.Entry) []string {
raw := e.Extended[extSnapClaims]
if len(raw) == 0 {
return nil
}
var out []string
if json.Unmarshal(raw, &out) != nil {
return []string{string(raw)} // unreadable: kept as one live claim (safe)
}
return out
}
func setClaims(e *filerpb.Entry, claims []string) {
if len(claims) == 0 {
delete(e.Extended, extSnapClaims)
return
}
sort.Strings(claims)
body, _ := json.Marshal(claims)
e.Extended[extSnapClaims] = body
}
// liveClaims returns the claims on vol/name that a fork may still need: a
// claim is dead only when its target has a HEAD, or its target's VOLUME
// was made by another request (or from another parent).
func (c *Catalog) liveClaims(ctx context.Context, vol, name string, claims []string) ([]string, error) {
var live []string
for _, cl := range claims {
target, req, ok := strings.Cut(cl, "/")
if !ok || CheckVolumeID(target) != nil {
live = append(live, cl) // not ours to judge: keep the snapshot
continue
}
_, has, err := c.ReadHead(ctx, target)
if err != nil {
return nil, err
}
if has {
continue
}
v, ok, err := c.ReadVolume(ctx, target)
if err != nil {
return nil, err
}
if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) {
continue
}
live = append(live, cl)
}
return live, nil
}
// allSnapshots lists every published, not-deleting snapshot of vol, with
// the attempt each name resolved to.
func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) {
return c.listSnapshots(ctx, vol, false)
}
func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) ([]SnapshotInfo, error) {
var out []SnapshotInfo
after := ""
for {
page, next, err := c.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, Limit: maxListLimit, IncludeDeleting: deleting})
if err != nil {
return nil, err
}
out = append(out, page...)
if next == "" {
return out, nil
}
if next <= after {
return nil, errors.New("chunkstore: non-advancing snapshot listing")
}
after = next
}
}
// forkParentsNeeded names the snapshots of vol a fork still needs by its
// published fork record: a volume whose fork record names vol and the
// snapshot, and which has no real published HEAD yet (absent or aborted).
// It covers forks published before fork holds existed; a newer fork is
// also covered, atomically, by its hold (deleteRetainedAttempt).
func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) {
vols, err := c.ListVolumes(ctx)
if err != nil {
return nil, err
}
needed := map[string]bool{}
for _, other := range vols {
if other == vol {
continue
}
v, ok, err := c.ReadVolume(ctx, other)
if err != nil {
return nil, err
}
if !ok || v.Fork == nil || v.Fork.Source != vol {
continue
}
h, has, err := c.ReadHead(ctx, other)
if err != nil {
return nil, err
}
if !has || h.State == storage.ChunkHeadAborted {
needed[v.Fork.Snapshot] = true
}
}
return needed, nil
}
@@ -0,0 +1,248 @@
//go:build chunkstore_integration
package chunkstore
import (
"bytes"
"context"
"fmt"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Retention and accounting against a real SeaweedFS (CHUNKSTORE_WEED):
// N+5 semantic snapshots plus pinned ones; a dry run writes nothing; retain
// leaves N plus the pinned; accounting follows (GC not run: the deleted
// snapshots' chunks are still stored, now unreferenced).
func TestIntegration_RetainAndUsage(t *testing.T) {
c := startWeed(t)
ctx := context.Background()
const base = "/swblock/chunks"
geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
full := uint64(geo.ChunkBlocks) * uint64(geo.BlockSize)
cat, err := NewCatalog(c.client(t, base), base)
if err != nil {
t.Fatal(err)
}
if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil {
t.Fatal(err)
}
r := c.remote(t, path.Join(base, "v1"))
clock := time.Now().Add(-72 * time.Hour)
cat.SetClock(func() time.Time { return clock })
// One snapshot per step; each step rewrites chunk 0 under a new key,
// so every snapshot but the newest owns one chunk exclusively.
cur, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
step := 0
snapshot := func(name, class string) {
t.Helper()
data := bytes.Repeat([]byte{byte(step + 1)}, int(full))
key := fmt.Sprintf("chunks/e1/c0/step-%02d", step)
step++
if err := r.Put(ctx, key, data); err != nil {
t.Fatal(err)
}
next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: uint64(step), Chunks: map[uint64]storage.ChunkRef{0: ref(key, data)}}
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next)
if err != nil {
t.Fatal(err)
}
next.Gen = gen
cur = next
clock = clock.Add(time.Minute)
if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name, Class: class}, next); err != nil {
t.Fatal(err)
}
}
snapshot("golden-a", SnapshotClassPinned) // the oldest, but pinned
snapshot("golden-b", SnapshotClassPinned)
const n = DefaultKeepNewest
for i := 0; i < n+5; i++ {
snapshot(fmt.Sprintf("s%02d", i), SnapshotClassSemantic)
}
clock = time.Now()
before, err := cat.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if len(before.Snapshots) != n+7 || before.StoredBindings != n+7 || before.StoredUpperBound || before.LiveBytes != full {
t.Fatalf("before: %d snapshots, %d bindings, upper=%t, live=%d", len(before.Snapshots), before.StoredBindings, before.StoredUpperBound, before.LiveBytes)
}
exclusive := func(u VolumeUsage) uint64 {
var sum uint64
for _, s := range u.Snapshots {
sum += s.ExclusiveBytes
}
return sum
}
if got := exclusive(before); got != uint64(n+6)*full {
t.Fatalf("before: exclusive %d, want %d (all but the newest snapshot)", got, uint64(n+6)*full)
}
// Dry run: exactly the 5 oldest semantic snapshots, nothing written.
namesBefore, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0)
if err != nil {
t.Fatal(err)
}
dry, err := cat.Retain(ctx, "v1", true)
if err != nil {
t.Fatal(err)
}
var wouldGo []string
for _, d := range dry.Decisions {
if !d.Keep {
wouldGo = append(wouldGo, d.Name)
}
}
if fmt.Sprint(wouldGo) != "[s04 s03 s02 s01 s00]" || len(dry.Deleted) != 0 {
t.Fatalf("dry run: would delete %v, deleted %v", wouldGo, dry.Deleted)
}
namesAfter, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0)
if err != nil || len(namesAfter) != len(namesBefore) {
t.Fatalf("dry run changed the name records: %d -> %d (%v)", len(namesBefore), len(namesAfter), err)
}
res, err := cat.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
if len(res.Deleted) != 5 || res.Kept != n+2 {
t.Fatalf("retain: deleted %v, kept %d", res.Deleted, res.Kept)
}
after, err := cat.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
left := map[string]bool{}
for _, s := range after.Snapshots {
left[s.Name] = true
}
if len(after.Snapshots) != n+2 || !left["golden-a"] || !left["golden-b"] || left["s04"] || !left["s05"] {
t.Fatalf("after: snapshots %v", left)
}
if got := exclusive(after); got != uint64(n+1)*full {
t.Fatalf("after: exclusive %d, want %d", got, uint64(n+1)*full)
}
if after.StoredBindings != n+7 || !after.StoredUpperBound {
t.Fatalf("after: %d bindings, upper=%t; want all still stored (no GC yet), flagged as an upper bound", after.StoredBindings, after.StoredUpperBound)
}
}
// The two held schedules of the review of #142 against a real filer:
// (1) a same-name pinned replacement made after planning survives (the
// filer's conditional name delete refuses the stale attempt); (2) a fork
// that starts after the scan and stops before its HEAD (VOLUME published,
// deadline exceeded) keeps its parent, and completes on retry; (3) a fork
// that claims between retention's claim check and its mark makes the
// filer refuse the mark (conditioned on no claims), so the parent is kept.
func TestIntegration_RetainHeldSchedules(t *testing.T) {
c := startWeed(t)
ctx := context.Background()
const base = "/swblock/chunks"
geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
full := int(geo.ChunkBlocks) * int(geo.BlockSize)
cat, err := NewCatalog(c.client(t, base), base)
if err != nil {
t.Fatal(err)
}
if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil {
t.Fatal(err)
}
r := c.remote(t, path.Join(base, "v1"))
data := bytes.Repeat([]byte{7}, full)
if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil {
t.Fatal(err)
}
cur, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
head := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: ref("chunks/e1/c0/k", data)}}
if head.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, head); err != nil {
t.Fatal(err)
}
clock := time.Now().Add(-72 * time.Hour)
cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances
for i := 0; i < 3; i++ {
if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, head); err != nil {
t.Fatal(err)
}
}
if err := cat.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy
t.Fatal(err)
}
clock = time.Now()
var pinnedAttempt string
stoppedFork := func(snap, target string) {
t.Helper()
cat.OpDeadline = time.Nanosecond
_, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"})
cat.OpDeadline = 0
if CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err)
}
if _, ok, err := cat.ReadVolume(ctx, target); !ok || err != nil {
t.Fatalf("the stopped fork %s VOLUME: ok=%t %v", target, ok, err)
}
}
cat.retainHook = func(stage, name string) {
if stage == hookChecked && name == "s02" {
stoppedFork("s02", "v3") // (3) lands between the check and the mark
return
}
if stage != hookPlanned {
return
}
// (1) s00 is replaced by a pinned snapshot of the same name.
if _, err := cat.DeleteSnapshot(ctx, "v1", "s00"); err != nil {
t.Fatal(err)
}
if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "pinned-b", Class: SnapshotClassPinned}, head); err != nil {
t.Fatal(err)
}
b, err := cat.readSnap(ctx, "v1", "s00")
if err != nil {
t.Fatal(err)
}
pinnedAttempt = b.attempt
// (2) a fork of s01 publishes its VOLUME and stops before HEAD.
stoppedFork("s01", "v2")
}
res, err := cat.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
cat.retainHook = nil
if len(res.Deleted) != 0 || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s02 s01]" {
t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want none / s00 / s02 s01", res.Deleted, res.Replaced, res.ForkHeld)
}
b, err := cat.readSnap(ctx, "v1", "s00")
if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned {
t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt)
}
// An explicit delete of a claimed parent is refused (claude05, 23:58Z).
if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed {
t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err)
}
for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} {
if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive {
t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err)
}
if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}); err != nil {
t.Fatalf("fork %s retry: %v", fk.target, err)
}
}
res, err = cat.Retain(ctx, "v1", false)
if err != nil || fmt.Sprint(res.Deleted) != "[s02 s01]" {
t.Fatalf("after the forks completed: deleted=%v %v; want s02 s01 (s00 is pinned)", res.Deleted, err)
}
}
@@ -0,0 +1,438 @@
package chunkstore
import (
"context"
"errors"
"path"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// Controls for the review of #142: attempt-bound deletion, fork claims,
// rolling windows, cross-volume holders and partial results.
// Log-spaced keeps use rolling windows anchored at now, not calendar
// periods: at 10:30 with KeepHourly=1, 10:20 is kept and 09:50 (another
// clock hour, but inside the same rolling hour) is not.
func TestPlanRetention_RollingWindows(t *testing.T) {
day0 := time.Unix(86400*1000, 0) // midnight, so clock hours and days are visible
at := func(d time.Duration) time.Time { return day0.Add(d) }
nm := func(a time.Time) string { return a.UTC().Format("01-02T15:04") }
plan := func(p RetentionPolicy, now time.Time, ages ...time.Time) map[string][]string {
var snaps []SnapshotInfo
for _, a := range ages {
snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil))
}
return kept(planRetention(p, snaps, nil, now))
}
now := at(10*time.Hour + 30*time.Minute)
if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil {
t.Fatalf("hourly at 10:30: kept %v; want only 10:20", k)
}
// Windows k=0,1: [09:30,10:30) and [08:30,09:30). 09:00 is the newest of window 1.
if k := plan(RetentionPolicy{KeepHourly: 2}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute), at(9*time.Hour), at(8*time.Hour+40*time.Minute)); len(k) != 2 || k[nm(at(10*time.Hour+20*time.Minute))] == nil || k[nm(at(9*time.Hour))] == nil {
t.Fatalf("hourly=2 at 10:30: kept %v; want 10:20 and 09:00", k)
}
// Daily across a non-aligned midnight: at 01:00, 00:30 and 23:00 the
// day before are both in the last rolling day; only the newest stays.
now = at(24*time.Hour + time.Hour)
if k := plan(RetentionPolicy{KeepDaily: 1}, now, at(24*time.Hour+30*time.Minute), at(23*time.Hour)); len(k) != 1 || k[nm(at(24*time.Hour+30*time.Minute))] == nil {
t.Fatalf("daily at 01:00: kept %v; want only 00:30", k)
}
// Weekly: 8 days back is week window 1, 6 days back window 0.
if k := plan(RetentionPolicy{KeepWeekly: 1}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour)); len(k) != 1 {
t.Fatalf("weekly=1: kept %v; want only the 6-day-old one", k)
}
if k := plan(RetentionPolicy{KeepWeekly: 2}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour), now.Add(-13*24*time.Hour)); len(k) != 2 {
t.Fatalf("weekly=2: kept %v; want 6 and 8 days old", k)
}
}
// Deletion is bound to the planned attempt: a same-name pinned replacement
// made between planning and deletion survives, attempt and name intact.
func TestCatalog_RetainSkipsASameNameReplacement(t *testing.T) {
_, c, h, _ := retentionFixture(t, 15) // s00..s04 expire
ctx := context.Background()
var newAttempt string
c.retainHook = func(stage, _ string) {
if stage != hookPlanned {
return
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil {
t.Fatal(err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s02", RequestID: "pinned-b", Class: SnapshotClassPinned}, h); err != nil {
t.Fatal(err)
}
b, err := c.readSnap(ctx, "v1", "s02")
if err != nil {
t.Fatal(err)
}
newAttempt = b.attempt
}
res, err := c.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
b, err := c.readSnap(ctx, "v1", "s02")
if err != nil {
t.Fatalf("the pinned replacement is gone: %v", err)
}
if b.attempt != newAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned {
t.Fatalf("replacement changed: %+v (attempt %s, want %s)", b, b.attempt, newAttempt)
}
if strings.Join(res.Replaced, ",") != "s02" || strings.Join(res.Deleted, ",") != "s04,s03,s01,s00" {
t.Fatalf("deleted=%v replaced=%v; want s02 replaced, the other four deleted", res.Deleted, res.Replaced)
}
}
func forkFixture(t *testing.T) (*fakeFiler, *Catalog) {
t.Helper()
f, c, _, _ := retentionFixture(t, 3)
ctx := context.Background()
if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy
t.Fatal(err)
}
for _, vol := range []string{"v1", "v2"} {
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
}
return f, c
}
// A fork that starts after the retention scan (its VOLUME published, its
// HEAD not yet) has claimed the parent: retention keeps it, and the fork
// completes on retry.
func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
c.retainHook = func(stage, _ string) {
if stage != hookPlanned {
return
}
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork with a held HEAD create: %v", err)
}
}
res, err := c.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" {
t.Fatalf("deleted=%v forkHeld=%v; want s01 kept for the fork", res.Deleted, res.ForkHeld)
}
if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive {
t.Fatalf("parent after retain: %+v %v; want active", s, err)
}
c.retainHook = nil
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil {
t.Fatalf("fork retry: %v", err)
}
// Completed: the hold is gone and the parent is no longer needed.
res, err = c.Retain(ctx, "v1", false)
if err != nil || strings.Join(res.Deleted, ",") != "s01" {
t.Fatalf("after the fork completed: deleted=%v %v; want s01", res.Deleted, err)
}
}
func claimsOf(t *testing.T, c *Catalog, name string) []string {
t.Helper()
ref, ok, err := c.resolveSnap(context.Background(), "v1", name)
if err != nil || !ok || ref.entry == nil {
t.Fatalf("read %s: ok=%t %v", name, ok, err)
}
return decodeClaims(ref.entry)
}
// A fork arriving after the mark finds the parent deleting and refuses
// before installing anything (and leaves no claim).
func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) {
_, c := forkFixture(t)
ctx := context.Background()
ran := false
c.retainHook = func(stage, name string) {
if stage != hookMarked || name != "s01" {
return
}
ran = true
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotDeleting {
t.Fatalf("fork of a marked parent: %v; want snapshot_deleting", err)
}
}
res, err := c.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
if !ran || strings.Join(res.Deleted, ",") != "s02,s01,s00" {
t.Fatalf("ran=%v deleted=%v; want all three", ran, res.Deleted)
}
if _, ok, err := c.ReadVolume(ctx, "v2"); ok || err != nil {
t.Fatalf("a refused fork published its VOLUME (%v)", err)
}
}
// Schedule 1: retention read no claims, then a fork claims before the
// mark. The mark's condition (no claims) fails; retention reads again,
// sees the live claim and keeps the parent.
func TestCatalog_ClaimBetweenCheckAndMarkWins(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
c.retainHook = func(stage, name string) {
if stage != hookChecked || name != "s01" {
return
}
c.retainHook = nil
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork with a held HEAD create: %v", err)
}
}
res, err := c.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" {
t.Fatalf("deleted=%v forkHeld=%v; want s01 kept", res.Deleted, res.ForkHeld)
}
if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive {
t.Fatalf("parent: %+v %v; want active", s, err)
}
if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/f" {
t.Fatalf("claims %v; want v2/f", got)
}
}
// Schedule 2: a fork that claimed and died before publishing its VOLUME
// keeps the parent however much later retention runs (no lifetimes); the
// fork retried to completion releases it.
func TestCatalog_DeadForkClaimKeepsTheParent(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
f.failCreate = func(p string) error {
if p == catBase+"/v2/"+volumeName {
return errors.New("filer unavailable")
}
return nil
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err == nil {
t.Fatal("fork with a failing VOLUME create succeeded")
}
f.failCreate = nil
if _, ok, _ := c.ReadVolume(ctx, "v2"); ok {
t.Fatal("VOLUME published")
}
saved := c.now
c.SetClock(func() time.Time { return saved().Add(30 * 24 * time.Hour) })
res, err := c.Retain(ctx, "v1", false)
if err != nil || strings.Join(res.ForkHeld, ",") != "s01" {
t.Fatalf("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil {
t.Fatalf("fork retry: %v", err)
}
if got := claimsOf(t, c, "s01"); len(got) != 0 {
t.Fatalf("claims after the fork completed: %v; want none", got)
}
res, err = c.Retain(ctx, "v1", false)
if err != nil || strings.Join(res.Deleted, ",") != "s01" {
t.Fatalf("after completion: deleted=%v %v; want s01", res.Deleted, err)
}
}
// Schedule 3: a second request for the same target is refused without
// touching the first request's claim (claims are per target AND request,
// and a fork drops only its own, only once its HEAD exists).
func TestCatalog_RefusedSameTargetForkLeavesTheOtherClaim(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork a: %v", err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "b"}); CodeOf(err) != CodeTargetExists {
t.Fatalf("fork b (same target, other request): %v; want target_exists", err)
}
if _, err := c.Retain(ctx, "v1", false); err != nil {
t.Fatal(err)
}
if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive {
t.Fatalf("parent after retain: %+v %v; want kept for request a", s, err)
}
if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/a" {
t.Fatalf("claims %v; want only a's, intact", got)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); err != nil {
t.Fatalf("fork a retry: %v", err)
}
res, err := c.Retain(ctx, "v1", false)
if err != nil || strings.Join(res.Deleted, ",") != "s01" {
t.Fatalf("after a completed: deleted=%v %v; want s01 (b's claim dead)", res.Deleted, err)
}
}
// A failure part way reports the confirmed deletions, the failing
// snapshot (uncertain: the mark's outcome is unknown) and what was not
// attempted; a lost response leaves the snapshot deleting and the next
// pass finishes it.
func TestCatalog_RetainReportsPartialProgress(t *testing.T) {
f, c, _, _ := retentionFixture(t, 15) // s04,s03,s02,s01,s00 expire, in that order
ctx := context.Background()
f.failUpdate = func(p string) error {
if strings.Contains(p, "/snaps/s03/") {
return errors.New("filer unavailable")
}
return nil
}
res, err := c.Retain(ctx, "v1", false)
if err == nil || res.Failed == nil {
t.Fatalf("retain with a failing mark: %+v %v; want an error with the partial result", res, err)
}
if strings.Join(res.Deleted, ",") != "s04" || res.Failed.Name != "s03" || !res.Failed.Uncertain || strings.Join(res.NotAttempted, ",") != "s02,s01,s00" {
t.Fatalf("partial: deleted=%v failed=%+v notAttempted=%v", res.Deleted, res.Failed, res.NotAttempted)
}
f.failUpdate = nil
f.failUpdateAfterApply = func(p string) error {
if strings.Contains(p, "/snaps/s03/") {
return errors.New("response lost")
}
return nil
}
res, err = c.Retain(ctx, "v1", false)
if err == nil || res.Failed == nil || res.Failed.Name != "s03" || !res.Failed.Uncertain || len(res.Deleted) != 0 {
t.Fatalf("lost response: %+v %v", res, err)
}
f.failUpdateAfterApply = nil
dry, err := c.Retain(ctx, "v1", true)
if err != nil {
t.Fatal(err)
}
listed := false
for _, d := range dry.Decisions {
if d.Name == "s03" && !d.Keep && strings.Join(d.Reasons, ",") == SnapDeleting {
listed = true
}
}
if !listed || dry.Expired != 4 {
t.Fatalf("dry run after the lost response: expired=%d decisions=%+v; want s03 listed as deleting", dry.Expired, dry.Decisions)
}
res, err = c.Retain(ctx, "v1", false)
if err != nil || strings.Join(res.Deleted, ",") != "s02,s01,s00,s03" {
t.Fatalf("rerun: deleted=%v %v; want the rest and the half-deleted s03", res.Deleted, err)
}
if _, ok, err := c.resolveSnap(ctx, "v1", "s03"); ok || err != nil {
t.Fatalf("s03's name still held after the rerun (%v)", err)
}
}
// Exclusive bytes count other volumes' holders: after a completed fork, a
// snapshot whose chunks the fork's HEAD references ("@v1/key") owns none.
func TestCatalog_UsageCountsForkHolders(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
for _, vol := range []string{"v1", "v2"} {
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil {
t.Fatal(err)
}
publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)})
u, err := c.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 {
t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots)
}
}
// claude05's ruling (23:58Z): an explicit delete of a snapshot an
// incomplete fork claims is refused (snapshot_claimed, not retryable,
// naming the fork); once the fork completes or is aborted the delete goes
// through. Retention and delete share the check (markDeleting).
func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork v2: %v", err)
}
holdFirst(f, catBase+"/v3/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s02", Target: "v3", RequestID: "g"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork v3: %v", err)
}
for _, tc := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} {
_, err := c.DeleteSnapshot(ctx, "v1", tc.snap)
var ce *CatalogError
if !errors.As(err, &ce) || ce.Code != CodeSnapshotClaimed || ce.Retryable || !strings.Contains(ce.Detail(), tc.target) {
t.Fatalf("delete %s claimed by %s: %v; want snapshot_claimed, not retryable, naming %s", tc.snap, tc.target, err, tc.target)
}
if s, err := c.readSnap(ctx, "v1", tc.snap); err != nil || s.State != SnapActive {
t.Fatalf("%s after the refused delete: %+v %v; want active", tc.snap, s, err)
}
}
// Completed fork: its claim no longer blocks.
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil {
t.Fatalf("fork v2 retry: %v", err)
}
if got, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil || got != SnapDeleting {
t.Fatalf("delete after the fork completed: %q %v", got, err)
}
// Aborted fork (a sweep's tombstone): neither does its claim.
if claimed, err := c.AbortFork(ctx, "v3"); err != nil || !claimed {
t.Fatalf("abort v3: claimed=%t %v", claimed, err)
}
if got, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil || got != SnapDeleting {
t.Fatalf("delete after the fork was aborted: %q %v", got, err)
}
}
// Review of f42e723: a completed fork's claim cleanup that read the parent
// entry, then paused while an explicit delete marked it, must not write
// its stale copy back (resurrecting an unnamed snapshot as a GC root).
func TestCatalog_ClaimCleanupNeverUndoesADelete(t *testing.T) {
f, c := forkFixture(t)
ctx := context.Background()
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork: %v", err)
}
parent, err := c.readSnap(ctx, "v1", "s01")
if err != nil {
t.Fatal(err)
}
ran := false
c.retainHook = func(stage, name string) {
if stage != hookClaimDrop || name != "s01" || ran {
return
}
ran = true // the fork's HEAD exists now: its claim is dead
if _, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil {
t.Fatalf("delete during the claim cleanup: %v", err)
}
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil {
t.Fatalf("fork retry: %v", err)
}
c.retainHook = nil
e, err := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s01"), parent.attempt)
if err != nil {
t.Fatal(err)
}
if !ran || string(e.Extended[extSnapState]) != SnapDeleting || len(e.Extended[extSnapDeletedNs]) == 0 {
t.Fatalf("ran=%t state=%q deleted_ns=%q; want the delete mark kept", ran, e.Extended[extSnapState], e.Extended[extSnapDeletedNs])
}
if _, ok, err := c.resolveSnap(ctx, "v1", "s01"); ok || err != nil {
t.Fatalf("s01's name is back (%v)", err)
}
}
@@ -0,0 +1,406 @@
package chunkstore
import (
"context"
"crypto/sha256"
"fmt"
"path"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Snapshot retention and space accounting (claude05's rulings
// 2026-11-15 22:53Z): policy edges, dry run, forks, accounting.
var retBase = time.Unix(1_000_000, 0)
func snapAt(name string, at time.Time, class string, expiresAt time.Time, labels map[string]string) SnapshotInfo {
s := SnapshotInfo{Name: name, CreatedNs: at.UnixNano(), Class: class, Labels: labels}
if !expiresAt.IsZero() {
s.ExpiresAtNs = expiresAt.UnixNano()
}
return s
}
func kept(ds []RetentionDecision) map[string][]string {
out := map[string][]string{}
for _, d := range ds {
if d.Keep {
out[d.Name] = d.Reasons
}
}
return out
}
func noYoung() RetentionPolicy { return RetentionPolicy{KeepNewest: 10} }
// Newest N unpinned are kept; equal creation times rank by name.
func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) {
now := retBase.Add(48 * time.Hour)
var snaps []SnapshotInfo
for i := 0; i < 15; i++ {
snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil))
}
k := kept(planRetention(noYoung(), snaps, nil, now))
if len(k) != 10 {
t.Fatalf("kept %d, want 10: %v", len(k), k)
}
for i := 5; i < 15; i++ {
if _, ok := k[fmt.Sprintf("s%02d", i)]; !ok {
t.Fatalf("newest s%02d not kept: %v", i, k)
}
}
tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)}
if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, nil, now)); len(k) != 1 || k["a"] == nil {
t.Fatalf("tie: kept %v, want only a (name order)", k)
}
}
// Pinned: never expired by count or age; past its ExpiresAtNs it is
// unpinned again. Semantic and labeled snapshots are not exempt.
func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) {
now := retBase.Add(48 * time.Hour)
snaps := []SnapshotInfo{
snapAt("pinned-old", retBase, SnapshotClassPinned, time.Time{}, nil),
snapAt("pinned-by-expiry", retBase, "", now.Add(time.Hour), nil),
snapAt("pinned-expired", retBase, SnapshotClassPinned, now.Add(-time.Second), nil),
snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil),
snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}),
}
k := kept(planRetention(RetentionPolicy{}, snaps, nil, now))
if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil {
t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k)
}
}
// Younger than T is kept beyond N; a creation time in the future (clock
// skew) counts as young.
func TestPlanRetention_YoungAndClockSkew(t *testing.T) {
now := retBase.Add(48 * time.Hour)
p := RetentionPolicy{KeepNewest: 0, KeepYoungerNs: int64(time.Hour)}
snaps := []SnapshotInfo{
snapAt("young", now.Add(-30*time.Minute), SnapshotClassSemantic, time.Time{}, nil),
snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil),
snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil),
}
k := kept(planRetention(p, snaps, nil, now))
if len(k) != 2 || k["young"] == nil || k["future"] == nil {
t.Fatalf("kept %v; want young and future", k)
}
}
// Log-spaced keeps: the newest snapshot of each of the last H hours.
func TestPlanRetention_HourlyBuckets(t *testing.T) {
now := retBase.Add(48*time.Hour + 59*time.Minute) // late in an hour
var snaps []SnapshotInfo
for i := 0; i < 12; i++ { // every 30 min over the last 6 hours
snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil))
}
k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, nil, now))
if len(k) != 3 {
t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k)
}
for _, reasons := range k {
if len(reasons) != 1 || reasons[0] != keepHourly {
t.Fatalf("reasons %v; want hourly", reasons)
}
}
}
// A snapshot a fork still needs is kept whatever the policy says.
func TestPlanRetention_ForkParentKept(t *testing.T) {
now := retBase.Add(48 * time.Hour)
snaps := []SnapshotInfo{snapAt("parent", retBase, SnapshotClassSemantic, time.Time{}, nil)}
k := kept(planRetention(RetentionPolicy{}, snaps, map[string]bool{"parent": true}, now))
if len(k) != 1 || k["parent"][0] != keepForkParent {
t.Fatalf("kept %v; want parent (fork_parent)", k)
}
}
// An agent that checkpoints every step stays bounded: one semantic
// snapshot a minute for a day keeps at most N + T/step + hourly buckets.
func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) {
p := RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger), KeepHourly: 24}
start := retBase
var snaps []SnapshotInfo
for i := 0; i < 24*60; i++ {
snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, map[string]string{"agent.step": fmt.Sprint(i)}))
}
now := start.Add(24 * time.Hour)
bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly
if k := kept(planRetention(p, snaps, nil, now)); len(k) > bound {
t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound)
}
// The bound holds however long the agent runs.
for i := 24 * 60; i < 7*24*60; i++ {
snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil))
}
if k := kept(planRetention(p, snaps, nil, start.Add(7*24*time.Hour))); len(k) > bound {
t.Fatalf("after a week: kept %d; want at most %d", len(k), bound)
}
}
// retentionFixture makes n semantic snapshots of v1, one a minute, two
// days before the catalog clock's now.
func retentionFixture(t *testing.T, n int) (*fakeFiler, *Catalog, storage.ChunkHead, *time.Time) {
t.Helper()
f, _, c, h := catalogFixture(t)
clock := retBase
c.SetClock(func() time.Time { return clock })
for i := 0; i < n; i++ {
clock = retBase.Add(time.Duration(i) * time.Minute)
if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, h); err != nil {
t.Fatal(err)
}
}
clock = retBase.Add(48 * time.Hour)
return f, c, h, &clock
}
func snapNames(t *testing.T, c *Catalog) map[string]bool {
t.Helper()
snaps, err := c.allSnapshots(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
out := map[string]bool{}
for _, s := range snaps {
out[s.Name] = true
}
return out
}
// A dry run lists exactly what would go and writes nothing.
func TestCatalog_RetainDryRunWritesNothing(t *testing.T) {
f, c, _, _ := retentionFixture(t, 15)
before := len(f.allWritten())
res, err := c.Retain(context.Background(), "v1", true)
if err != nil {
t.Fatal(err)
}
if got := len(f.allWritten()); got != before {
t.Fatalf("dry run wrote %d entries", got-before)
}
var expired []string
for _, d := range res.Decisions {
if !d.Keep {
expired = append(expired, d.Name)
}
}
if res.Expired != 5 || res.Kept != 10 || len(res.Deleted) != 0 || strings.Join(expired, ",") != "s04,s03,s02,s01,s00" {
t.Fatalf("dry run: expired=%d kept=%d deleted=%v names=%v; want the 5 oldest listed, none deleted", res.Expired, res.Kept, res.Deleted, expired)
}
if len(snapNames(t, c)) != 15 {
t.Fatal("dry run removed snapshots")
}
}
// Retain deletes the expired snapshots, keeps N plus the pinned one, and
// frees the expired names.
func TestCatalog_RetainKeepsNewestNAndPinned(t *testing.T) {
_, c, h, clock := retentionFixture(t, 15)
ctx := context.Background()
saved := *clock
*clock = retBase.Add(-time.Hour) // the oldest snapshot of all, but pinned
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "golden", RequestID: "rg", Class: SnapshotClassPinned}, h); err != nil {
t.Fatal(err)
}
*clock = saved
res, err := c.Retain(ctx, "v1", false)
if err != nil {
t.Fatal(err)
}
names := snapNames(t, c)
if len(res.Deleted) != 5 || len(names) != 11 || !names["golden"] || names["s00"] || !names["s14"] {
t.Fatalf("after retain: deleted=%v remaining=%v; want 5 deleted, s05..s14 and golden left", res.Deleted, names)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "reuse"}, h); err != nil {
t.Fatalf("expired name not freed: %v", err)
}
}
// The policy lives on the VOLUME entry: default until set; set stores it
// without touching the volume document; negatives are refused.
func TestCatalog_RetentionPolicyStoredOnVolume(t *testing.T) {
_, _, c, _ := catalogFixture(t)
ctx := context.Background()
p, set, err := c.ReadRetentionPolicy(ctx, "v1")
if err != nil || set || p != DefaultRetentionPolicy() {
t.Fatalf("unset policy: %+v set=%t err=%v; want the default", p, set, err)
}
want := RetentionPolicy{KeepNewest: 3, KeepYoungerNs: int64(time.Minute), KeepDaily: 7}
if err := c.SetRetentionPolicy(ctx, "v1", want); err != nil {
t.Fatal(err)
}
if p, set, err := c.ReadRetentionPolicy(ctx, "v1"); err != nil || !set || p != want {
t.Fatalf("stored policy: %+v set=%t err=%v", p, set, err)
}
if v, ok, err := c.ReadVolume(ctx, "v1"); err != nil || !ok || v.Geometry != catGeo {
t.Fatalf("volume after setting a policy: %+v %t %v", v, ok, err)
}
if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: -1}); CodeOf(err) != CodeInvalidPolicy {
t.Fatalf("negative policy: %v; want invalid_policy", err)
}
}
// Two setters racing on one revision: the second update's precondition
// fails.
func TestCatalog_RetentionPolicyConcurrentSetIsConditional(t *testing.T) {
f, _, c, _ := catalogFixture(t)
ctx := context.Background()
f.failUpdate = func(p string) error {
if p == path.Join(catBase, "v1", volumeName) {
f.failUpdate = nil
// another setter lands first
e := f.entries[p]
e.Extended[extRetentionRev] = []byte("7")
}
return nil
}
if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: 1}); err == nil {
t.Fatal("a set that lost the race succeeded")
}
}
// The class is validated and stored with the snapshot.
func TestCatalog_SnapshotClass(t *testing.T) {
_, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "x", RequestID: "rx", Class: "forever"}, h); CodeOf(err) != CodeInvalidClass {
t.Fatalf("unknown class: %v; want invalid_class", err)
}
s, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "p", RequestID: "rp", Class: SnapshotClassPinned}, h)
if err != nil || s.Class != SnapshotClassPinned || !s.Pinned() {
t.Fatalf("pinned snapshot: %+v %v", s, err)
}
snaps, err := c.allSnapshots(ctx, "v1")
if err != nil || len(snaps) != 1 || snaps[0].Class != SnapshotClassPinned {
t.Fatalf("listed class: %+v %v", snaps, err)
}
}
// A fork whose HEAD is not yet written still needs its parent snapshot:
// retain keeps it; once the fork's HEAD is published it no longer does.
func TestCatalog_RetainKeepsParentOfAnIncompleteFork(t *testing.T) {
f, c, _, clock := retentionFixture(t, 3)
ctx := context.Background()
if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy
t.Fatal(err)
}
// The fake filer lists only directory entries it holds; a real filer
// has them for every volume directory.
for _, vol := range []string{"v1", "v2"} {
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
}
holdFirst(f, catBase+"/v2/HEAD")
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("fork with a held HEAD create: %v", err)
}
res, err := c.Retain(ctx, "v1", true)
if err != nil {
t.Fatal(err)
}
if k := kept(res.Decisions); len(k) != 1 || k["s01"] == nil || k["s01"][0] != keepForkParent {
t.Fatalf("incomplete fork: kept %v; want only s01 (fork_parent)", k)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil {
t.Fatalf("fork retry: %v", err)
}
_ = clock
if res, err := c.Retain(ctx, "v1", true); err != nil || res.Kept != 0 {
t.Fatalf("published fork: kept %d (%v); want 0", res.Kept, err)
}
}
// publishTagged installs a HEAD for vol with chunks under keys tagged tag.
func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead {
t.Helper()
ctx := context.Background()
r, err := NewChunkRemote(f, b, path.Join(catBase, vol))
if err != nil {
t.Fatal(err)
}
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 43, Chunks: map[uint64]storage.ChunkRef{}}
for idx, data := range chunks {
key := fmt.Sprintf("chunks/%s/c%d/k", tag, idx)
if err := r.Put(ctx, key, data); err != nil {
t.Fatal(err)
}
h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
}
cur, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h)
if err != nil {
t.Fatal(err)
}
h.Gen = gen
return h
}
// Accounting from manifests and listings: live bytes from HEAD; a
// snapshot's exclusive bytes are what only it references; stored bytes
// count every binding, exact for referenced keys.
func TestCatalog_UsageFromManifests(t *testing.T) {
f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3
ctx := context.Background()
full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize)
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil {
t.Fatal(err)
}
u, err := c.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 {
t.Fatalf("shared chunks: %+v", u)
}
if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound {
t.Fatalf("stored: %+v; want 2 bindings, exact", u)
}
// HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one.
publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)})
u, err = c.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if u.Snapshots[0].ExclusiveBytes != 2*full {
// both of s1's chunks are now exclusive: the new HEAD uses e2 keys
t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full)
}
if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound {
t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u)
}
// s1 deleted: its keys are unreferenced but still stored (until GC),
// counted at the full chunk size as an upper bound.
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
u, err = c.Usage(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound {
t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u)
}
}
// chunkSize clips the last chunk to NumBlocks.
func TestChunkSizeClipsLastChunk(t *testing.T) {
g := Geometry{NumBlocks: 20, BlockSize: 4096, ChunkBlocks: 8}
for idx, want := range map[uint64]uint64{0: 8 * 4096, 1: 8 * 4096, 2: 4 * 4096, 3: 0} {
if got := chunkSize(g, idx); got != want {
t.Errorf("chunk %d: %d, want %d", idx, got, want)
}
}
}
@@ -0,0 +1,220 @@
package chunkstore
import (
"context"
"errors"
"net/url"
"path"
"sort"
"strings"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Space accounting (claude05's rulings, 2026-11-15 22:53Z). Everything is
// computed from manifests and filer listings; no chunk data is read.
//
// A chunk's bytes are ChunkBlocks x BlockSize, the last chunk clipped to
// NumBlocks (ChunkRef carries no size).
//
// - LiveBytes: the chunks HEAD references.
// - per snapshot, ExclusiveBytes: the chunks that snapshot references
// and no other holder does, where the holders are this volume's HEAD
// and live snapshots AND every other volume's HEAD and live snapshots
// (a fork's "@owner/key" references are resolved to the owner's
// chunk). These are the bytes deleting that snapshot makes eligible
// for GC; GC still keeps them through its grace period and while any
// in-flight intent names them, so they are not reclaimed at once.
// - StoredBytes: the volume's chunk-key bindings in the filer (what is
// stored now, referenced or not). A binding a manifest references is
// counted at its exact (clipped) size; any other binding at the full
// chunk size, so StoredBytes is an upper bound whenever
// StoredUpperBound is set.
//
// "Bytes uploaded since creation" needs a counter nothing records today (a
// follow-up). The unreferenced-not-yet-collected bytes come from GC's
// preview once that lands (#140).
// SnapshotUsage is one snapshot's share of a volume's space.
type SnapshotUsage struct {
Name string `json:"name"`
CreatedNs int64 `json:"createdNs"`
Class string `json:"class"`
Pinned bool `json:"pinned"`
Chunks int `json:"chunks"`
ExclusiveBytes uint64 `json:"exclusiveBytes"`
}
// VolumeUsage is a volume's space accounting.
type VolumeUsage struct {
VolumeID string `json:"volumeID"`
ChunkBytes uint64 `json:"chunkBytes"` // one full chunk
LiveChunks int `json:"liveChunks"`
LiveBytes uint64 `json:"liveBytes"`
Snapshots []SnapshotUsage `json:"snapshots"`
StoredBindings int `json:"storedBindings"`
StoredBytes uint64 `json:"storedBytes"`
StoredUpperBound bool `json:"storedUpperBound"`
Policy RetentionPolicy `json:"policy"`
PolicySet bool `json:"policySet"`
}
// chunkSize is the byte size of chunk index idx under g.
func chunkSize(g Geometry, idx uint64) uint64 {
full := uint64(g.ChunkBlocks) * uint64(g.BlockSize)
if g.ChunkBlocks == 0 {
return 0
}
first := idx * uint64(g.ChunkBlocks)
if first >= g.NumBlocks {
return 0
}
if rest := g.NumBlocks - first; rest < uint64(g.ChunkBlocks) {
return rest * uint64(g.BlockSize)
}
return full
}
// Usage computes vol's space accounting.
func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) {
v, ok, err := c.ReadVolume(ctx, vol)
if err != nil {
return VolumeUsage{}, err
}
if !ok {
return VolumeUsage{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol)
}
g := v.Geometry
u := VolumeUsage{VolumeID: vol, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize), Snapshots: []SnapshotUsage{}}
if u.Policy, u.PolicySet, err = c.ReadRetentionPolicy(ctx, vol); err != nil {
return VolumeUsage{}, err
}
head, _, err := c.ReadHead(ctx, vol)
if err != nil {
return VolumeUsage{}, err
}
snaps, err := c.allSnapshots(ctx, vol)
if err != nil {
return VolumeUsage{}, err
}
// holders counts, per chunk identity (owner volume + key), how many
// HEADs and live snapshots of any volume reference it; size is each
// identity's byte size as this volume's geometry indexes it.
holders := map[string]int{}
size := map[string]uint64{}
addHolder := func(owner string, h storage.ChunkHead, sized bool) {
seen := map[string]bool{}
for idx, ref := range h.Chunks {
id := chunkIdentity(owner, ref.Key)
if sized {
size[id] = chunkSize(g, idx)
}
if !seen[id] {
seen[id] = true
holders[id]++
}
}
}
addHolder(vol, head, true)
for idx := range head.Chunks {
u.LiveChunks++
u.LiveBytes += chunkSize(g, idx)
}
for _, s := range snaps {
addHolder(vol, s.Head(), true)
}
others, err := c.ListVolumes(ctx)
if err != nil {
return VolumeUsage{}, err
}
for _, other := range others {
if other == vol {
continue
}
oh, has, err := c.ReadHead(ctx, other)
if err != nil {
return VolumeUsage{}, err
}
if has {
addHolder(other, oh, false)
}
osnaps, err := c.allSnapshots(ctx, other)
if err != nil {
return VolumeUsage{}, err
}
for _, s := range osnaps {
addHolder(other, s.Head(), false)
}
}
for _, s := range snaps {
su := SnapshotUsage{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Chunks: len(s.Head().Chunks)}
seen := map[string]bool{}
for _, ref := range s.Head().Chunks {
id := chunkIdentity(vol, ref.Key)
if seen[id] {
continue
}
seen[id] = true
if holders[id] == 1 {
su.ExclusiveBytes += size[id]
}
}
u.Snapshots = append(u.Snapshots, su)
}
sort.Slice(u.Snapshots, func(i, j int) bool {
if u.Snapshots[i].CreatedNs != u.Snapshots[j].CreatedNs {
return u.Snapshots[i].CreatedNs > u.Snapshots[j].CreatedNs
}
return u.Snapshots[i].Name < u.Snapshots[j].Name
})
// Stored: this volume's own chunk-key bindings.
r, err := NewChunkRemote(c.f, nilBlobs{}, path.Join(c.base, vol))
if err != nil {
return VolumeUsage{}, err
}
after := ""
for {
page, err := c.f.ListEntries(ctx, r.keyDir(), "", after, listPage)
if err != nil {
return VolumeUsage{}, remoteErr(err, "list the chunk keys of %s", vol)
}
for _, e := range page {
if e.GetName() <= after {
return VolumeUsage{}, errors.New("chunkstore: non-advancing chunk key listing")
}
after = e.GetName()
if e.GetIsDirectory() || string(e.Extended[extKind]) != kindChunkKey {
continue
}
key, err := url.PathUnescape(e.GetName())
if err != nil || strings.HasPrefix(key, "@") {
continue
}
u.StoredBindings++
if n, ok := size[chunkIdentity(vol, key)]; ok {
u.StoredBytes += n
} else {
u.StoredBytes += u.ChunkBytes
u.StoredUpperBound = true
}
}
if len(page) < listPage {
return u, nil
}
}
}
// chunkIdentity names the chunk a ref in volume vol points at: an
// owner-qualified "@owner/key" (a fork's reference) is owner's key,
// anything else is vol's.
func chunkIdentity(vol, key string) string {
if strings.HasPrefix(key, "@") {
if owner, rest, ok := strings.Cut(key[1:], "/"); ok {
return owner + "\x00" + rest
}
}
return vol + "\x00" + key
}
@@ -31,6 +31,9 @@ type ChunkControl interface {
ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error)
DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error)
Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error)
// Usage is the volume's space accounting and retention policy
// (GET /status/chunk).
Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error)
}
// ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1).
@@ -54,6 +57,7 @@ type ChunkSnapshotRequest struct {
Labels map[string]string
Consistency string
ExpiresAtNs int64
Class string // retention class: "semantic" or "pinned"
}
// ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6).
@@ -210,7 +214,7 @@ func chunkErrorCode(err error) (int, string, bool) {
func catalogStatus(code string) int {
switch code {
case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel:
case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel, chunkstore.CodeInvalidClass, chunkstore.CodeInvalidPolicy:
return http.StatusBadRequest
case chunkstore.CodeSnapshotNotFound:
return http.StatusNotFound
@@ -315,6 +319,7 @@ func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Reques
Labels map[string]string `json:"labels"`
Consistency string `json:"consistency"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Class string `json:"class"`
TimeoutMs int64 `json:"timeoutMs"`
}
if !decodeChunkBody(w, r, &req) {
@@ -327,7 +332,7 @@ func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Reques
ctx, cancel := chunkContext(r, req.TimeoutMs)
defer cancel()
info, err := ctl.Snapshot(ctx, req.VolumeID, ChunkSnapshotRequest{Name: req.Name, RequestID: req.RequestID,
Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs})
Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, Class: req.Class})
if err != nil {
writeChunkFailure(w, err)
return
@@ -458,8 +463,13 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64)
// for the name gets snapshot_exists, both without cutting. Only a free name
// is cut, and the HEAD that cut installed is stored.
func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) {
// Admit the request before anything can cut: an invalid class must
// not advance HEAD (review of #142).
if err := chunkstore.ValidateSnapshotClass(req.Class); err != nil {
return chunkstore.SnapshotInfo{}, err
}
sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels,
Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume"}
Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class}
if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed {
return info, err
}
@@ -479,6 +489,32 @@ func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string
return c.cat.DeleteSnapshot(ctx, volumeID, name)
}
func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) {
return c.cat.Usage(ctx, volumeID)
}
// handleStatusChunk answers GET /status/chunk?volume=<id>: the served
// volume's space accounting and retention policy, computed from manifests
// and filer listings (no chunk data reads).
func (s *StatusServer) handleStatusChunk(w http.ResponseWriter, r *http.Request) {
if !s.chunkAdmit(w, r, http.MethodGet) {
return
}
volumeID := r.URL.Query().Get("volume")
ctl := s.chunkTarget(w, volumeID)
if ctl == nil {
return
}
ctx, cancel := chunkContext(r, 0)
defer cancel()
u, err := ctl.Usage(ctx, volumeID)
if err != nil {
writeChunkFailure(w, err)
return
}
writeChunkJSON(w, http.StatusOK, u)
}
func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) {
r, last, err := c.p.DetachVolume(ctx, volumeID)
if err != nil {
@@ -0,0 +1,44 @@
package volume
import (
"context"
"net/http"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
)
// An invalid class is refused before anything cuts or writes, and as a
// client error (400); a valid class cuts once, and its replay cuts none
// (review of #142).
func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) {
ctx := context.Background()
fp, ctl := adapterFixture(t)
_, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: "golden"})
if chunkstore.CodeOf(err) != chunkstore.CodeInvalidClass {
t.Fatalf("invalid class: %v; want invalid_class", err)
}
if fp.cuts != 0 {
t.Fatalf("an invalid class cut %d times", fp.cuts)
}
if got, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); err != nil || len(got) != 0 {
t.Fatalf("an invalid class left snapshots %v (%v)", got, err)
}
for _, code := range []string{chunkstore.CodeInvalidClass, chunkstore.CodeInvalidPolicy} {
if s := catalogStatus(code); s != http.StatusBadRequest {
t.Fatalf("%s maps to %d, want 400", code, s)
}
}
if s := catalogStatus(chunkstore.CodeSnapshotClaimed); s != http.StatusConflict {
t.Fatalf("snapshot_claimed maps to %d, want 409", s)
}
info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned})
if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 {
t.Fatalf("valid class: %+v %v cuts=%d", info, err, fp.cuts)
}
info, err = ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned})
if err != nil || !info.Replayed || fp.cuts != 1 {
t.Fatalf("replay: %+v %v cuts=%d; want a replay with no new cut", info, err, fp.cuts)
}
}
@@ -27,6 +27,7 @@ type fakeChunkControl struct {
next string
state string
detach ChunkDetachResponse
usage chunkstore.VolumeUsage
lastOpts chunkstore.ListOptions
lastSnap ChunkSnapshotRequest
lastMin uint64
@@ -61,6 +62,12 @@ func (f *fakeChunkControl) DeleteSnapshot(ctx context.Context, vol, name string)
f.calls++
return f.state, f.err
}
func (f *fakeChunkControl) Usage(ctx context.Context, vol string) (chunkstore.VolumeUsage, error) {
f.calls++
f.remember(ctx)
return f.usage, f.err
}
func (f *fakeChunkControl) Detach(ctx context.Context, vol string) (ChunkDetachResponse, error) {
f.calls++
f.remember(ctx)
@@ -0,0 +1,59 @@
package volume
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
)
// GET /status/chunk?volume= answers the served volume's space accounting
// and retention policy; the usual chunk-route guards apply.
func TestStatusServer_StatusChunkUsage(t *testing.T) {
fake := &fakeChunkControl{usage: chunkstore.VolumeUsage{
VolumeID: "v1", ChunkBytes: 32768, LiveChunks: 2, LiveBytes: 65536, StoredBindings: 3, StoredBytes: 98304, StoredUpperBound: true,
Snapshots: []chunkstore.SnapshotUsage{{Name: "s1", Class: chunkstore.SnapshotClassSemantic, Chunks: 2, ExclusiveBytes: 32768}},
Policy: chunkstore.DefaultRetentionPolicy(),
}}
s := chunkServer(t, fake, true)
w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v1")
if w.Code != http.StatusOK {
t.Fatalf("status %d: %s", w.Code, w.Body)
}
var got chunkstore.VolumeUsage
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.LiveBytes != 65536 || got.StoredBytes != 98304 || !got.StoredUpperBound || len(got.Snapshots) != 1 || got.Snapshots[0].ExclusiveBytes != 32768 || got.Policy.KeepNewest != chunkstore.DefaultKeepNewest {
t.Fatalf("usage body %+v", got)
}
if w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v9"); w.Code != http.StatusNotFound {
t.Fatalf("other volume: %d", w.Code)
}
if w := serveStatusChunk(t, s, http.MethodPost, "/status/chunk?volume=v1"); w.Code != http.StatusMethodNotAllowed {
t.Fatalf("POST: %d", w.Code)
}
}
// The snapshot route carries the retention class through.
func TestStatusServer_ChunkSnapshotCarriesClass(t *testing.T) {
fake := &fakeChunkControl{snap: chunkstore.SnapshotInfo{VolumeID: "v1", Name: "s1"}}
s := chunkServer(t, fake, true)
if w := serve(t, s, http.MethodPost, "/chunk/snapshot", `{"volumeID":"v1","name":"s1","requestID":"r","class":"pinned"}`, ""); w.Code != http.StatusOK {
t.Fatalf("snapshot: %d %s", w.Code, w.Body)
}
if fake.lastSnap.Class != chunkstore.SnapshotClassPinned {
t.Fatalf("class not passed through: %+v", fake.lastSnap)
}
}
func serveStatusChunk(t *testing.T, s *StatusServer, method, target string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, target, nil)
req.RemoteAddr = "127.0.0.1:5555"
w := httptest.NewRecorder()
s.handleStatusChunk(w, req)
return w
}
@@ -341,6 +341,7 @@ func (s *StatusServer) Start(addr string) (string, error) {
}
if s.chunkEnabled {
mux.Handle("/chunk/", s.chunkMux())
mux.HandleFunc("/status/chunk", s.handleStatusChunk)
}
s.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}