Merge pull request #370 from seaweedfs/train/20261121-11b

train 11: deletion list 1, seal resume, row splits + length check, runbook, test fixes
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-21 15:33:30 -08:00
commit ec03498005
20 files changed
+624 -198

No files matched your search

+9 -1
View File
@@ -137,6 +137,10 @@ sw-block ops chunk verify --volume v1 --chunk-filer <filer> # read-only che
```
`volume-delete` is refused while the volume is attached or has snapshots.
Frozen detach and the pre-copy detach are not supported in this release: a
detach with `--frozen` (`frozen:true` on `POST /chunk/detach`) is refused with
409 `frozen_detach_unsupported`, and `blockvolume` refuses to start with
`--chunk-detach-precopy`.
`restore` creates the target from the snapshot and, with `--status-addr` naming
the blockvolume that serves the target, starts the background restore there:
the target serves at once, copies every chunk under its own keys and becomes
@@ -216,7 +220,11 @@ a launcher of your own that binds blockmaster to a node address must add it.
## Correctness and verification
- **CI** runs `go build`, `go vet` and `go test -short` on every pull request
and push to `main` ([workflow](.github/workflows/test.yml)). Crash,
and push to `main` ([workflow](.github/workflows/test.yml)); that set leaves out the four
long, disk-heavy packages (a pull request runs those of them it changes);
they run in full, together with the legacy-fixture configuration, on a
separate test VM for every merge train (commit status `full-suite (pool VM)`
on the train head). Crash,
mutation, real-SeaweedFS and binary tests are described in the
[core design, Part 2](docs/design/block-design.md#part-2-verification-lessons-known-issues),
with the known issues.
@@ -52,6 +52,9 @@ type chunkFlags struct {
func validateChunkFlags(f flags) error {
c := f.chunk
if c.detachPrecopy {
return errors.New("--chunk-detach-precopy is not supported in this release")
}
if c.hostLimit.Directory != "" {
if err := c.hostLimit.Validate(); err != nil {
return err
@@ -71,6 +71,34 @@ func TestWALStoreChunkFlags(t *testing.T) {
}
}
// --chunk-detach-precopy stays defined but is refused at flag validation, so
// a process started with it fails with a clear message instead of running the
// pre-copy detach; without it the same flags parse as before.
func TestChunkDetachPrecopyFlagRefused(t *testing.T) {
base := func(extra ...string) []string {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
valid := []string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
"--status-addr=127.0.0.1:0", "--chunk-control-endpoint"}
f, err := parseFlags(base(valid...))
if err != nil || f.chunk.detachPrecopy {
t.Fatalf("valid chunk flags without --chunk-detach-precopy: %+v %v", f.chunk, err)
}
const want = "--chunk-detach-precopy is not supported in this release"
for name, args := range map[string][]string{
"walstore-chunk": base(append(valid, "--chunk-detach-precopy")...),
"explicit true": base(append(valid, "--chunk-detach-precopy=true")...),
"without a chunk": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-detach-precopy"),
} {
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%s: parseFlags error = %v, want %q", name, err, want)
}
}
if _, err := parseFlags(base(append(valid, "--chunk-detach-precopy=false")...)); err != nil {
t.Errorf("explicit false: %v", err)
}
}
func TestChunkVolumeRootStaysInsideBase(t *testing.T) {
root, err := chunkVolumeRoot(defaultChunkPath, "v1")
if err != nil || root != defaultChunkPath+"/v1" {
+1 -1
View File
@@ -202,7 +202,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)")
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit")
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)")
f.chunk.snapshotSchedule = defaultSnapshotSchedule
fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off")
+3 -3
View File
@@ -267,9 +267,9 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
fs.StringVar(&volumeID, "volume", "", "volume id")
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)")
fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)")
fs.BoolVar(&frozen, "frozen", false, "guest is already frozen; use one cut within its remaining five-second budget")
fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "guest freeze start in Unix nanoseconds on the serving host clock")
fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "explicit final frozen attempt; record over_budget rather than refuse its estimate")
fs.BoolVar(&frozen, "frozen", false, "not supported in this release: the server refuses a frozen detach (frozen_detach_unsupported)")
fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "not supported in this release; only valid with --frozen")
fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "not supported in this release; only valid with --frozen")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
@@ -167,6 +167,29 @@ func (c *weedCluster) remote(t *testing.T, root string) *ChunkRemote {
return r
}
// publishIntegrationHead uses the real format-3 manifest path before publishing data.
func publishIntegrationHead(t *testing.T, r *ChunkRemote, base, next storage.ChunkHead, chunkBytes uint64) storage.ChunkHead {
t.Helper()
ctx := context.Background()
next, intents, err := r.PrepareManifest(ctx, base, next, chunkBytes)
if err != nil {
t.Fatal(err)
}
next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next)
if err != nil {
t.Fatal(err)
}
if next.Gen != base.Gen+1 {
t.Fatalf("published generation %d, want %d", next.Gen, base.Gen+1)
}
for _, id := range intents {
if err := r.DeleteIntent(ctx, id); err != nil {
t.Fatal(err)
}
}
return next
}
func TestIntegration_ChunkRemoteContract(t *testing.T) {
c := startWeed(t)
ctx := context.Background()
@@ -191,10 +214,7 @@ func TestIntegration_ChunkRemoteContract(t *testing.T) {
t.Fatalf("Get from another client: %d bytes, %v", len(got), err)
}
h1 := storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{4: ref(key, d)}}
if gen, err := a.CASHead(ctx, storage.ChunkHeadVersion{}, h1); err != nil || gen != 1 {
t.Fatalf("first CAS = %d, %v", gen, err)
}
h1 := publishIntegrationHead(t, a, storage.ChunkHead{}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{4: ref(key, d)}}, 16384)
if _, err := b.CASHead(ctx, storage.ChunkHeadVersion{}, h1); !isPrecondition(err) {
t.Fatalf("racing first CAS: %v; want precondition (real o_excl)", err)
}
@@ -203,7 +223,9 @@ func TestIntegration_ChunkRemoteContract(t *testing.T) {
t.Fatalf("HEAD from another client = %+v, %v", got, err)
}
// Takeover at epoch 2, then the old holder's CAS at the version it read.
if gen, err := b.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, storage.ChunkHead{Epoch: 2, Holder: "b", RemoteLSN: 7, Chunks: h1.Chunks}); err != nil || gen != 2 {
takeover := h1
takeover.Epoch, takeover.Holder = 2, "b"
if gen, err := b.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, takeover); err != nil || gen != 2 {
t.Fatalf("takeover CAS = %d, %v", gen, err)
}
_, err = a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 9})
@@ -50,11 +50,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) {
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
next = publishIntegrationHead(t, r, cur, next, full)
cur = next
clock = clock.Add(time.Minute)
if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name, Class: class}, next); err != nil {
@@ -73,7 +69,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(before.Snapshots) != n+7 || before.StoredBindings != n+7 || before.StoredUpperBound || before.LiveBytes != full {
if len(before.Snapshots) != n+7 || before.StoredBindings != 2*(n+7) || before.ManifestBindings != 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 {
@@ -131,7 +127,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) {
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 {
if after.StoredBindings != 2*(n+7) || after.ManifestBindings != 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)
}
}
@@ -166,9 +162,7 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) {
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)
}
head = publishIntegrationHead(t, r, cur, head, uint64(full))
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++ {
@@ -8,6 +8,7 @@ import (
"fmt"
"path"
"sort"
"strings"
"testing"
"time"
@@ -51,10 +52,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) {
t.Fatal(err)
}
next := storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: cur.RemoteLSN + 1, Chunks: chunks, State: storage.ChunkHeadActive}
if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil {
t.Fatal(err)
}
return next
return publishIntegrationHead(t, r, cur, next, uint64(full))
}
detach := func(r *ChunkRemote) {
t.Helper()
@@ -95,7 +93,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) {
for k, v := range fh.Chunks {
chunks[k] = v
}
publish(w2, "h2", 1, chunks)
h3 := publish(w2, "h2", 1, chunks)
// An attached volume is refused (w1 is held by h1; w2 by h2).
for _, vol := range []string{"w1", "w2"} {
@@ -130,7 +128,8 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) {
if _, err := g.Run(ctx); err != nil {
t.Fatalf("GC mark 1: %v", err)
}
at = at.Add(grace + time.Minute)
// Reclamation requires strictly more than grace plus the skew bound.
at = at.Add(grace + DefaultGCClockSkew + time.Second)
gr, err := g.Run(ctx)
if err != nil {
t.Fatalf("GC mark 2: %v", err)
@@ -139,9 +138,16 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) {
for _, o := range gr.WouldDelete {
got = append(got, o.Volume+":"+o.Key)
}
want := []string{"w1:chunks/e1/c0/a", "w2:chunks/e1/c2/d"}
for _, h := range []storage.ChunkHead{h1, h3} {
for _, segment := range h.Segments {
want = append(want, segment.Owner+":"+strings.TrimPrefix(segment.Key, "@"+segment.Owner+"/"))
}
}
sort.Strings(want)
sort.Strings(got)
if fmt.Sprint(got) != "[w1:chunks/e1/c0/a w2:chunks/e1/c2/d]" || gr.Reclaimed != 2 {
t.Fatalf("GC reclaimed %v (%d); want exactly w1's A and w2's D", got, gr.Reclaimed)
if fmt.Sprint(got) != fmt.Sprint(want) || gr.Reclaimed != len(want) {
t.Fatalf("GC reclaimed %v (%d); want exactly w1's A, w2's D and their unreachable manifests; roots=%+v candidates=%d", got, gr.Reclaimed, gr.Roots, gr.Candidates)
}
for _, kept := range []string{bb.Key, cc.Key} {
if _, err := w1.Get(ctx, kept); err != nil {
@@ -0,0 +1,129 @@
package durable_test
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type sealProgressRemote struct {
*storage.MemChunkRemote
mu sync.Mutex
expire context.CancelCauseFunc
keys []string
images map[[32]byte]int
bytes int
calls int
}
func (r *sealProgressRemote) Put(ctx context.Context, key string, b []byte) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
r.calls++
if r.expire != nil && len(r.keys) == 2 {
r.expire(context.DeadlineExceeded)
r.expire = nil
return context.DeadlineExceeded
}
if err := r.MemChunkRemote.Put(ctx, key, b); err != nil {
return err
}
r.keys = append(r.keys, key)
r.images[sha256.Sum256(b)]++
r.bytes += len(b)
return nil
}
// The caller's deadline cause is injected at the third PUT, after exactly two
// completed uploads. No wall-clock race decides whether progress was made.
func TestPlainSealDeadlineRetryUploadsOnlyRemainingChunks(t *testing.T) {
const chunks = 5
const chunkBytes = 4096 * pcChunkBlocks
parent, stop := context.WithTimeout(context.Background(), time.Minute)
defer stop()
first, expire := context.WithCancelCause(parent)
defer expire(context.Canceled)
remote := &sealProgressRemote{MemChunkRemote: storage.NewMemChunkRemote(), expire: expire, images: map[[32]byte]int{}}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: chunks * pcChunkBlocks, ChunkBlocks: pcChunkBlocks, ChunkUploadConcurrency: 1,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
openRecovered(t, p)
b, err := p.Open(parent, "v1")
if err != nil {
t.Fatal(err)
}
for i := 0; i < chunks; i++ {
if _, err = b.Write(parent, int64(i*chunkBytes), block(byte(0x40+i))); err != nil {
t.Fatal(err)
}
}
if err = b.Close(); err != nil {
t.Fatal(err)
}
before, err := remote.GetHead(parent)
if err != nil {
t.Fatal(err)
}
if _, _, err = p.DetachVolumePlain(first, "v1"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("plain seal missed deadline event: %v", err)
}
if !errors.Is(context.Cause(first), context.DeadlineExceeded) || parent.Err() != nil {
t.Fatal("caller deadline event was not witnessed")
}
after, err := remote.GetHead(parent)
if err != nil || after.Gen != before.Gen || after.State != before.State {
t.Fatalf("aborted seal changed HEAD: %+v %v", after, err)
}
if remote.calls != 3 || len(remote.keys) != 2 || remote.bytes != 2*chunkBytes {
t.Fatalf("first attempt progress: calls=%d successful=%d bytes=%d", remote.calls, len(remote.keys), remote.bytes)
}
firstKeys := append([]string(nil), remote.keys...)
r, last, err := p.DetachVolumePlain(parent, "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last || r.Head.RemoteLSN != last {
t.Fatalf("plain seal retry failed: %+v last=%d err=%v", r, last, err)
}
if len(remote.keys) != chunks || remote.bytes != chunks*chunkBytes {
t.Fatalf("plain seal retransmitted completed chunks: successful=%d bytes=%d want=%d", len(remote.keys), remote.bytes, chunks*chunkBytes)
}
for sum, n := range remote.images {
if n != 1 {
t.Errorf("reuploaded unchanged payload %x count=%d", sum, n)
}
}
for _, key := range firstKeys {
found := false
for _, ref := range r.Head.Chunks {
if ref.Key == key {
found = true
}
}
if !found {
t.Errorf("completed first-attempt key not reused: %s", key)
}
}
for lba := 0; lba < chunks*pcChunkBlocks; lba++ {
want := make([]byte, 4096)
if lba%pcChunkBlocks == 0 {
want = block(byte(0x40 + lba/pcChunkBlocks))
}
if !bytes.Equal(headBlock(t, remote.MemChunkRemote, uint32(lba)), want) {
t.Fatalf("sealed image differs at lba=%d", lba)
}
}
}
@@ -30,10 +30,14 @@ type slowGuardStore struct {
stop chan struct{} // closed by release(): frees any held Put
stopOnce sync.Once
held atomic.Int64 // lease writes that were held and then completed
// Diagnostics only, printed when the test fails: when renewals succeeded.
t0 time.Time
lastOK atomic.Int64 // time since t0 of the latest successful renewal
maxGap atomic.Int64 // longest time between two successful renewals
}
func newSlowGuardStore(s authority.AuthorityStore) *slowGuardStore {
return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{})}
return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{}), t0: time.Now()}
}
// release disarms and frees every held Put; idempotent.
@@ -45,6 +49,15 @@ func (s *slowGuardStore) release() {
// renewed credits a successful renewal that started under generation g.
func (s *slowGuardStore) renewed(g int64) {
s.renewals.Add(1)
now := int64(time.Since(s.t0))
if prev := s.lastOK.Swap(now); prev != 0 {
for gap := now - prev; ; {
m := s.maxGap.Load()
if gap <= m || s.maxGap.CompareAndSwap(m, gap) {
break
}
}
}
for {
c := s.credited.Load()
if g <= c || s.credited.CompareAndSwap(c, g) {
@@ -162,13 +175,16 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
// so a renewal that waited for the store would deadlock this test. The
// sampler records any fence while armed; three held writes must complete.
var fenced atomic.Bool
var sinceOKAtFence atomic.Int64 // time since the latest successful renewal when the fence was first seen
sampled := make(chan struct{})
slow.armed.Store(true)
go func() {
defer close(sampled)
for slow.armed.Load() {
if !g.Projection().Healthy || stops.Load() != 0 {
fenced.Store(true)
if fenced.CompareAndSwap(false, true) {
sinceOKAtFence.Store(int64(time.Since(slow.t0)) - slow.lastOK.Load())
}
}
time.Sleep(20 * time.Millisecond)
}
@@ -182,7 +198,10 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
slow.armed.Store(false)
<-sampled
if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 {
t.Fatalf("guard fenced while lease writes were held behind renewals (held=%d renewals=%d stops=%d)", slow.held.Load(), slow.renewals.Load(), stops.Load())
// The gaps tell a starved runner (a gap near the 4 s validity) from a
// guard that fenced although renewals kept succeeding in time.
t.Fatalf("guard fenced while lease writes were held behind renewals (held=%d renewals=%d stops=%d); longest gap between successful renewals %s, time since the latest one when the fence was seen %s, validity 4s; the guard gives as cause: %q",
slow.held.Load(), slow.renewals.Load(), stops.Load(), time.Duration(slow.maxGap.Load()), time.Duration(sinceOKAtFence.Load()), g.FenceCause())
}
t.Logf("guard stayed healthy through %d held lease writes (%d renewals)", slow.held.Load(), slow.renewals.Load())
}
@@ -571,14 +571,11 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request)
var res ChunkDetachResponse
var err error
if req.Frozen {
frozen, ok := ctl.(interface {
DetachFrozen(context.Context, string, storage.FrozenDetachOptions) (ChunkDetachResponse, error)
})
if !ok {
writeChunkErr(w, http.StatusConflict, "frozen_detach_unsupported", false, "frozen detach unsupported")
return
}
res, err = frozen.DetachFrozen(ctx, req.VolumeID, storage.FrozenDetachOptions{StartedAt: time.Unix(0, req.FreezeStartedAtNs), AllowOverBudget: req.AllowOverBudget})
// Frozen detach is not supported in this release: refuse before any
// provider call. The request fields stay so the strict decoder keeps
// answering this typed refusal rather than an unknown-field 400.
writeChunkErr(w, http.StatusConflict, "frozen_detach_unsupported", false, "frozen detach is not supported in this release; stop the guest and send a plain detach")
return
} else if req.Plain {
plain, ok := ctl.(interface {
DetachPlain(context.Context, string) (ChunkDetachResponse, error)
@@ -5,10 +5,8 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"net/http"
"sync"
"testing"
"time"
)
@@ -31,8 +29,12 @@ func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) {
at := time.Now().Add(-time.Second).UnixNano()
body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at)
w := serve(t, s, http.MethodPost, "/chunk/detach", body, "")
if w.Code != 200 || p.calls != 1 || p.opts.StartedAt.UnixNano() != at || !p.opts.AllowOverBudget {
t.Fatalf("frozen wire lost fields: %d %s %+v", w.Code, w.Body, p.opts)
var refused chunkErrorBody
_ = json.Unmarshal(w.Body.Bytes(), &refused)
// Frozen detach is not supported in this release: a well-formed request
// is refused before the provider is called.
if w.Code != 409 || refused.Code != "frozen_detach_unsupported" || refused.Retryable || p.calls != 0 {
t.Fatalf("frozen request not refused before the provider: %d %s calls=%d", w.Code, w.Body, p.calls)
}
for _, invalid := range []string{`{"volumeID":"v1","frozen":true}`, `{"volumeID":"v1","allowOverBudget":true}`, fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, at)} {
before := p.calls
@@ -41,12 +43,10 @@ func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) {
t.Fatalf("invalid request reached provider: %d %s", w.Code, w.Body)
}
}
p.err = storage.ErrFrozenTailTooLarge
w = serve(t, s, http.MethodPost, "/chunk/detach", body, "")
var e chunkErrorBody
_ = json.Unmarshal(w.Body.Bytes(), &e)
if w.Code != 409 || e.Code != "frozen_tail_too_large" || !e.Retryable {
t.Fatalf("wrong frozen refusal: %d %s", w.Code, w.Body)
// The handler no longer reaches the provider's frozen path; its error
// mapping is checked directly.
if status, code, retry := chunkErrorCode(storage.ErrFrozenTailTooLarge); status != 409 || code != "frozen_tail_too_large" || !retry {
t.Fatalf("wrong frozen refusal: %d %s %t", status, code, retry)
}
for _, terminal := range []error{storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced, storage.ErrChunkCASOutcomeUnknown} {
expectedStatus, expectedCode, expectedRetry := chunkErrorCode(terminal)
@@ -108,7 +108,10 @@ func TestChunkFrozenValidationHasDistinctPreMutationCode(t *testing.T) {
}
}
func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) {
// Frozen detach is not supported in this release: even when the provider
// would answer with a frozen refusal that carries a freeze budget, the
// request is refused before the provider and the response carries no budget.
func TestChunkFrozenRequestRefusalCarriesNoBudget(t *testing.T) {
report := storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 5570 * time.Millisecond, FrozenEstimateKnown: true, FreezeLimit: 5 * time.Second}, Estimate: 5570 * time.Millisecond, RemainingFreeze: 4 * time.Second, GuestFreezeElapsed: time.Second, Reason: "frozen_tail_too_large"}
refusal := &storage.FrozenRefusal{Report: report}
p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}, err: refusal}
@@ -119,120 +122,14 @@ func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 409 {
t.Fatalf("refusal %d %s", w.Code, w.Body)
}
for key, want := range map[string]int64{"frozenEstimateNs": 5570000000, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": 0, "remainingFreezeNs": 4000000000, "guestFreezeElapsedNs": 1000000000} {
var value int64
if raw, ok := got[key]; !ok {
t.Errorf("missing %s: %s", key, w.Body)
} else if err := json.Unmarshal(raw, &value); err != nil || value != want {
t.Errorf("%s=%s want%d", key, raw, want)
var code string
_ = json.Unmarshal(got["code"], &code)
if code != "frozen_detach_unsupported" || p.calls != 0 {
t.Fatalf("frozen request reached the provider: %s calls=%d", w.Body, p.calls)
}
for _, key := range []string{"frozenEstimateNs", "frozenEstimateKnown", "freezeLimitNs", "maxRefreezeQuiesceNs", "remainingFreezeNs", "guestFreezeElapsedNs"} {
if _, ok := got[key]; ok {
t.Errorf("refusal carries %s: %s", key, w.Body)
}
}
var known bool
if err := json.Unmarshal(got["frozenEstimateKnown"], &known); err != nil || !known {
t.Errorf("known lost: %s", w.Body)
}
p.err = &storage.FrozenRefusal{Report: storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 300 * time.Millisecond, FreezeLimit: 5 * time.Second}, Estimate: 300 * time.Millisecond, Reason: "frozen_tail_too_large", RemainingFreeze: 5 * time.Second}}
w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "")
got = nil
_ = json.Unmarshal(w.Body.Bytes(), &got)
if string(got["frozenEstimateKnown"]) != "false" || string(got["maxRefreezeQuiesceNs"]) != "0" || string(got["frozenEstimateNs"]) != "300000000" {
t.Fatalf("unknown refusal became an actionable estimate: %s", w.Body)
}
p.err = errors.Join(storage.ErrChunkLayerClosed, refusal)
w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "")
got = nil
if json.Unmarshal(w.Body.Bytes(), &got) != nil {
t.Fatal(w.Body)
}
status, code, _ := chunkErrorCode(storage.ErrChunkLayerClosed)
var gotCode string
_ = json.Unmarshal(got["code"], &gotCode)
if w.Code != status || gotCode != code {
t.Fatalf("terminal precedence lost: %d %s", w.Code, w.Body)
}
if _, ok := got["frozenEstimateNs"]; ok {
t.Fatalf("terminal response offered retry budget: %s", w.Body)
}
}
// Hold a real admitted Sync through the replication observer, so the actual
// frontend drain expires before storage frozen admission. No report is injected.
type frozenDrainObserver struct{ entered, release chan struct{} }
func (*frozenDrainObserver) Observe(context.Context, uint32, uint64, []byte) error { return nil }
func (o *frozenDrainObserver) Sync(ctx context.Context, _ uint64) error {
close(o.entered)
select {
case <-o.release:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func TestChunkFrozenDrainRefusalCarriesObservedBudget(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
dp, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16,
ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, healthyView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = dp.Close() })
if _, err = dp.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = dp.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
backend, err := dp.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if _, err = backend.Write(ctx, 4096, make([]byte, 4096)); err != nil {
t.Fatal(err)
}
observer := &frozenDrainObserver{make(chan struct{}), make(chan struct{})}
if err = backend.(*durable.StorageBackend).SetWriteObserver(observer); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
var once sync.Once
t.Cleanup(func() {
once.Do(func() { close(observer.release) })
select {
case <-done:
case <-time.After(3 * time.Second):
t.Error("Sync did not join")
}
})
go func() { done <- backend.Sync(ctx) }()
select {
case <-observer.entered:
case <-ctx.Done():
t.Fatal("Sync never admitted")
}
before, _ := remote.GetHead(ctx)
puts := remote.Puts()
server := chunkServer(t, NewChunkControl(dp, nil), true)
body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, time.Now().Add(-time.Second).UnixNano())
response := serve(t, server, http.MethodPost, "/chunk/detach", body, "")
var got struct {
Code string `json:"code"`
storage.FrozenBudget
Remaining time.Duration `json:"remainingFreezeNs"`
Elapsed time.Duration `json:"guestFreezeElapsedNs"`
}
if err = json.Unmarshal(response.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if response.Code != 409 || got.Code != "frozen_tail_too_large" || got.FreezeLimit != 5*time.Second || got.Elapsed < time.Second || got.Remaining <= 0 || got.Elapsed+got.Remaining != got.FreezeLimit || got.FrozenEstimateKnown || got.MaxRefreezeQuiesce != 0 {
t.Fatalf("real drain refusal lost observation: %d %s", response.Code, response.Body)
}
after, _ := remote.GetHead(ctx)
if after.Gen != before.Gen || remote.Puts() != puts {
t.Fatal("failed drain uploaded or published")
}
}
@@ -0,0 +1,68 @@
package volume
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// refusedDetachProvider counts every detach entry point of the provider, so a
// refused request can be shown to reach none of them.
type refusedDetachProvider struct {
*frozenDetachProvider
detachCalls int
plainCalls int
}
func (p *refusedDetachProvider) DetachVolume(ctx context.Context, id string) (storage.ChunkCutResult, uint64, error) {
p.detachCalls++
return p.fakeChunkProvider.DetachVolume(ctx, id)
}
func (p *refusedDetachProvider) DetachVolumePlain(ctx context.Context, id string) (storage.ChunkCutResult, uint64, error) {
p.plainCalls++
return p.fakeChunkProvider.DetachVolume(ctx, id)
}
// A well-formed frozen detach is refused with a typed, non-retryable 409
// before the provider is called, with or without allowOverBudget.
func TestChunkDetachFrozenRefusedBeforeProvider(t *testing.T) {
p := &refusedDetachProvider{frozenDetachProvider: &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{
detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}}}
s := chunkServer(t, NewChunkControl(p, nil), true)
at := time.Now().Add(-time.Second).UnixNano()
for _, body := range []string{
fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, at),
fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at),
} {
w := serve(t, s, http.MethodPost, "/chunk/detach", body, "")
var got map[string]json.RawMessage
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("%s: body %s: %v", body, w.Body, err)
}
var code, message string
var retryable bool
_ = json.Unmarshal(got["code"], &code)
_ = json.Unmarshal(got["message"], &message)
_ = json.Unmarshal(got["retryable"], &retryable)
if w.Code != http.StatusConflict || code != "frozen_detach_unsupported" || retryable || message == "" {
t.Errorf("%s: got %d %s, want 409 frozen_detach_unsupported retryable=false", body, w.Code, w.Body)
}
if _, ok := got["frozenEstimateNs"]; ok {
t.Errorf("%s: refusal carries a freeze budget: %s", body, w.Body)
}
if p.calls != 0 || p.detachCalls != 0 || p.plainCalls != 0 {
t.Fatalf("%s: refused request reached the provider: frozen=%d detach=%d plain=%d", body, p.calls, p.detachCalls, p.plainCalls)
}
}
// The ordinary detach on the same server is unaffected.
w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1"}`, "")
if w.Code != http.StatusOK || p.detachCalls != 1 || p.calls != 0 {
t.Fatalf("ordinary detach after refusals: %d %s detach=%d frozen=%d", w.Code, w.Body, p.detachCalls, p.calls)
}
}
+2 -2
View File
@@ -99,7 +99,7 @@ func TestOwnBatch_CarriesGuestWrites(t *testing.T) {
// A chunk whose every block the guest overwrote and flushed before the walker
// reached it stays absent but is fully local: a batch owns it with no fetch
// (codex01 #340 S1: otherwise nothing ever cuts it and the driver stalls).
// (otherwise nothing ever cuts it and the driver stalls).
func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) {
fastWalker(t)
s, layer, remote, _ := hydrationFixture(t, 2, 64)
@@ -145,7 +145,7 @@ func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) {
}
// A failed ordinary cut remembers an equal-to-HEAD chunk without a key; the
// next batch must still upload it under an own key (codex01 #340 S2).
// next batch must still upload it under an own key.
func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) {
fastWalker(t)
s, layer, remote, _ := hydrationFixture(t, 2, 64)
@@ -278,7 +278,7 @@ func TestG1_InvalidOrMissingRecordRefusesTheListener(t *testing.T) {
}
// failAt makes one persistence step fail (the rest behave as on disk).
func failAt(t *testing.T, step string) {
func failAt(t *testing.T, ln *ReplicaListener, step string) {
t.Helper()
ops := osFloorOps
boom := errors.New("injected " + step + " failure")
@@ -294,6 +294,8 @@ func failAt(t *testing.T, step string) {
}
floorFS = ops
t.Cleanup(func() { floorFS = osFloorOps })
// A refusal/probe reply is not a join of the connection handler.
t.Cleanup(ln.StopHard)
}
// A mutation that would raise the floor is refused, with nothing applied and
@@ -308,7 +310,7 @@ func TestG1_PersistFailureRefusesTheRaisingMutation(t *testing.T) {
if err := ln.AdmitAsReplica(1); err != nil {
t.Fatal(err)
}
failAt(t, step)
failAt(t, ln, step)
if g1Ship(t, ln, store, g1Lineage(1, 2), 1, 's') {
t.Fatal("a ship raising the floor was applied though the floor write failed")
}
@@ -318,7 +320,7 @@ func TestG1_PersistFailureRefusesTheRaisingMutation(t *testing.T) {
if g1Rebuild(t, ln, store, g1Lineage(3, 2), 'r') {
t.Fatal("a rebuild raising the floor was written though the floor write failed")
}
floorFS = osFloorOps
// A current-floor ship does not persist: keep the fault armed until handlers join.
if !g1Ship(t, ln, store, g1Lineage(4, 1), 2, 'o') {
t.Fatal("a ship at the current floor was refused")
}
@@ -343,6 +345,8 @@ func TestG1_SlowPersistFailureIsStillARefusal(t *testing.T) {
}
floorFS = ops
t.Cleanup(func() { floorFS = osFloorOps })
// A refusal/probe reply is not a join of the connection handler.
t.Cleanup(ln.StopHard)
if g1Ship(t, ln, store, g1Lineage(1, 2), 1, 's') {
t.Fatal("a slow refused ship was classified as applied")
}
@@ -376,7 +380,7 @@ func TestG1_RoleCallsPersistBeforeReturning(t *testing.T) {
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
failAt(t, "rename")
failAt(t, ln, "rename")
if err := ln.AdmitAsReplica(3); err == nil {
t.Fatal("AdmitAsReplica returned nil though its floor write failed")
}
@@ -426,6 +430,8 @@ func TestG1_ConcurrentRaisesNeverLowerTheRecord(t *testing.T) {
}
floorFS = ops
t.Cleanup(func() { floorFS = osFloorOps })
// A refusal/probe reply is not a join of the connection handler.
t.Cleanup(ln.StopHard)
var wg sync.WaitGroup
wg.Add(2)
+61 -21
View File
@@ -211,6 +211,7 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th
stateDiagram-v2
[*] --> Admit
[*] --> Refused: invalid frozen request; invalid_freeze_budget; no provider mutation
[*] --> Refused: valid frozen request; frozen_detach_unsupported; no provider call
Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid
Admit --> PlainStop: plain detach and idle frontend lock acquired
PlainStop --> Quiesce: idle frontend closed; caller-bounded offline seal
@@ -244,16 +245,16 @@ stateDiagram-v2
| Step | Guard | Enforced in | Protects |
|---|---|---|---|
| Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` |
| Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` |
| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` |
| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` |
| Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` |
| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` |
| Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
| Guest-frozen detach | (Not reachable in this release; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` |
| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` |
| Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` |
| Pre-copy host drain | (Not reachable in this release; see the note below.) a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` |
| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` |
| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` |
@@ -264,6 +265,8 @@ stateDiagram-v2
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged.
Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes;
0 explicitly disables); they do not create named snapshots. One five-minute
context covers a cut, including uploads. Deadline-aborted uploads remain rooted
@@ -400,7 +403,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
163 rows: 141 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 148 new.
185 rows: 163 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 170 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.
@@ -518,7 +521,10 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE |
| `INV-WS-HEAD-BELT-001` | After a successful HEAD CAS, takeover or cut, the publisher acts on it only once a re-read of HEAD (the durable frontier) shows that CAS's generation, epoch and holder: a takeover opens I/O only then, a cut settles remoteLSN and the owned map and drops its intents only then. | M4 Claiming → Cooling → Holder; M5 CAS → Settled | `core/storage/chunk_head_belt.go` `casAndConfirmChunkHeadMeasured`, `confirmChunkHead`, `confirmChunkTakeover`; `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach` | `TestHeadBeltTakeoverRefusesLateOldCAS`, `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltConfirmationUsesOnlyRoot` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE |
| `INV-WS-HEAD-BELT-COOLING-001` | The HEAD cooling window W is 0 or at least 2.1 s (the 2 s HEAD operation deadline plus 100 ms settling); with W > 0 a takeover waits W after its CAS, on the local monotonic clock, before its confirming re-read. | M4 Claiming → Cooling → Holder | `core/storage/chunk_head_belt.go` `validateHeadCoolingWindow`, `confirmChunkTakeover`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestHeadBeltCoolingWindowCoversCASAndSettle`, `TestHeadBeltTakeoverWaitsBeforeConfirmation`, `TestHeadBeltSinglePointHasNoCoolingDelay`, `TestHeadBeltRetryOfUnconfirmedClaimStillCools` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-WS-HEAD-BELT-DEADLINE-001` | Each HEAD CAS and each HEAD confirmation re-read runs under its own deadline of at most 2 s on the local monotonic clock, nested inside the caller's context. | M4 Claiming → Cooling → Holder; M5 CAS | `core/storage/chunk_head_belt.go` `casChunkHead`, `confirmChunkHead`, `readChunkHead` | `TestHeadBeltOperationsHaveOwnDeadline` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-WS-HEAD-BELT-FENCE-001` | A publisher whose CAS failed or was not confirmed, and whose re-read shows a publication owner different from its own (another epoch, a lower one included, or another holder), fences without retrying the CAS. With an empty last known HEAD its own owner is its configured epoch and holder. | M4 Cooling → HolderFenced; M5 CAS → Fenced | `core/storage/chunk_head_belt.go` `publicationOwnerChanged`, `fencePublication`; `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach` | `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB |
@@ -528,7 +534,7 @@ Notes:
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE |
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
| `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns carries its lost range as stored before the issue (the kept HEAD's remote LSN, LostUntil in master time, the kept HEAD's generation and the HEAD entry's filer mtime read with that HEAD, or "unknown"), also on a replay and after a restart; `QueryWorkspaceLostRange` returns the same stored ranges, all of them in issue order or one by request id, never recomputed. A forced move whose range record is missing or fails its checks (the range checksum or the HEAD-time checksum) makes the readout fail (a grant without a range and with the reason; `DataLoss` from the query; CLI exit 4) and is never reported as no loss. A failure after the issue (e.g. the binding reconciliation) is answered as `Internal` naming the move ISSUED, never as a refusal; the client reports it as an unknown outcome with the same-request-id recovery (never a new request id), and the master's audit log records the issued forced move. An issuing write that may have reached the store but reported an error (memory unissued), and any move on a volume whose workspace persistence is already uncertain, fail with `ErrWorkspaceOutcomeUncertain` and are answered as an unknown outcome (`Internal`, restart then rerun with the same request id), logged as unknown, never as a refusal; admission refusals and failures before the issue stay `FailedPrecondition`. The client accepts a grant only when it matches the request (request id, volume, expected holder and epoch, target replica and host, a higher epoch; else unknown) and its range only when it names the same move and kept HEAD (volume, request id, epochs, old replica, HEAD generation, frontier = remote LSN; else unproven). `PreviewWorkspaceMove` runs the forced admission and writes nothing. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`, `decodeLostRangeHeadTimes`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `PreviewWorkspaceForcedMove`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/authority/authority.go` `applyWithWorkspaceMove`; `core/host/master/workspace_service.go` `MoveWorkspace`, `grantWithLostRange`, `postIssueError`, `issuedRecord`, `logForcedGrant`, `QueryWorkspaceLostRange`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove`, `checkGrant`, `checkRange`, `LostRanges`, `Readout`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange`, `shellCommand` | `TestWorkspaceForcedMoveStoresHeadFilerTime`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeAccumulatesInIssueOrder`, `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected`, `TestWorkspaceForcedMovePreviewWritesNothing` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`); `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven`, `TestForceMoveBindsGrantAndRange`, `TestLostRangesBindsTheAnswer`, `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row7_ReadoutUnproven`, `TestWorkspaceForceMove_Row8_RerunSameRequestID`, `TestWorkspaceForceMoveRecoveryCommandRuns`, `TestWorkspaceForceMoveRejectsAMismatchedAnswer`, `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`); `TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome` (`cmd/sw-block/workspace_postissue_test.go`); `TestWorkspaceForceMoveUncertainIssueWriteIsUnknown` (`cmd/sw-block/workspace_uncertain_test.go`) | — | ACTIVE |
@@ -543,7 +549,10 @@ Notes:
- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here.
- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models.
- `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun).
- `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged.
- `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. Stop-pending changes only when the guard renews, never what it admits, fences or acknowledges: see M4 Valid → StopPending. It clears only for the latest detach attempt, provably not applied, with serving resumed: see M4 StopPending → Valid. The 250 ms bound is on scheduling only; it does not bound the time from a revocation to its acknowledgement, which also includes a renewal already in flight, the drain and the ACK. The detach hook runs on the plain path only after the idle stop succeeds, so a busy plain detach never sets stop-pending.
- `INV-WS-HEAD-BELT-001`: an unconfirmed publication keeps its intents through Close: see `INV-CUT-INTENT-CLOSE-001`. The takeover half also follows from M4 Claiming → Holder ("an exact generation/epoch/holder readback"); the row is kept for the cut half, which no Part A guard states.
- `INV-WS-HEAD-BELT-COOLING-001`: the supported mode is a single serialization point with W = 0; a W > 0 window is explicit and experimental. ASSUMPTION (class TIME across hosts): W ≥ 2.1 s outlasts an old holder's in-flight CAS only if the filer applies no CAS more than 100 ms after its client's 2 s deadline, which runs on the old holder's clock. That margin is the CAS apply bound, the bound `INV-GC-GRACE-DEADLINE-001` and `INV-SNAP-DELETE-ANY-ORDER-001` name; here it is assumed to be at most 100 ms. The code cannot check it.
- `INV-WS-CAS-UNKNOWN-001`: Close keeps the intents of a proposal still pending: see `INV-CUT-INTENT-CLOSE-001`.
### B.5 Workspace: the cut pipeline
@@ -552,9 +561,11 @@ Notes:
| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE |
| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE |
| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE |
| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE |
| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRequestRefusalCarriesNoBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE |
| `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE |
| `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE |
| `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE |
| `INV-CUT-FROZEN-DETACH-REFUSED-001` | A detach request with `frozen` set is refused with HTTP409 `frozen_detach_unsupported`, retryable=false, before any provider call, admission or cut work. | M5 [*] → Refused (valid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach` | `TestChunkDetachFrozenRefusedBeforeProvider` (`core/host/volume/chunk_frozen_refused_test.go`), `TestChunkFrozenDetachWireContractAndPrecedence`, `TestChunkFrozenRequestRefusalCarriesNoBudget` (`core/host/volume/chunk_frozen_budget_test.go`) | — (request refusal) | ACTIVE |
| `INV-CUT-PRECOPY-FLAG-REFUSED-001` | blockvolume refuses to start with `--chunk-detach-precopy` set: flag validation fails with "--chunk-detach-precopy is not supported in this release", so no blockvolume process runs the pre-copy detach. | M5 Admit (pre-copy admission never entered) | `cmd/blockvolume/chunk_remote.go` `validateChunkFlags` | `TestChunkDetachPrecopyFlagRefused` (`cmd/blockvolume/chunk_remote_test.go`) | — (startup validation) | ACTIVE |
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
@@ -568,25 +579,43 @@ Notes:
| `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE |
| `INV-CUT-GUEST-BOUNDED-WAIT-001` | Inside an open cut window, a guest write to a candidate chunk waits only for local work, never for a remote fetch or upload: at most 250 ms for a saver slot (then only the cut aborts) and one local capture of the chunk's at-H image. | M5 OpenWindow → Copy (guest write during Copy / Upload) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `claim`, `acquireSaver`, `readCOWChunk`, `fillMissing` | `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained` (`core/storage/chunk_cut_cow_fill_test.go`) | `CutCOW2` `Blocked` defines which writes wait; remote I/O is not modelled | ACTIVE |
| `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE |
| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SpillCapAbortsTheCut` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE |
| `INV-CUT-PAYLOAD-BOUNDED-001` | One volume's cut upload workers, active COW savers and cached COW saves together hold at most its payload byte budget (default max(64 MiB, six chunks)), whatever the number of candidate chunks. | M5 Stage / Copy / Upload | `core/storage/chunk_cut_payload.go` `cutPayloadWorkers`; `core/storage/chunk_cut_cow.go` `installCOWWindow`, `save` | `TestCutPayloadBudgetBoundsSlots` (`core/storage/chunk_cut_payload_budget_test.go`); `TestCutBudgetRefusesBeforeBarrier` (`core/storage/chunk_cut_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE |
| `INV-CUT-PAYLOAD-MIN-001` | A chunk layer is not attached with a negative payload budget or an explicit one below six chunks; zero selects the default. | M5 Stage / Copy / Upload (layer attach) | `core/storage/chunk_layer.go` `attachChunkLayerImpl` | `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-SAVER-WAIT-001` | A write waits at most 250 ms, on the local monotonic clock, for a COW saver slot, holding no window lock and making no remote call; on expiry only the cut aborts and the write proceeds. | M5 Copy (COW save) | `core/storage/chunk_cut_cow.go` `acquireSaver`, `beforeCOWMutation` | `TestCutCOWV3_SaverCapacityAbortsWithoutParkingGuest`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutAbortReasonsAreCountedAndCopied` (`core/storage/chunk_review271_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-BUDGET-COW-001` | With a host Budget, each COW save reserves its chunk bytes on the cut's ticket while holding no window lock; a refused reservation or a revocation aborts only that cut, never the write. | M5 Copy → Aborted (budget revocation) | `core/storage/chunk_cut_cow.go` `save`; `core/storage/chunk_cut_budget.go` `reserve`; `core/storage/chunk_layer.go` `captureLocked` | `TestCutBudgetCOWRefusalAbortsOnlyCut` (`core/storage/chunk_cut_budget_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-BUDGET-RELEASE-001` | A cut's host Budget ticket is released only after all of that cut's COW savers and upload workers have returned, also after a revocation. | M5 Aborted, Closed | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/chunk_cut_cow.go` `join`; `core/storage/chunk_upload.go` `uploadBatch` | `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-SCRATCH-001` | Reading one block from a WAL batch record allocates block-sized scratch, not the record's size, and still verifies the whole-record CRC. | M5 Copy (cut read) | `core/storage/walstore_v3.go` `readRecordV3`, `readDirtyV3Into` | `TestV3ReadLargeBatchScratchIsBlockBounded` (`core/storage/chunk_review271_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-STREAM-001` | Each staging or cut upload worker holds one chunk image at a time, from its read through its PUT and retries; there is no payload queue and no whole-round copy. | M5 Stage, Copy → Upload | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_upload.go` `uploadBatch`, `putCapturedWith` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-SPILL-001` | A copy window's side-file bytes never exceed its cut's side-file cap (`COWSpillLimit`, default 1 GiB, lowered by free space: Part E); a save that would exceed it aborts the cut, returns its chunks to the dirty set and lets the write proceed. | M5 Copy → Aborted | `core/storage/chunk_cut_cow.go` `save`, `cowSpillLimit`; `core/storage/chunk_layer.go` `attachChunkLayerImpl`, `abortCut` | `TestCutCOWV3_SpillCapAbortsTheCut`, `TestChunkLayer_COWSpillLimitDefaultAndRefusal`, `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCOWSpillLimit_FromFreeSpace` (`core/storage/chunk_cut_cow_spillfree_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-SPILL-SOURCE-001` | Only a COW save made before a store mutation (`WriteContext`, `WriteBatchContext` or `applyEntryV3`) consumes side-file bytes; copy and upload workers never write the side file. | M5 Copy (COW save) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `copyCOWEntry`; `core/storage/walstore.go` `WriteContext`, `WriteBatchContext`; `core/storage/base_install_v3.go` `applyEntryV3` | `TestCutCOWV3_SpillWithinCapIsAccounted` (`core/storage/chunk_cut_cow_spillcap_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-JOIN-001` | Every upload worker of a cut or staging round has returned before that round's intents are cleaned up or its outcome is settled, also after an upload failure or cancellation. | M5 Upload → Closed, Aborted | `core/storage/chunk_upload.go` `uploadBatch`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | — | ACTIVE |
| `INV-CUT-ERROR-PRECEDENCE-001` | A chunk-control error body reports `cut_aborted` for a local cut abort even when the abort cancelled a remote upload, but an unknown CAS outcome, a fence or a closed or detached layer joined to it keeps its own code (`outcome_unknown`, `fenced`, `closing`). | M5 Copy, Upload → Aborted (HTTP error body) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestStatusServer_ChunkErrorBodyIsTyped` (`core/host/volume/chunk_control_test.go`) | — | ACTIVE |
| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE |
| `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, an intent naming every key of that kind the round preallocated is durable in the filer: one for all candidate chunks, however many upload waves the round uses, and one for all new segments. | M5 Intent → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_FailedPutIntentUploadsNothing` (`core/storage/chunk_layer_intent_test.go`); `TestCutPayloadIntentCountIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE |
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`); `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks.
Notes:
- `INV-CUT-TIMER-RESTART-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- `INV-CUT-TIMER-RESTART-001`, `INV-CUT-TIMER-SKIP-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal.
- `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting.
- `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests).
- `INV-CUT-READ-LOGICAL-001`: the staging clause (`readChunk` through `WALStore.Read`) is enforced by reading; no test captures WAL-only bytes through a staging round.
- `INV-CUT-GUEST-BOUNDED-WAIT-001`: the capture a write waits for is its own or that of the chunk's current copier or saver. Lazily absent blocks are left to the copier, which fills them from the base HEAD after it releases the entry.
- `INV-CUT-PAYLOAD-BOUNDED-001`: upload-worker buffers are not counted at run time; the budget reserves four chunk buffers per uploader and two per saver before any cached save is admitted (`cutPayloadWorkers`, `installCOWWindow`). Host-wide policy is a separate limiter module (`INV-HOST-CUT-BUDGET-001`). A host Budget admits a cut for this payload ceiling before staging or the barrier: see M5 Admit (test `TestCutBudgetRefusesBeforeBarrier`). Physical local I/O stays joined (`INV-CUT-COW-DRAIN-001`), and native at-H reads protect unsent candidates with COW (`INV-CUT-COW-OWNER-001`, `INV-CUT-HOOK-BEFORE-APPEND`).
- `INV-CUT-PAYLOAD-SPILL-SOURCE-001`: `applyEntryV3` (base install and replicated applies) runs the same COW hook, so it would charge the side file if a cut window were open. That is believed unreachable, since cut admission needs a healthy primary and no base install, but nothing prevents it (enforced by reading: none).
- `INV-CUT-ERROR-PRECEDENCE-001`: class ORDER, a wire contract: the order of the cases in `chunkErrorCode` decides which code a caller sees when one error carries several causes.
- `INV-CUT-INTENT-FIRST-001`: unused preallocated keys are harmless: they hold no payload and no binding. An intent is deleted only once the CAS outcome is known: see M6 intent live → removed.
- `INV-CUT-INTENT-CLOSE-001`: the one home of the Close rule; `INV-WS-HEAD-BELT-001` and `INV-WS-CAS-UNKNOWN-001` point here. "Unresolved" includes a CAS that failed or was not confirmed and whose re-read showed a foreign owner (the fence path, `INV-WS-HEAD-BELT-FENCE-001`). Those intents remain for later epoch fencing by GC (`INV-GC-INTENT-EXPIRY-001`).
- `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin.
@@ -598,11 +627,16 @@ Notes:
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE |
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and the scheduled-snapshot worker and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass`, `TestScheduledSnapshotLoop_StopJoinsTheAttempt` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
| `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-REACHABLE-001` | GC tombstones the binding and deletes the needle of a key only when no HEAD, snapshot, snapshot attempt (a deleting one within its grace) or live intent references the key in the current complete mark; those roots are durable catalog entries in the filer. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
| `INV-GC-REACHABLE-OWNER-001` | A ref qualified by an owner volume (`@<owner>/<key>`) in any root roots the owner's binding of that key, also after the owner's snapshot and volume are gone. | M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/chunk_remote.go` `keyLocation`; `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `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-DELETE-PROGRESS-001` | A definite HTTP 400 refusal of one needle DELETE does not end the GC pass: later eligible bindings are still reclaimed in that pass and every other candidate keeps its mark coverage. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `Collector.run`, `reclaimBinding`; `core/frontend/chunkstore/gc_execution.go` `executeGC`; `core/frontend/chunkstore/swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`); `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`) | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE |
| `INV-GC-CLOCK-SKEW-001` | GC counts a persisted timestamp as older than a threshold (grace or intent TTL) only when its age on the collector's wall clock exceeds the threshold plus the configured pairwise skew bound (default 1 min), plus 1 s for second-resolution binding times. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `Collector.run`, `NewCollector`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewPersistedCoverageAcrossHosts` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `EventuallyEligibleAtBound` | ACTIVE |
| `INV-GC-CLOCK-SKEW-FUTURE-001` | A capture intent, copy intent or deleting-snapshot stamp later than the collector's wall clock stays a root and does not stop the pass from expiring, settling or reclaiming other objects. | M6 intent expiry, deleting snapshot roots | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies`, `snapshotAttemptHeads` | `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement`, `TestGCSkewSnapshotDeleteGraceBothDirections` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `FutureProtects`, `IndependentProgress` | ACTIVE |
| `INV-GC-CLOCK-SKEW-MARK-001` | A GC mark supplies elapsed coverage only if it is complete, was written with the same grace, intent TTL, skew bound and operation deadline, and is not later than the collector's wall clock; a backward clock step since the last in-process pass discards coverage. | M6 GC clock admission | `core/frontend/chunkstore/gc_execution.go` `executeGC`, `readMark`; `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewPersistedCoverageAcrossHosts` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | — | ACTIVE |
| `INV-GC-CLOCK-SKEW-MARK-FORMAT-001` | A saved GC mark that fails validation (entry kind, token, format, scope, base, durations, times or candidate entries) makes the GC run fail before it changes anything. | M6 GC clock admission | `core/frontend/chunkstore/gc_execution.go` `readMark`, `executeGC` | `TestGCSkewConfigAndMarkCoverage` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | — | ACTIVE |
| `INV-GC-COPY-SETTLE-001` | GC deletes a snapshot or fork copy intent past its deadline only after an exclusive create at the copy's target settles it: GC's aborted tombstone (attempt entry or HEAD) or the published one already there; an unknown claim or read keeps the intent. | M6 HEAD: — → `aborted`; M6 copy intent: live → removed | `core/frontend/chunkstore/gc_copy.go` `SweepCopies`; `core/frontend/chunkstore/catalog.go` `AbortSnapshot`, `AbortFork` | `TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease`, `TestGC_CopySweepClaimsForkHEADNotExistingVolume`, `TestGC_CopyClaimUnknownRetainsIntent` (`core/frontend/chunkstore/gc_copy_test.go`); `TestFork_TombstoneLosesToPublishedFork` (`core/frontend/chunkstore/catalog_tombstone_test.go`) | — | ACTIVE |
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE |
| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie), never a rebuilt one. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`); `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`) | — | ACTIVE |
| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and past its age bound, and restarts when a mark finds it rooted or its binding changed; a deleting snapshot attempt roots its keys until its deleting time is past the grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
@@ -628,7 +662,7 @@ Notes:
| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE |
| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`nc_red_SnapDuringRestore`) | ACTIVE |
| `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED |
| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE |
| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fetches a chunk only through that chunk's shared fill flight: at most one fetch per chunk absence, and a fetched block is never installed over a block written locally. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `nextHydrateTarget`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked`; `core/storage/chunk_layer.go` `fillOnce` | `TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage`, `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE |
| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE |
| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE |
| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE |
@@ -637,6 +671,12 @@ Notes:
Notes:
- `INV-GC-REACHABLE-001`: an unrooted key's binding is tombstoned and its needle deleted only after the two-mark, binding-age and unchanged-binding checks: see M6 bound → tombstoned, needle deleted. The binding itself is never removed (`INV-CHUNK-WRITE-ONCE-001`). A snapshot whose name record still exists, deleting or not, is rooted with no grace limit; that over-protects, which is safe.
- `INV-GC-REACHABLE-OWNER-001`: this is what forks and restores rely on: a target's HEAD keeps the source's chunks live after the source snapshot and the source volume are gone.
- `INV-GC-DELETE-PROGRESS-001`: the refused needle keeps its tombstone and fid and is retried in a later pass; it is never counted as reclaimed and is reported in FailedDeletes. ExecuteGC saves the complete mark before it returns the partial failure. Any other DELETE error, a metadata error or cancellation still fails the pass. See M6 tombstoned, DELETE rejected → tombstoned, retry later.
- `INV-GC-CLOCK-SKEW-001`: these rows assume every timestamp writer (cut hosts for intents, the filer for binding crtime, GC hosts for marks and delete stamps) stays within the configured pairwise skew bound of the collector; no finite grace is safe without that bound. Within one process, in-memory mark times keep Go's monotonic reading; persisted marks and catalog stamps are wall time. Copy intents are not covered: their settlement is an order fact (`INV-GC-COPY-SETTLE-001`).
- `INV-GC-COPY-SETTLE-001`: class ORDER, not TIME. The deadline only admits the claim and is compared with no skew margin, and none is needed: a late publish of the copy loses to the exclusive aborted tombstone at the target.
- `INV-RESTORE-HYDRATE-001`: the walker yields while any flight has a guest waiter, retrying after a backoff of 20 ms that doubles up to 2 s; each fill holds one host-limiter permit (no cut payload, the caller's class), released only after that flight's I/O settles, also on cancel, revocation or close: see M4 Holder (background hydrate). "Never over a local write" is the install check in `fillOnce`, shared with guest read misses (`INV-CUT-READMISS-001`). The production caller is the restore driver (M6 restore Restoring → Hydrating, `INV-RESTORE-DRIVER-001`).
- `INV-GC-DELETE-EXACT-FID-001`: what happens after a rejected or failed delete is `INV-GC-DELETE-PROGRESS-001`. The tombstone-before-delete order is asserted only through a rejected delete; on a successful delete it is enforced by reading. The cookie check itself is done by the SeaweedFS volume server, not by this repository.
- `INV-GC-GRACE-RESTART-001`: "past the grace" means past the grace plus the clock-skew bound of `INV-GC-CLOCK-SKEW-001`. The restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test.
- `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code.
@@ -745,8 +785,8 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a
| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work |
|---|---|---|---|---|
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; HTTP requires positive timeoutMs before provider dispatch; no live-serving timer | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes.
+1 -1
View File
@@ -516,7 +516,6 @@ limit 50, no physical I/O latency. Raw quantities and JSON preservation are
checked by native Go tests; this derived arithmetic model does not model the HTTP
encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun.
#344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard.
2026-11-21 offline-seal extension: `PlainDetach` now includes frontend Close,
@@ -572,3 +571,4 @@ HEAD-read deadline/cancellation controls in
controls in `TestWorkspaceUncertaintyPrecedesRequestRefusal`. Actual request
cancellation retains its own controls, including a conflicting dependency status.
These are reply-classification claims, not authority-durability or delivery proof.
#344 review qualification: `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. (The HTTP-level drain refusal test was removed when `/chunk/detach` stopped admitting frozen requests in this release.) `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard.
@@ -285,3 +285,102 @@ step stops it. In order, it:
The script's default engine is `SW_BLOCK_DURABLE_IMPL=smartwal`; the command
above sets `walstore`, the engine used by the Kubernetes chart and the
workspace path. There is no equivalent script for ublk yet.
## Snapshots, restore and space (walstore-chunk)
**Recovery point.**
- **A stopped volume** keeps everything it acknowledged, on its host.
- **If the host is lost,** the volume is restored from its last cut. With the defaults (periodic capture off, one scheduled snapshot a day), that cut is at most one day old.
- **For a newer recovery point,** cut more often (`--chunk-capture-interval`, at least 5 minutes), or take a snapshot right before risky work.
**Consistency.** A snapshot is crash-consistent:
- it holds every write the volume acknowledged up to the cut;
- a guest file system restored from it replays its journal;
- data an application had not fsynced may be missing.
The commands below use these placeholders:
- `FILER` is the SeaweedFS filer gRPC address (`--chunk-filer`).
- `MASTER` is the blockmaster address the blockvolumes use.
- `WEED_MASTER` is the SeaweedFS master HTTP address.
- `STATUS` is a blockvolume's status address (its `--status-addr`, with `--chunk-control-endpoint` set).
**About the control endpoint.** `--chunk-control-endpoint` carries destructive operations (cut, snapshot, snapshot delete, detach, restore) on the status listener.
- **Binding:** that listener binds loopback addresses only, unless `--allow-external-status-bind` is set.
- **No authentication:** nothing authenticates it in this release. Keep it on loopback, or behind your own access control.
### Scheduled snapshots
- **Schedule:** with the default `--chunk-snapshot-schedule=daily:7`, each attached volume takes one named snapshot (`sched-<UTC time>`) once per 24 h, at a per-volume offset rather than at a wall-clock hour.
- **Retention:** keeps the newest 7 scheduled snapshots. It counts only the scheduled class, so other snapshots are not affected.
- **Deleting by hand:** scheduled snapshots are safe to delete with `snapshot-delete` like any other.
- **Restoring volumes:** a volume still restoring is skipped, and the skip is counted.
- **Status:** `GET STATUS/status/durable?volume=<id>` shows the schedule under `Chunk.ScheduledSnapshot`: `lastOkNs`, `nextDueNs`, `lastFailure`, `skipped` and `snapshot_overdue`.
```bash
sw-block ops chunk snapshots --volume v1 --chunk-filer FILER # list
sw-block ops chunk snapshot --volume v1 --name before-upgrade --status-addr STATUS # take one now
```
### Deleting snapshots and getting space back
Space comes back in two steps. Neither is immediate.
1. **GC deletes the chunks**, after the grace. The grace is `sw-block ops chunk gc --grace`, **1 hour by default**.
- A deleted snapshot keeps its chunks rooted for the grace after the delete.
- A chunk is then reclaimed only once two complete GC marks, at least the grace apart, have both seen it unreferenced.
- With the default grace, a deleted snapshot's chunks are reclaimed about **2 hours** after the delete. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that.
- Automatic GC is off by default (`--chunk-maintenance-gc`), so run the passes yourself:
```bash
sw-block ops chunk snapshot-delete --volume v1 --name sched-20261120T031204Z --chunk-filer FILER
# one hour or more later, and again one hour or more after that:
sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply
```
- Each pass prints its `Candidates`, `Reclaimed` and `failed_deletes`.
- A chunk shows as a candidate in the first pass that sees it and is reclaimed in a later pass.
- Without `--apply`, a pass is read-only.
2. **SeaweedFS vacuum compacts the volume files.** Reclaimed chunks are deleted needles.
- SeaweedFS counts them at once in `DeletedByteCount`.
- The disk space returns only when SeaweedFS vacuums those volumes, which runs asynchronously.
To check the count, and to ask for a vacuum now:
```bash
curl http://WEED_MASTER/vol/status # DeletedByteCount per volume
curl "http://WEED_MASTER/vol/vacuum?garbageThreshold=0.01" # compact volumes with more than 1% garbage
# or, in weed shell: volume.list and volume.vacuum -garbageThreshold 0.01
```
Check the data afterwards. `--depth data` reads every chunk once.
| Exit | Meaning |
|---|---|
| 0 | clean |
| 3 | the pass found problems |
| 1 | the pass could not complete, for example a filer or master is unreachable; the partial result is printed |
| 2 | the command could not run: a usage error, or the filer is not the only filer of its group (it refuses to start) |
```bash
sw-block ops chunk verify --volume v1 --chunk-filer FILER --all-snapshots --depth data --timeout 30m
```
### Restoring a snapshot into a new volume
A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards.
1. **Add the target to blockmaster.** Add the target volume (for example `v2`) to blockmaster's topology, and start a blockvolume for it with the same chunk settings (`--chunk-filer`, `--chunk-path`, `--chunk-control-endpoint`) and the source's geometry.
2. **Create the restore and start it:**
```bash
sw-block ops chunk restore --source v1 --snapshot sched-20261120T031204Z --target v2 --chunk-filer FILER --status-addr STATUS_OF_V2
```
This creates `v2` from the snapshot (idempotent by `--request-id`; the generated id is printed, so reuse it to retry) and starts the restore driver in v2's blockvolume.
- **Before the target is attached:** run the same command without `--status-addr` to create `v2`. Once its blockvolume is up, run `sw-block ops chunk restore --volume v2 --status-addr STATUS_OF_V2` to start the driver.
3. **v2 serves at once.** It reads chunks it does not hold yet from the source's snapshot.
- Meanwhile the driver fetches every chunk and re-uploads them under v2's own keys.
- It then marks v2 independent: phases `hydrating`, then `owning`, then `independent`.
- Follow it with `sw-block ops chunk restore --volume v2 --status-addr STATUS_OF_V2 --status`.
- Until v2 is independent, a snapshot of v2 is refused (`restore_incomplete`).
- While v2 still fetches chunks, its scheduled snapshots are skipped and counted as `restoring`. After that, until it is independent, they are refused like any snapshot and show as failed attempts with that code.
@@ -1,25 +1,32 @@
// Package invcheck checks docs/design/invariants.md against the code: the
// row count it states is the count its tables hold, every Go test a row
// names exists, and an ACTIVE row names at least one test.
// names exists, an ACTIVE row names at least one test, and a statement is
// short (one property per row).
package invcheck
import (
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"unicode/utf8"
)
type invRow struct {
id string
tests []string
status string
line int
id string
statement string
tests []string
status string
line int
}
// maxStatement is the longest Statement cell, in characters, a row may have.
const maxStatement = 300
var (
rowID = regexp.MustCompile("^\\| `(INV-[A-Z0-9-]+)` \\|")
testName = regexp.MustCompile("`(Test[A-Za-z0-9_]+)`")
@@ -70,7 +77,7 @@ func partB(t *testing.T, root string) ([]invRow, string) {
t.Errorf("invariants.md:%d: row %s has %d cells, want 7", firstLine+i, m[1], len(cells))
continue
}
r := invRow{id: m[1], status: strings.TrimSpace(cells[6]), line: firstLine + i}
r := invRow{id: m[1], statement: strings.TrimSpace(cells[1]), status: strings.TrimSpace(cells[6]), line: firstLine + i}
for _, tm := range testName.FindAllStringSubmatch(cells[4], -1) {
r.tests = append(r.tests, tm[1])
}
@@ -183,3 +190,77 @@ func TestInvariantRowCountMatchesTables(t *testing.T) {
t.Fatalf("invariants.md says %q; its tables hold %q", m, want)
}
}
// TestInvariantStatementsAreShort checks that the Statement of every row that
// is not ARCHIVED is at most maxStatement characters, except the rows named in
// testdata/long-statements.txt. That list only shrinks: it must be sorted,
// name each row once, and name only rows that exist and are still too long.
func TestInvariantStatementsAreShort(t *testing.T) {
root := repoRoot(t)
rows, _ := partB(t, root)
const list = "internal/invcheck/testdata/long-statements.txt"
raw, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(list)))
if err != nil {
t.Fatal(err)
}
listed := map[string]int{}
prev := ""
for i, line := range strings.Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n") {
id := strings.TrimSpace(line)
if id == "" || strings.HasPrefix(id, "#") {
continue
}
if at, dup := listed[id]; dup {
t.Errorf("%s:%d: %s is also at line %d", list, i+1, id, at)
continue
}
if id < prev {
t.Errorf("%s:%d: %s is not in sorted order (after %s)", list, i+1, id, prev)
}
listed[id], prev = i+1, id
}
exists := map[string]bool{}
for _, r := range rows {
exists[r.id] = true
n := utf8.RuneCountInString(r.statement)
long := r.status != "ARCHIVED" && n > maxStatement
at, ok := listed[r.id]
switch {
case long && !ok:
t.Errorf("invariants.md:%d: %s has a %d-character statement, over %d: split it into rows of one property each", r.line, r.id, n, maxStatement)
case !long && ok:
t.Errorf("%s:%d: %s is no longer over %d characters (%d, %s): delete its line", list, at, r.id, maxStatement, n, r.status)
}
}
for id, at := range listed {
if !exists[id] {
t.Errorf("%s:%d: %s is not a row of invariants.md: delete its line", list, at, id)
}
}
// The list only shrinks. Its size is pinned here, so a new exception needs
// an edit of this constant, and where the base commit is at hand every
// listed row must already have been listed there.
if len(listed) != longStatementsLeft {
t.Errorf("%s names %d rows, longStatementsLeft is %d: lower the constant when a line is deleted; it is never raised", list, len(listed), longStatementsLeft)
}
base, err := exec.Command("git", "-C", root, "show", "HEAD^1:"+list).Output()
if err != nil {
t.Logf("no base version of %s (%v): the only-shrink comparison is skipped", list, err)
return
}
was := map[string]bool{}
for _, line := range strings.Split(strings.ReplaceAll(string(base), "\r\n", "\n"), "\n") {
if id := strings.TrimSpace(line); id != "" && !strings.HasPrefix(id, "#") {
was[id] = true
}
}
for id, at := range listed {
if !was[id] {
t.Errorf("%s:%d: %s was not listed in the base commit: the list only shrinks", list, at, id)
}
}
}
// longStatementsLeft is the number of rows testdata/long-statements.txt may
// name. It only goes down.
const longStatementsLeft = 28
@@ -0,0 +1,29 @@
# Part B rows whose Statement is over 300 characters. This list only shrinks: split a row into rows of one property each, then delete its line; never add one.
INV-AUTH-PERSIST-BEFORE-PUBLISH-001
INV-FE-NVME-READY-001
INV-HOST-CUT-BUDGET-001
INV-LEASE-VIEW-001
INV-PROMOTE-FRONTIER-001
INV-REPL-NO-PER-LBA-DATA-REGRESSION
INV-WAL-DATA-SYNC-001
INV-WAL-V3-ACTIVATION-001
INV-WAL-V3-ADMISSION-001
INV-WAL-V3-BASE-001
INV-WAL-V3-BATCH-001
INV-WAL-V3-BINDING-001
INV-WAL-V3-CATCHUP-001
INV-WAL-V3-DESCRIPTOR-001
INV-WAL-V3-FENCE-001
INV-WAL-V3-INSTALL-ACK-001
INV-WAL-V3-MAP-BYTES-001
INV-WAL-V3-MAP-PUBLISH-001
INV-WAL-V3-PUBLISH-001
INV-WAL-V3-RECLAIM-001
INV-WAL-V3-RECORD-001
INV-WAL-V3-RESET-001
INV-WAL-V3-W-001
INV-WS-FORCED-CONFIRM-001
INV-WS-FORCED-MOVE-001
INV-WS-FREEZE-REFUSAL-001
INV-WS-LEASE-HORIZON-001
INV-WS-LOST-RANGE-READOUT-001