Merge branch 'p328' into train/20261121-7

# Conflicts:
#	docs/design/invariants.md
This commit is contained in:
pingqiu committed 2026-11-20 22:33:26 -08:00
commit 3ae278e117
21 files changed
+667 -30

No files matched your search

@@ -208,7 +208,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) {
if !first.MarkSaved || first.Reclaimed != 0 {
t.Fatalf("first mark: %+v", first)
}
now = now.Add(time.Hour + time.Second)
now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second)
preview = call(false)
if preview.Reclaimed != 0 || len(preview.WouldDelete) != 1 || preview.WouldDelete[0].Key != "orphan" {
t.Fatalf("mature preview: %+v", preview)
@@ -278,7 +278,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) {
if expired.ExpiredIntents != 1 || expired.Reclaimed != 0 {
t.Fatalf("fenced intent admission: %+v", expired)
}
now = now.Add(time.Hour + time.Second)
now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second)
reclaimed := call(true)
if reclaimed.Reclaimed != 1 || len(reclaimed.WouldDelete) != 1 || reclaimed.WouldDelete[0].Key != "held" {
t.Fatalf("expired capture: %+v", reclaimed)
@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -264,3 +265,20 @@ func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) {
})
}
}
func TestOpsChunkGC_PermanentDeleteReportsFailureWithSavedCoverage(t *testing.T) {
var stdout, stderr bytes.Buffer
out := chunkstore.GCExecution{MarkOutcome: "complete", MarkSaved: true, GCResult: chunkstore.GCResult{
Reclaimed: 1, FailedDeletes: []chunkstore.GCDeleteFailure{{GCObject: chunkstore.GCObject{Volume: "v1", Key: "bad", FID: "3,bad"}, Error: "http 400"}},
}}
rc := chunkGCResult(out, chunkstore.ErrBlobDeleteRejected, &stdout, &stderr)
var body struct {
GC chunkstore.GCExecution `json:"gc"`
}
if err := json.Unmarshal(stdout.Bytes(), &body); err != nil {
t.Fatal(err)
}
if rc != 1 || !body.GC.MarkSaved || body.GC.MarkOutcome != "complete" || body.GC.Reclaimed != 1 || len(body.GC.FailedDeletes) != 1 || body.GC.FailedDeletes[0].FID != "3,bad" {
t.Fatalf("partial failure lost saved coverage or object identity: rc=%d body=%s", rc, stdout.String())
}
}
+66 -11
View File
@@ -19,6 +19,15 @@ import (
const extGCDeleted = "swb.gc.deleted"
// ErrBlobDeleteRejected identifies a definite per-object refusal (HTTP400).
// It never proves the needle absent; GC retains its tombstone and reports it.
var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected")
// DefaultGCClockSkew is the allowed pairwise difference between timestamp
// writers and collectors. Deployments with a larger bound must raise ClockSkew;
// no finite time-based grace can be safe with unbounded clock differences.
const DefaultGCClockSkew = time.Minute
// BlobDeleter deletes one immutable needle. Missing needles are success.
// Implementations must not reuse a deleted fid.
type BlobDeleter interface {
@@ -30,8 +39,11 @@ type BlobDeleter interface {
// lease expiry or a cached guess. Unknown authority retains the intent.
type GCConfig struct {
Grace, IntentTTL time.Duration
IssuedEpoch func(context.Context, string) (uint64, error)
Now func() time.Time
// ClockSkew bounds pairwise wall-clock differences. Zero uses the default.
// Binding creation timestamps additionally lose up to one second of precision.
ClockSkew time.Duration
IssuedEpoch func(context.Context, string) (uint64, error)
Now func() time.Time
}
type GCRoot struct {
@@ -47,10 +59,16 @@ type GCObject struct {
Key string `json:"key"`
FID string `json:"fid"`
}
type GCDeleteFailure struct {
GCObject
Error string `json:"error"`
}
type GCResult struct {
Roots []GCRoot `json:"roots"`
WouldDelete []GCObject `json:"would_delete"`
WouldExpireIntents []string `json:"would_expire_intents"`
FailedDeletes []GCDeleteFailure `json:"failed_deletes"`
Roots []GCRoot `json:"roots"`
WouldDelete []GCObject `json:"would_delete"`
WouldExpireIntents []string `json:"would_expire_intents"`
Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int
// Pre-binding needles cannot be enumerated by this API. They are retained;
// UnknownUnbound is true rather than inventing a report-only count.
@@ -90,6 +108,12 @@ func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, er
if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil {
return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority")
}
if cfg.ClockSkew == 0 {
cfg.ClockSkew = DefaultGCClockSkew
}
if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second {
return nil, errors.New("chunkstore: invalid GC clock skew bound")
}
if cfg.Now == nil {
cfg.Now = time.Now
}
@@ -113,6 +137,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
result.Roots = []GCRoot{}
result.WouldDelete = []GCObject{}
result.WouldExpireIntents = []string{}
result.FailedDeletes = []GCDeleteFailure{}
defer func() {
if err != nil && apply {
g.candidates = map[string]gcCandidate{}
@@ -120,7 +145,13 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
}()
start := g.cfg.Now()
if !g.last.IsZero() && start.Before(g.last) {
return result, errors.New("chunkstore: GC clock moved backwards")
// Discard coverage across a backward clock step; a fresh complete mark
// can still make progress without borrowing time from the future.
if apply {
g.candidates = map[string]gcCandidate{}
}
// Preview must also ignore the old coverage without mutating it.
// Candidate lookup below is guarded by this same condition.
}
roots := map[string]bool{}
var bindings []gcBinding
@@ -208,11 +239,11 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
}
for _, in := range intents {
result.Intents++
if in.CreatedNs <= 0 || in.CreatedNs > start.UnixNano() {
if in.CreatedNs <= 0 {
return result, errors.New("chunkstore: invalid intent creation time")
}
expire := false
if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL {
if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && g.oldEnough(start, time.Unix(0, in.CreatedNs), g.cfg.IntentTTL, 0) {
issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol)
// Catalog copy intents are retained: their exclusive creates
// are not epoch-fenced. For a capture, both the authority
@@ -317,15 +348,18 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
continue
}
created := time.Unix(b.entry.Attributes.Crtime, 0)
if !start.After(created.Add(g.cfg.Grace)) {
if !g.oldEnough(start, created, g.cfg.Grace, time.Second) {
continue
}
candidate, seen := g.candidates[p]
if !g.last.IsZero() && start.Before(g.last) {
seen = false
}
if !seen || candidate.digest != b.digest {
candidate = gcCandidate{start, b.digest}
}
result.Candidates++
if start.Sub(candidate.since) < g.cfg.Grace {
if !g.oldEnough(start, candidate.since, g.cfg.Grace, 0) {
nextCandidates[p] = candidate
continue
}
@@ -348,7 +382,20 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
}
}
if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil {
return result, err
if ctx.Err() != nil {
return result, ctx.Err()
}
if !errors.Is(err, ErrBlobDeleteRejected) {
return result, err
}
// INV-GC-DELETE-PROGRESS-001: a confirmed object rejection
// must not starve later candidates or invalidate a complete mark.
// Keep the fid/tombstone and retry; never record this object done.
result.FailedDeletes = append(result.FailedDeletes, GCDeleteFailure{
GCObject: GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])}, Error: err.Error(),
})
nextCandidates[p] = candidate
continue
}
e := proto.Clone(b.entry).(*filerpb.Entry)
e.Extended[extGCDeleted] = []byte("done")
@@ -393,3 +440,11 @@ func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) {
}
return reader.Get(ctx, fid)
}
// INV-GC-CLOCK-SKEW-001: expiry uses a lower bound on elapsed time,
// never the raw difference of timestamps from different hosts. Subtracting
// separately avoids overflowing grace + skew for large configured durations.
func (g *Collector) oldEnough(now, stamp time.Time, grace, resolution time.Duration) bool {
age := now.Sub(stamp)
return age > grace && age-grace > g.cfg.ClockSkew+resolution
}
@@ -0,0 +1,308 @@
package chunkstore
import (
"context"
"encoding/json"
"github.com/seaweedfs/seaweed-block/core/storage"
"path"
"strings"
"testing"
"time"
)
// Exercise the default one-minute pairwise budget independently of the
// implementation constant. Wider clock differences require a larger config.
const testedGCSkew = time.Minute
func TestGCSkewSnapshotDeleteGraceBothDirections(t *testing.T) {
for _, offset := range []time.Duration{-testedGCSkew, testedGCSkew} {
t.Run(offset.String(), func(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
realDelete := *now
c.SetClock(func() time.Time { return realDelete.Add(offset) })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)})
snapshotDir(t, f, "v1", "s1")
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
if offset < 0 {
*now = realDelete.Add(g.cfg.Grace - testedGCSkew/2)
} else {
*now = realDelete
}
roots, err := g.snapshotAttemptHeads(ctx, "v1", *now)
if err != nil || len(roots) != 1 {
t.Fatalf("skew shortened delete grace or blocked mark: roots=%d err=%v", len(roots), err)
}
*now = realDelete.Add(g.cfg.Grace + 2*testedGCSkew + time.Nanosecond)
roots, err = g.snapshotAttemptHeads(ctx, "v1", *now)
if err != nil || len(roots) != 0 {
t.Fatalf("old deleting attempt did not release: roots=%d err=%v", len(roots), err)
}
})
}
}
func TestGCSkewIntentExpiryUsesConservativeAge(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old"})
if err != nil {
t.Fatal(err)
}
ins, _ := r.ListIntents(ctx)
created := time.Unix(0, ins[0].CreatedNs)
head, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
t.Fatal(err)
}
g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil }
*now = created.Add(g.cfg.IntentTTL + testedGCSkew/2)
result, err := g.Run(ctx)
if err != nil || result.ExpiredIntents != 0 {
t.Fatalf("intent expired inside skew allowance: %+v %v", result, err)
}
*now = created.Add(g.cfg.IntentTTL + testedGCSkew + time.Nanosecond)
result, err = g.Run(ctx)
if err != nil || result.ExpiredIntents != 1 {
t.Fatalf("eligible intent %s retained: %+v %v", id, result, err)
}
}
func TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
for _, key := range []string{"rooted", "orphan"} {
if err := r.Put(ctx, key, []byte(key)); err != nil {
t.Fatal(err)
}
}
id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}})
if err != nil {
t.Fatal(err)
}
dir := path.Join(catBase, "v1", intentsDir)
entry, err := f.LookupEntry(ctx, dir, id)
if err != nil {
t.Fatal(err)
}
var doc intentDoc
if err = json.Unmarshal(entry.Content, &doc); err != nil {
t.Fatal(err)
}
doc.CreatedNs = now.Add(testedGCSkew / 2).UnixNano()
entry.Content, _ = json.Marshal(doc)
if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
out, err := g.Run(ctx)
if err != nil {
t.Fatalf("future intent blocked unrelated progress: %v", err)
}
if i == 1 && out.Reclaimed != 1 {
t.Fatalf("unrelated orphan did not progress: %+v", out)
}
*now = now.Add(2 * time.Hour)
}
if _, err = r.Get(ctx, "rooted"); err != nil {
t.Fatal("future root lost", err)
}
}
func TestGCSkewPersistedCoverageAcrossHosts(t *testing.T) {
for _, future := range []bool{false, true} {
t.Run(map[bool]string{false: "fast-reader", true: "future-writer"}[future], func(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil {
t.Fatal(err)
}
first := *now
if future {
*now = first.Add(testedGCSkew)
}
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil {
t.Fatal(err)
}
if future {
*now = first
} else {
*now = first.Add(g.cfg.Grace + testedGCSkew/2)
}
out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
if err != nil || out.Reclaimed != 0 {
t.Fatalf("cross-host coverage shortened grace or blocked pass: %+v %v", out, err)
}
*now = now.Add(g.cfg.Grace + testedGCSkew + time.Nanosecond)
out, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
if err != nil || out.Reclaimed != 1 {
t.Fatalf("fresh safe coverage did not reclaim: %+v %v", out, err)
}
})
}
}
func TestGCSkewBindingAgeIncludesSecondResolution(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil {
t.Fatal(err)
}
born := time.Unix(now.Unix(), 900000000)
*now = born.Add(g.cfg.Grace)
dir := path.Join(catBase, "v1", keysDir)
entry, err := f.LookupEntry(ctx, dir, "orphan")
if err != nil {
t.Fatal(err)
}
entry.Attributes.Crtime = born.Add(-testedGCSkew).Unix()
if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil {
t.Fatal(err)
}
out, err := g.Run(ctx)
if err != nil || out.Candidates != 0 {
t.Fatalf("binding age lost skew/second resolution: %+v %v", out, err)
}
}
func TestGCSkewConfigAndMarkCoverage(t *testing.T) {
for _, skew := range []time.Duration{0, 2 * time.Minute} {
t.Run(skew.String(), func(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil {
t.Fatal(err)
}
cfg := g.cfg
cfg.ClockSkew = skew
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true); err != nil {
t.Fatal(err)
}
entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName)
if err != nil {
t.Fatal(err)
}
var mark savedGCMark
if err = json.Unmarshal(entry.Content, &mark); err != nil {
t.Fatal(err)
}
if mark.ClockSkewNs <= 0 {
t.Fatal("normalized clock policy absent from mark")
}
// A legacy mark, or one from another skew policy, cannot authorize deletion.
mark.ClockSkewNs = 0
entry.Content, _ = json.Marshal(mark)
if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), entry, nil); err != nil {
t.Fatal(err)
}
*now = now.Add(2 * time.Hour)
out, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true)
if err != nil || out.Reclaimed != 0 {
t.Fatalf("legacy coverage borrowed: %+v %v", out, err)
}
*now = now.Add(2 * time.Hour)
out, err = c.ExecuteVolumeGC(ctx, "v1", b, cfg, true)
if err != nil || out.Reclaimed != 1 {
t.Fatalf("matching normalized policy lost coverage: %+v %v", out, err)
}
})
}
_, b, c, g, _ := gcFixture(t)
for _, bad := range []time.Duration{-1, time.Duration(1<<63 - 1)} {
cfg := g.cfg
cfg.ClockSkew = bad
if _, err := NewCollector(c, b, cfg); err == nil {
t.Fatalf("bad skew %s accepted", bad)
}
}
}
func TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate(t *testing.T) {
f, b, _, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil {
t.Fatal(err)
}
if _, err := g.Run(ctx); err != nil {
t.Fatal(err)
}
first := g.last
*now = now.Add(-time.Second)
if out, err := g.Preview(ctx); err != nil || out.Reclaimed != 0 {
t.Fatalf("backward preview: %+v %v", out, err)
}
if !g.last.Equal(first) || len(g.candidates) != 1 {
t.Fatal("preview changed coverage")
}
if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 {
t.Fatalf("backward mark: %+v %v", out, err)
}
*now = now.Add(g.cfg.Grace + g.cfg.ClockSkew + time.Nanosecond)
if out, err := g.Run(ctx); err != nil || out.Reclaimed != 1 {
t.Fatalf("fresh coverage made no progress: %+v %v", out, err)
}
}
func TestGCSkewFutureCopyDoesNotBlockOtherSettlement(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x55)})
for _, name := range []string{"future", "expired"} {
snapshotDir(t, f, "v1", name)
holdFirst(f, path.Join(catBase, "v1", snapsDir, name)+"/")
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, h); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("held copy: %v", err)
}
}
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
ins, err := r.ListIntents(ctx)
if err != nil || len(ins) != 2 {
t.Fatalf("intents: %+v %v", ins, err)
}
*now = now.Add(DefaultOpDeadline + time.Second)
futureID := ""
for _, in := range ins {
if !strings.Contains(in.Holder, "/future/") {
continue
}
futureID = in.ID
dir := path.Join(catBase, "v1", intentsDir)
e, err := f.LookupEntry(ctx, dir, in.ID)
if err != nil {
t.Fatal(err)
}
var d intentDoc
if err = json.Unmarshal(e.Content, &d); err != nil {
t.Fatal(err)
}
d.CreatedNs = now.Add(testedGCSkew / 2).UnixNano()
e.Content, _ = json.Marshal(d)
if err = f.UpdateEntry(ctx, dir, e, nil); err != nil {
t.Fatal(err)
}
}
if futureID == "" {
t.Fatal("future copy fixture not found")
}
if count, err := g.SweepCopies(ctx); err != nil || count != 1 {
t.Fatalf("unrelated settlement blocked: %d %v", count, err)
}
left, err := r.ListIntents(ctx)
if err != nil || len(left) != 1 || left[0].ID != futureID {
t.Fatalf("future protection lost: %+v %v", left, err)
}
if out, err := g.Run(ctx); err != nil || len(out.Roots) == 0 {
t.Fatalf("future copy not rooted: %+v %v", out, err)
}
}
@@ -46,10 +46,13 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) {
if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") {
continue
}
if in.CreatedNs <= 0 || in.CreatedNs > now.UnixNano() {
if in.CreatedNs <= 0 {
return 0, errors.New("chunkstore: invalid copy intent creation time")
}
if in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs {
// A future creation stamp retains protection, without preventing
// unrelated copy attempts from settling. Deadline alone never
// releases roots: the permanent target claim below is still required.
if in.CreatedNs > now.UnixNano() || in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs {
continue
}
pending = append(pending, copyAttempt{vol, r, in})
@@ -174,10 +177,10 @@ func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now ti
}
if info.State == SnapDeleting {
ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64)
if err != nil || ns <= 0 || ns > now.UnixNano() {
if err != nil || ns <= 0 {
return nil, errors.New("chunkstore: invalid deleted snapshot timestamp")
}
if now.Sub(time.Unix(0, ns)) > g.cfg.Grace {
if g.oldEnough(now, time.Unix(0, ns), g.cfg.Grace, 0) {
continue
}
}
@@ -163,7 +163,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) {
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 {
t.Fatalf("first unrooted mark: %+v %v", result, e)
}
*now = now.Add(time.Hour)
*now = now.Add(time.Hour + g.cfg.ClockSkew + time.Nanosecond)
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 {
t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e)
}
@@ -0,0 +1,97 @@
package chunkstore
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestGCPermanentDeleteDoesNotStarveLaterBindings(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
for _, key := range []string{"a_bad", "b_later", "rooted"} {
if err := r.Put(ctx, key, []byte(key)); err != nil {
t.Fatal(err)
}
}
if _, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}); err != nil {
t.Fatal(err)
}
entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad")
if err != nil {
t.Fatal(err)
}
badFID := string(entry.Extended[extFid])
calls := map[string]int{}
var callsMu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fid := strings.TrimPrefix(req.URL.Path, "/")
callsMu.Lock()
calls[fid]++
callsMu.Unlock()
if fid == badFID {
http.Error(w, "cookie mismatch", http.StatusBadRequest)
return
}
if err := b.DeleteBlob(req.Context(), fid); err != nil {
t.Error(err)
}
w.WriteHeader(http.StatusAccepted)
}))
defer server.Close()
deleter := &SWFS{http: server.Client(), vidCache: map[string][]string{"3": {strings.TrimPrefix(server.URL, "http://")}}}
if _, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true); err != nil {
t.Fatal(err)
}
*now = now.Add(2 * time.Hour)
out, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true)
if out.Reclaimed != 1 {
t.Fatalf("permanent DELETE starved later binding: %+v err=%v", out, err)
}
if len(out.FailedDeletes) != 1 || out.FailedDeletes[0].FID != badFID || out.FailedDeletes[0].Key != "a_bad" || out.FailedDeletes[0].Volume != "v1" || !strings.Contains(out.FailedDeletes[0].Error, "http 400") {
t.Fatalf("object refusal missing from result: %+v", out)
}
if !errors.Is(err, ErrBlobDeleteRejected) || !out.MarkSaved {
t.Fatalf("partial deletion must retain complete mark coverage: %+v %v", out, err)
}
badEntry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad")
if err != nil || string(badEntry.Extended[extGCDeleted]) != "1" {
t.Fatalf("failed DELETE declared done: %+v %v", badEntry, err)
}
if _, err := r.Get(ctx, "rooted"); err != nil {
t.Fatal("protected root lost", err)
}
// A repeatedly rejected older object must not erase a younger object's
// first mark, including when each pass is a new collector process.
if err := r.Put(ctx, "c_new", []byte("c_new")); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
*now = now.Add(2 * time.Hour)
out, err = c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true)
if (err != nil && !errors.Is(err, ErrBlobDeleteRejected)) || !out.MarkSaved || ((len(out.FailedDeletes) > 0) != errors.Is(err, ErrBlobDeleteRejected)) {
t.Fatalf("repeated rejection stalled coverage: %+v %v", out, err)
}
if i == 1 && out.Reclaimed != 1 {
t.Fatalf("younger binding lost coverage: %+v", out)
}
}
callsMu.Lock()
badCalls := calls[badFID]
callsMu.Unlock()
if badCalls < 2 {
t.Fatal("failed binding was silently abandoned")
}
if err := r.Put(ctx, "a_bad", []byte("rebind")); err == nil {
t.Fatal("failed deletion permitted rebinding")
}
}
@@ -29,6 +29,7 @@ type savedGCMark struct {
Format int `json:"format"`
Base string `json:"base"`
GraceNs int64 `json:"grace_ns"`
ClockSkewNs int64 `json:"clock_skew_ns"`
TTLNs int64 `json:"ttl_ns"`
OpDeadlineNs int64 `json:"op_deadline_ns"`
Ready bool `json:"ready"`
@@ -81,7 +82,7 @@ func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
if err != nil {
return out, err
}
if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(cfg.IntentTTL) && mark.OpDeadlineNs == int64(c.deadline()) {
if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(g.cfg.IntentTTL) && mark.ClockSkewNs == int64(g.cfg.ClockSkew) && mark.OpDeadlineNs == int64(c.deadline()) {
for p, candidate := range mark.Candidates {
raw, _ := hex.DecodeString(candidate.Digest)
var digest [32]byte
@@ -120,11 +121,17 @@ func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
}
out.MarkOutcome = "complete"
out.MarkSaved = true
if len(out.FailedDeletes) != 0 {
// The mark completed and is reusable even though these tombstoned
// objects remain. Report partial failure after persisting coverage,
// so CLI/maintenance callers cannot mistake it for full reclamation.
return out, fmt.Errorf("%w: %d objects retained; complete GC mark saved", ErrBlobDeleteRejected, len(out.FailedDeletes))
}
return out, nil
}
func (g *Collector) mark(ready bool) savedGCMark {
m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), ClockSkewNs: int64(g.cfg.ClockSkew), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
if ready {
m.LastNs = g.last.UnixNano()
for p, c := range g.candidates {
@@ -163,13 +170,13 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
if err = d.Decode(&trailing); err != io.EOF {
return nil, "", errors.New("chunkstore: trailing GC mark content")
}
if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 || m.ClockSkewNs < 0 {
return nil, "", errors.New("chunkstore: incompatible GC mark")
}
if m.Ready {
now := g.cfg.Now().UnixNano()
if m.LastNs <= 0 || m.LastNs > now {
return nil, "", errors.New("chunkstore: invalid/future GC mark time")
if m.LastNs <= 0 {
return nil, "", errors.New("chunkstore: invalid GC mark time")
}
for p, c := range m.Candidates {
digest, err := hex.DecodeString(c.Digest)
@@ -177,6 +184,11 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
return nil, "", errors.New("chunkstore: invalid GC candidate state")
}
}
if m.LastNs > now {
// A valid mark from a faster clock cannot supply elapsed coverage.
// Keep its token for the conditional replacement, but start afresh.
m.Ready, m.LastNs, m.Candidates = false, 0, nil
}
} else if m.LastNs != 0 || len(m.Candidates) != 0 {
return nil, "", errors.New("chunkstore: incomplete GC mark carries coverage")
}
@@ -31,7 +31,7 @@ func TestGCExecution_PreviewAndIndependentApplyMarks(t *testing.T) {
if e != nil || len(early.WouldDelete) != 0 {
t.Fatalf("early independent preview: %+v %v", early, e)
}
*now = now.Add(2 * time.Second)
*now = now.Add(2*time.Second + g.cfg.ClockSkew)
before, _ := f.LookupEntry(ctx, catBase, gcMarkName)
mature, e := c.ExecuteGC(ctx, b, g.cfg, false)
if e != nil || len(mature.WouldDelete) != 1 || mature.Reclaimed != 0 {
@@ -142,7 +142,7 @@ func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) {
if _, e := r.Get(ctx, "orphan"); e != nil {
t.Fatal("orphan deleted before grace", e)
}
*now = now.Add(2 * time.Second)
*now = now.Add(2*time.Second + g.cfg.ClockSkew)
result, e := g.Run(ctx)
if e != nil || result.Reclaimed != 1 {
t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e)
@@ -181,7 +181,7 @@ func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) {
{"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false},
{"unknown-authority", 2, 2, 2 * time.Hour, true, false},
{"TTL-not-exceeded", 2, 2, time.Hour, false, false},
{"higher-issued-and-fenced", 2, 2, time.Hour + time.Nanosecond, false, true},
{"higher-issued-and-fenced", 2, 2, time.Hour + DefaultGCClockSkew + time.Nanosecond, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
f, b, _, g, now := gcFixture(t)
@@ -339,7 +339,7 @@ func TestGC_CopyIntentSurvivesTakeover(t *testing.T) {
}
func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) {
for _, status := range []int{200, 202, 204, 404, 401, 500} {
for _, status := range []int{200, 202, 204, 404, 400, 401, 500} {
t.Run(http.StatusText(status), func(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -355,6 +355,9 @@ func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) {
if (e == nil) != (status == 200 || status == 202 || status == 204 || status == 404) {
t.Fatalf("status %d: %v", status, e)
}
if errors.Is(e, ErrBlobDeleteRejected) != (status == 400) {
t.Fatalf("wrong per-object refusal classification: status=%d err=%v", status, e)
}
if calls != 1 {
t.Fatalf("calls %d", calls)
}
@@ -317,6 +317,9 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
return err
}
resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
}
+19 -3
View File
@@ -303,11 +303,25 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` |
| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` |
| intent live | removed (catalog) | the operation's create is confirmed or can never apply; the delete outlives the caller's cancellation but is bounded by `dropIntentTimeout` | `core/frontend/chunkstore/catalog.go` `dropIntent` | `INV-CAT-INTENT-DROP-BOUNDED-001` |
| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` |
| intent live | expired | conservative elapsed age exceeds the TTL after pairwise clock skew, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001`, `INV-GC-CLOCK-SKEW-001` |
| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` |
| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` |
| bound | tombstoned, needle deleted | unrooted in two complete marks separated by more than grace plus clock skew, binding age exceeds grace plus skew plus one-second timestamp precision, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-CLOCK-SKEW-001` |
| tombstoned, DELETE rejected | tombstoned, retry later; continue other bindings | definite HTTP400 is reported per object; no success recorded for the rejected fid; complete mark coverage is saved before returning partial failure; cancellation, unknown/other DELETE errors and metadata errors still stop the pass | `core/frontend/chunkstore/gc.go` `Collector.run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `INV-GC-DELETE-PROGRESS-001` |
| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` |
GC clock admission (`INV-GC-CLOCK-SKEW-001`):
```mermaid
flowchart LR
stamp[Persisted timestamp] --> age[Observed age minus pairwise skew and timestamp precision]
age --> young[Not past grace: retain root or candidate]
age --> old[Past grace: existing authority and complete-mark guards]
future[Future or backward mark clock] --> reset[Discard elapsed coverage and start a fresh mark]
old --> reject[HTTP400: retain tombstone and report failure]
reject --> later[Continue later bindings and save complete mark]
```
---
### Local WAL-pressure durability progress
@@ -368,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage.
## Part B. Invariant ledger
133 rows: 114 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 118 new.
135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -552,6 +566,8 @@ Notes:
| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` | ACTIVE |
| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE |
| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE |
| `INV-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE |
| `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE |
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRejectsCopyDeadline` | `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE |
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
+24
View File
@@ -0,0 +1,24 @@
------------------------- MODULE GCClockSkew -------------------------
EXTENDS Integers, TLC
CONSTANTS G, S, Q, MaxT, IgnoreSkew, IgnoreResolution, AbortFuture
VARIABLES t, bias, rounded, stamp, phase, removed, removedOld
vars == <<t,bias,rounded,stamp,phase,removed,removedOld>>
Born == 10
Init == /\ t = Born /\ bias \in {-S,0,S} /\ rounded \in {0,Q}
/\ stamp = Born+bias-rounded /\ phase = "check"
/\ removed = FALSE /\ removedOld = FALSE
Allowance == (IF IgnoreSkew THEN 0 ELSE S)+(IF IgnoreResolution THEN 0 ELSE rounded)
Check == /\ phase = "check"
/\ removed' = (removed \/ (t-stamp > G+Allowance))
/\ removedOld' = (removedOld \/ ~(AbortFuture /\ stamp > t))
/\ phase' = "done"
/\ UNCHANGED <<t,bias,rounded,stamp>>
Tick == /\ phase = "done" /\ t < MaxT /\ t' = t+1 /\ phase' = "check"
/\ UNCHANGED <<bias,rounded,stamp,removed,removedOld>>
Next == Check \/ Tick
Spec == Init /\ [][Next]_vars
NoEarlyExpiry == removed => t-Born > G
FutureProtects == stamp > t => ~removed
IndependentProgress == phase = "done" => removedOld
EventuallyEligibleAtBound == (phase = "done" /\ t = MaxT) => removed
=============================================================================
@@ -0,0 +1,7 @@
SPECIFICATION Spec
CONSTANTS G=3 S=1 Q=1 MaxT=17
IgnoreSkew = FALSE
IgnoreResolution = FALSE
AbortFuture = TRUE
INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound
CHECK_DEADLOCK FALSE
@@ -0,0 +1,7 @@
SPECIFICATION Spec
CONSTANTS G=3 S=1 Q=1 MaxT=17
IgnoreSkew = FALSE
IgnoreResolution = TRUE
AbortFuture = FALSE
INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound
CHECK_DEADLOCK FALSE
@@ -0,0 +1,7 @@
SPECIFICATION Spec
CONSTANTS G=3 S=1 Q=1 MaxT=17
IgnoreSkew = TRUE
IgnoreResolution = FALSE
AbortFuture = FALSE
INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound
CHECK_DEADLOCK FALSE
@@ -0,0 +1,7 @@
SPECIFICATION Spec
CONSTANTS G=3 S=1 Q=1 MaxT=17
IgnoreSkew = FALSE
IgnoreResolution = FALSE
AbortFuture = FALSE
INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound
CHECK_DEADLOCK FALSE
@@ -0,0 +1,24 @@
------------------------ MODULE GCDeleteProgress ------------------------
EXTENDS Integers, FiniteSets
CONSTANT StopOnReject
VARIABLES next, deleted, rejected, complete
vars == <<next, deleted, rejected, complete>>
Bad == 1
Keys == 1..3
Init == /\ next = 1 /\ deleted = {} /\ rejected = {} /\ complete = FALSE
Step == /\ next \in Keys
/\ IF next = Bad THEN
/\ rejected' = rejected \cup {next}
/\ deleted' = deleted
/\ next' = IF StopOnReject THEN 4 ELSE next+1
/\ complete' = StopOnReject
ELSE
/\ deleted' = deleted \cup {next}
/\ rejected' = rejected
/\ next' = next+1
/\ complete' = (next = 3)
Spec == Init /\ [][Step]_vars
NoFalseSuccess == Bad \notin deleted
FailureVisible == complete => Bad \in rejected
LaterProgress == complete => deleted = Keys \ {Bad}
=============================================================================
@@ -0,0 +1,4 @@
SPECIFICATION Spec
CONSTANT StopOnReject = FALSE
INVARIANTS NoFalseSuccess FailureVisible LaterProgress
CHECK_DEADLOCK FALSE
@@ -0,0 +1,4 @@
SPECIFICATION Spec
CONSTANT StopOnReject = TRUE
INVARIANTS NoFalseSuccess FailureVisible LaterProgress
CHECK_DEADLOCK FALSE
+38
View File
@@ -457,3 +457,41 @@ The same command with each negative config exited12 at its intended invariant:
third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last
`AuthorityAtPublication`. Source tests separately check time/metadata handling,
no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch.
## GC clock allowance
`GCClockSkew.tla` checks the time-admission portion of M6 GC: pairwise clock
bias -S/0/+S, timestamp truncation 0/Q, and retaining future-dated roots while
an independently eligible object progresses. It abstracts the existing complete
root scan, exclusive copy settlement and higher-epoch guards; it does not prove
those protocols or safety with clocks outside the configured bound.
Local TLC2.19 / Java21 run 2026-11-21, jar SHA256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`:
`java -Xmx512m -cp <jar> tlc2.TLC -config GCClockSkew_safe.cfg GCClockSkew`
from `docs/spec`, each run with its own metadir. Bounds G=3, S=1, Q=1,
Born=10, MaxT=17. Positive exhausted: exit0, 96 generated / 96 distinct states,
queue empty, depth16. `GCClockSkew_no_skew.cfg` exited12 at `NoEarlyExpiry`
(43/43, depth8); `GCClockSkew_no_resolution.cfg` exited12 at `NoEarlyExpiry`
(44/44, depth8); `GCClockSkew_abort_future.cfg` exited12 at
`IndependentProgress` (11/11, depth2). Source tests independently cover
persisted-mark compatibility, future-clock resets and authority-preserving expiry.
## Per-object GC DELETE progress
`GCDeleteProgress.tla` models the narrow sweep transition after a complete,
authorised mark: three ordered candidates, first DELETE definitively rejected,
later deletes accepted. It checks that the rejected fid is never reported
successful, the failure is visible, and later candidates progress. Root/epoch
admission, elapsed coverage and persistence are outside this small abstraction;
source tests retain those guards and reopen independent collectors between passes.
Local TLC2.19 / Java21, same jar SHA256 as GCClockSkew above, 2026-11-21:
`java -Xmx512m -cp <jar> tlc2.TLC -config GCDeleteProgress_safe.cfg GCDeleteProgress`
from `docs/spec`, separate metadirs. Positive exhausted exit0, 4 generated /4
distinct states, depth4. `GCDeleteProgress_stop.cfg` exits12 at `LaterProgress`
(2 generated /2 distinct, depth2). The HTTP source red uses an actual400 and
checks later reclamation, retained failed tombstones, younger-object progress
across separate collectors and permanent no-rebind behavior.