diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index 9e58424413..6b2ea197c5 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -12,8 +12,12 @@ import ( const precopyQueueBudget = 5 * time.Second +var errPrecopyPaused = fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + type precopyWaiter struct { ready chan struct{} + deadline time.Time + err error signaled bool } type precopyAdmission struct { @@ -48,7 +52,7 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) once.Do(func() { b.mu.Lock() if b.precopy == p { - b.finishPrecopyLocked(b.operational.Load() && !b.closed) + b.finishPrecopyLocked() } b.mu.Unlock() }) @@ -73,30 +77,26 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) } } -func signalPrecopy(w *precopyWaiter) { - if !w.signaled { - close(w.ready) - w.signaled = true - } -} - -// Caller owns mu. Resume admits the old queue serially; a terminal stop wakes -// every command to observe the terminal gate, without issuing storage I/O. -func (b *StorageBackend) finishPrecopyLocked(resume bool) { +// Caller owns mu. INV-CUT-PRECOPY-001: ending the pause releases every +// waiter in FIFO admission order in this one lock hold, then normal gate checks +// and completion run independently. New arrivals cannot join the ended pause. +func (b *StorageBackend) finishPrecopyLocked() { p := b.precopy if p == nil { return } p.active = false - if !resume { - for _, w := range p.waiters { - signalPrecopy(w) + b.precopy = nil + for _, w := range p.waiters { + // INV-CUT-PRECOPY-001: expiry versus grant is decided under mu. + if !time.Now().Before(w.deadline) { + w.err = context.DeadlineExceeded + } + w.signaled = true + close(w.ready) + if hook := b.testPrecopyGranted; hook != nil && w.err == nil { + hook(w) } - b.precopy = nil - } else if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) } } @@ -112,69 +112,67 @@ func (b *StorageBackend) removePrecopyWaiter(p *precopyAdmission, w *precopyWait break } } - if !p.active { - if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) - } - } } // An unqueued caller races the pause only at admit's final registration check. // Waiting callers own no I/O lock and execute no storage/observer operation. func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), error)) (func(), error) { + arrival := time.Now() // INV-CUT-PRECOPY-001: one command-owned wait budget. for { b.mu.Lock() p := b.precopy - if p == nil { - b.mu.Unlock() - release, err := admit() - if err != nil { - b.mu.Lock() - pending := b.precopy != nil - b.mu.Unlock() - if pending { - continue - } + + b.mu.Unlock() + if p != nil { + if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { + return nil, err } - return release, err - } - b.mu.Unlock() - if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { - return nil, err - } - b.mu.Lock() - if b.precopy != p { + b.mu.Lock() + if b.precopy != p { + b.mu.Unlock() + continue + } + deadline := arrival.Add(precopyQueueBudget) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + w := &precopyWaiter{ready: make(chan struct{}), deadline: deadline} + p.waiters = append(p.waiters, w) b.mu.Unlock() - continue - } - w := &precopyWaiter{ready: make(chan struct{})} - p.waiters = append(p.waiters, w) - if !p.active && len(p.waiters) == 1 { - signalPrecopy(w) - } - deadline := p.started.Add(precopyQueueBudget) - b.mu.Unlock() - if hook := b.testPrecopyQueued; hook != nil { - hook() - } - waitCtx, cancel := context.WithDeadline(ctx, deadline) - select { - case <-w.ready: - case <-waitCtx.Done(): - } - cause := waitCtx.Err() - cancel() - if cause != nil { - b.removePrecopyWaiter(p, w) - return nil, b.attachReadyTimeout(cause) + if hook := b.testPrecopyQueued; hook != nil { + hook() + } + waitCtx, cancel := context.WithDeadline(ctx, deadline) + select { + case <-w.ready: + case <-waitCtx.Done(): + } + b.mu.Lock() + cause := waitCtx.Err() + if w.signaled { + cause = w.err + } + b.mu.Unlock() + // A timely queue grant cannot outlive the command's own deadline. + if cause == nil { + cause = ctx.Err() + } + cancel() + if cause != nil { + b.removePrecopyWaiter(p, w) + return nil, b.attachReadyTimeout(cause) + } } release, err := admit() - if err != nil { - b.removePrecopyWaiter(p, w) - return nil, err + // INV-CUT-PRECOPY-001 / INV-FE-LINEAGE-GATE-001: retry only the pause. + if errors.Is(err, errPrecopyPaused) { + b.mu.Lock() + pending := b.precopy != nil + b.mu.Unlock() + if pending { + continue + } } - return func() { release(); b.removePrecopyWaiter(p, w) }, nil + return release, err } } diff --git a/seaweed-block/core/frontend/durable/precopy_arrival_test.go b/seaweed-block/core/frontend/durable/precopy_arrival_test.go new file mode 100644 index 0000000000..c3da43764f --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_arrival_test.go @@ -0,0 +1,314 @@ +package durable + +import ( + "context" + "errors" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// INV-CUT-PRECOPY-001: an active pause may predate this command. Its queue +// allowance is measured once from this command's arrival, capped by its caller. +func TestPrecopyQueueBoundStartsAtCommandArrival(t *testing.T) { + for _, caller := range []time.Duration{2 * time.Second, 10 * time.Second} { + t.Run(caller.String(), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + resume, err := b.BeginPrecopyPause(context.Background()) + if err != nil { + t.Fatal(err) + } + defer resume() + // Let the active pause get older than five seconds before this arrival. + time.Sleep(6 * time.Second) + ctx, cancel := context.WithTimeout(context.Background(), caller) + defer cancel() + queued, done := make(chan struct{}), make(chan error, 1) + b.testPrecopyQueued = func() { close(queued) } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + joined := false + t.Cleanup(func() { + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("arrival-bounded waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + bound := 5 * time.Second + if caller < bound { + bound = caller + } + time.Sleep(bound - time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + t.Fatalf("fresh waiter inherited old pause deadline: %v", err) + default: + } + time.Sleep(time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expiry classification: %v", err) + } + default: + t.Fatal("arrival/caller deadline did not bound the waiter") + } + select { + case <-observed: + t.Fatal("expired paused waiter reached physical Sync") + default: + } + }) + }) + } +} + +// The queue grant and its deadline have one decision boundary even when a +// descheduled waiter cannot run until after its queue timer would have expired. +func TestPrecopyResumeGrantVersusExpiry(t *testing.T) { + for _, outcome := range []string{"grant-before-queue-expiry", "expiry-before-grant", "caller-expiry", "close-after-grant"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + caller := 10 * time.Second + if outcome == "caller-expiry" { + caller = 4 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), caller) + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceed := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(proceed) }) } + b.testPrecopyQueued = func() { close(queued); <-proceed } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + t.Cleanup(func() { + release() + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("boundary waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + if outcome == "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + resume() + if outcome != "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + if outcome == "close-after-grant" { + _ = b.Close() + } + release() + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("grant boundary did not settle") + } + switch outcome { + case "grant-before-queue-expiry": + if result != nil { + t.Fatalf("timely grant lost to later queue expiry: %v", result) + } + case "close-after-grant": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close did not retain terminal precedence: %v", result) + } + default: + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) { + t.Fatalf("expiry not refused as typed busy: %v", result) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused waiter performed Sync") + } + default: + if result == nil { + t.Fatal("successful grant did not perform Sync") + } + } + }) + }) + } +} + +func TestPrecopyGrantedWaiterFollowsReplacementPause(t *testing.T) { + for _, outcome := range []string{"resume", "caller-cancel", "close", "original-deadline"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + resumeA, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceedA := make(chan int, 2), make(chan struct{}) + calls := 0 + var once sync.Once + releaseA := func() { once.Do(func() { close(proceedA) }) } + b.testPrecopyQueued = func() { + calls++ + queued <- calls + if calls == 1 { + <-proceedA + } + } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + resumeB := func() {} + t.Cleanup(func() { + releaseA() + cancel() + resumeA() + resumeB() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("replacement-pause waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case n := <-queued: + if n != 1 { + t.Fatal("first pause registration missing") + } + case err := <-done: + joined = true + t.Fatalf("command ended before first pause registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + time.Sleep(2 * time.Second) + resumeA() + resumeB, err = b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + releaseA() + synctest.Wait() + select { + case n := <-queued: + if n != 2 { + t.Fatalf("requeue=%d", n) + } + case err := <-done: + joined = true + t.Fatalf("granted waiter returned replacement pause Busy instead of requeueing: %v", err) + default: + t.Fatal("waiter did not join replacement pause") + } + select { + case <-observed: + t.Fatal("waiter crossed replacement pause") + default: + } + switch outcome { + case "resume": + resumeB() + case "caller-cancel": + cancel() + case "close": + _ = b.Close() + case "original-deadline": + time.Sleep(3 * time.Second) + } + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("replacement boundary did not settle") + } + switch outcome { + case "resume": + if result != nil { + t.Fatal(result) + } + case "close": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close priority: %v", result) + } + case "caller-cancel": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.Canceled) { + t.Fatalf("caller priority: %v", result) + } + case "original-deadline": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) || ctx.Err() != nil { + t.Fatalf("requeue reset command allowance: %v ctx=%v", result, ctx.Err()) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused replacement waiter performed Sync") + } + default: + if result == nil { + t.Fatal("resumed replacement waiter did not Sync") + } + } + }) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index 7b41c5f2fe..ce8644ad14 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -83,100 +83,6 @@ func TestPrecopyHostDrainDoesNotCompleteHeldGuestIO(t *testing.T) { } } -func TestPrecopyQueueResumesInFIFOOrder(t *testing.T) { - b := precopyMemoryBackend(t) - ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) - queued := make(chan struct{}, 4) - b.testPrecopyQueued = func() { queued <- struct{}{} } - first, release := make(chan struct{}), make(chan struct{}) - var once sync.Once - unpark := func() { once.Do(func() { close(release) }) } - seen := make(chan byte, 4) - if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { - seen <- v - if v == 1 { - close(first) - select { - case <-release: - case <-ctx.Done(): - } - } - }}); err != nil { - t.Fatal(err) - } - resume, err := b.BeginPrecopyPause(ctx) - if err != nil { - t.Fatal(err) - } - var wg sync.WaitGroup - joined := make(chan struct{}) - errs := make(chan error, 4) - t.Cleanup(func() { - cancel() - unpark() - resume() - _ = b.Close() - go func() { wg.Wait(); close(joined) }() - select { - case <-joined: - case <-time.After(3 * time.Second): - t.Error("queue workers did not join") - } - }) - start := func(v byte) { - wg.Add(1) - go func() { defer wg.Done(); _, err := b.Write(ctx, 0, bytes.Repeat([]byte{v}, 4096)); errs <- err }() - select { - case <-queued: - case <-ctx.Done(): - t.Fatal("command was not queued") - } - } - start(1) - start(2) - start(3) - resume() - select { - case <-first: - case <-ctx.Done(): - t.Fatal("first queued write did not enter") - } - start(4) // New arrivals cannot bypass the old queue during an aborted cut. - if v := <-seen; v != 1 { - t.Fatalf("first write=%d", v) - } - select { - case v := <-seen: - t.Fatalf("write %d bypassed held FIFO head", v) - case <-time.After(30 * time.Millisecond): - } - unpark() - for _, want := range []byte{2, 3, 4} { - select { - case got := <-seen: - if got != want { - t.Fatalf("write=%d want%d", got, want) - } - case <-ctx.Done(): - t.Fatal("FIFO queue did not drain") - } - } - for i := 0; i < 4; i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-ctx.Done(): - t.Fatal("queued write did not finish") - } - } - data := make([]byte, 4096) - if _, err := b.Read(ctx, 0, data); err != nil || data[0] != 4 { - t.Fatalf("ordered final bytes=%d err=%v", data[0], err) - } -} - func TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture(t *testing.T) { b := precopyMemoryBackend(t) entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) @@ -258,7 +164,7 @@ func TestPrecopyQueueUsesFiveSecondCutoverBudget(t *testing.T) { // Releasing that lock before the fallback must not replace the pause identity. func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { for _, terminal := range []bool{false, true} { - name := "resume_fifo" + name := "resume_all" if terminal { name = "close" } @@ -365,12 +271,14 @@ func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { default: } } else { - for _, want := range []byte{1, 2} { + seenWrites := map[byte]bool{} + for i := 0; i < 2; i++ { select { case got := <-seen: - if got != want { - t.Fatalf("FIFO got %d want %d", got, want) + if got < 1 || got > 2 || seenWrites[got] { + t.Fatalf("unexpected resumed write %d", got) } + seenWrites[got] = true case <-ctx.Done(): t.Fatal("missing write") } diff --git a/seaweed-block/core/frontend/durable/precopy_resume_test.go b/seaweed-block/core/frontend/durable/precopy_resume_test.go new file mode 100644 index 0000000000..1f4c528663 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_resume_test.go @@ -0,0 +1,192 @@ +package durable + +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +// INV-CUT-PRECOPY-001: a completed pause releases admission, not one +// whole storage operation at a time. Independent LBAs must run concurrently. +func TestPrecopyResumeReleasesAllWaiters(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + queued := make(chan struct{}, 3) + var want, granted []*precopyWaiter + grantUnlocked := false + b.testPrecopyGranted = func(w *precopyWaiter) { + granted = append(granted, w) + if b.mu.TryLock() { + b.mu.Unlock() + grantUnlocked = true + } + } + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered := make(chan byte, 3) + release := make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { + entered <- v + select { + case <-release: + case <-ctx.Done(): + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + results := make(chan error, 3) + t.Cleanup(func() { + unpark() + cancel() + resume() + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("resumed writers did not join") + } + }) + for v := byte(1); v <= 3; v++ { + wg.Add(1) + go func(v byte) { + defer wg.Done() + _, err := b.Write(ctx, int64(v-1)*4096, bytes.Repeat([]byte{v}, 4096)) + results <- err + }(v) + select { + case <-queued: + b.mu.Lock() + want = append(want, b.precopy.waiters[len(b.precopy.waiters)-1]) + b.mu.Unlock() + case <-ctx.Done(): + t.Fatal("write did not queue") + } + } + select { + case v := <-entered: + t.Fatalf("paused write %d reached observer", v) + default: + } + resume() + if grantUnlocked || len(granted) != 3 { + t.Fatalf("FIFO grants not made together under mu: count=%d unlocked=%v", len(granted), grantUnlocked) + } + for i, w := range want { + if granted[i] != w { + t.Fatalf("grant %d bypassed arrival order", i) + } + } + seen := map[byte]bool{} + for i := 0; i < 3; i++ { + select { + case v := <-entered: + seen[v] = true + case <-ctx.Done(): + t.Fatalf("resume serialized independent I/O: %d/3 entered before any completion", len(seen)) + } + } + unpark() + for i := 0; i < 3; i++ { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("resumed write did not finish") + } + } + for v := byte(1); v <= 3; v++ { + got := make([]byte, 4096) + if _, err := b.Read(ctx, int64(v-1)*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{v}, 4096)) { + t.Fatalf("resumed LBA %d bytes incorrect: %v", v-1, err) + } + } +} + +// Real elapsed time, not a changed production budget: an admitted Sync remains +// held past the old pause's five-second clock while a fresh write must succeed. +func TestPrecopyResumedArrivalDoesNotInheritExpiredPause(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 9*time.Second) + queued := make(chan struct{}, 2) + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(ctx context.Context) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + // Capture the existing pause's origin only to wait beyond its public bound. + b.mu.Lock() + started := b.precopy.started + b.mu.Unlock() + var syncErr error + t.Cleanup(func() { + unpark() + cancel() + resume() + select { + case <-done: + case <-time.After(time.Second): + t.Error("held Sync did not join") + } + }) + go func() { defer close(done); syncErr = b.Sync(ctx) }() + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("Sync did not queue") + } + resume() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("Sync did not resume") + } + timer := time.NewTimer(time.Until(started.Add(5*time.Second + 50*time.Millisecond))) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + t.Fatal("caller expired before pause-age witness") + } + want := bytes.Repeat([]byte{7}, 4096) + if n, err := b.Write(ctx, 4096, want); err != nil || n != len(want) { + t.Fatalf("serving volume rejected a fresh arrival after ended pause aged past five seconds: n=%d err=%v", n, err) + } + got := make([]byte, 4096) + if _, err := b.Read(ctx, 4096, got); err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh write bytes: %v", err) + } + unpark() + select { + case <-done: + if syncErr != nil { + t.Fatal(syncErr) + } + case <-ctx.Done(): + t.Fatal("Sync did not finish") + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go new file mode 100644 index 0000000000..279f50d7a8 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go @@ -0,0 +1,52 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "testing" + "time" +) + +type precopyProjectionFunc func() frontend.Projection + +func (f precopyProjectionFunc) Projection() frontend.Projection { return f() } + +// Projection is the real gate seam: pause B begins before admittedIO increments, +// and that same observation returns stale ownership. B cannot erase this error. +func TestPrecopyNewPauseCannotEraseObservedStalePrimary(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + resumeB := func() {} + defer func() { resumeB() }() + calls := 0 + var startErr error + b.view = precopyProjectionFunc(func() frontend.Projection { + calls++ + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + startErr = err + return frontend.Projection{} + } + resumeB = resume + return frontend.Projection{VolumeID: b.id.VolumeID, ReplicaID: b.id.ReplicaID, Epoch: b.id.Epoch + 1, EndpointVersion: b.id.EndpointVersion, Healthy: true} + }) + observed := false + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed = true; return nil }}); err != nil { + t.Fatal(err) + } + err := b.Sync(ctx) + if startErr != nil { + t.Fatal("start B from projection:", startErr) + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("observed stale ownership replaced by pause retry: %v", err) + } + b.mu.Lock() + admitted := b.admittedIO + b.mu.Unlock() + if calls != 1 || observed || admitted != 0 { + t.Fatalf("stale observation retried or admitted I/O: calls=%d observed=%v admitted=%d", calls, observed, admitted) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index f1c9e3779c..9ac6db58e4 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,8 +149,9 @@ type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). testBeforeIOLock func() - testPrecopyQueued func() // after FIFO registration, outside mu - testPrecopyStopFallback func() // before fallback lock attempts, outside mu + testPrecopyQueued func() // after FIFO registration, outside mu + testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook + testPrecopyStopFallback func() // before fallback lock attempts, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -368,7 +369,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true - b.finishPrecopyLocked(false) + b.finishPrecopyLocked() b.notifyReadReadyLocked() return nil } @@ -488,7 +489,7 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { // teardown. Keep a final pre-copy queue parked until Close or its budget; // publishing readiness loss must not complete commands on that path. if ok || b.precopy == nil || !b.precopy.active { - b.finishPrecopyLocked(ok) + b.finishPrecopyLocked() } b.notifyReadReadyLocked() } @@ -829,7 +830,7 @@ func (b *StorageBackend) admit() (func(), error) { if b.precopy != nil && b.precopy.active { b.mu.Unlock() b.ioMu.RUnlock() - return nil, fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return nil, errPrecopyPaused } b.admittedIO++ b.mu.Unlock() @@ -879,7 +880,7 @@ func (b *StorageBackend) readyCheck() error { return frontend.ErrStalePrimary } if precopyPending { - return fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return errPrecopyPaused } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..5023b8dc8a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -218,7 +218,7 @@ stateDiagram-v2 Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload Quiesce --> FinalFreeze: measured admission or explicit frozen final override FinalFreeze --> OpenWindow: admission stays closed through detached settlement - Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier + Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier; release all held admission OpenWindow --> Copy: release barrier Copy --> Upload: local entry released, intent durable first Upload --> Copy: next unsent candidate @@ -244,9 +244,9 @@ stateDiagram-v2 | 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` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `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 reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-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` | | 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 resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-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` | | Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-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` | @@ -528,7 +528,7 @@ Notes: | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy 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` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-WS-FREEZE-ACCOUNTING-001` | 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. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible` (classification itself does not alter the admission model) | 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` | 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; safe resume is FIFO, 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. | 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`, `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess`, `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`, `TestPrecopyQueueResumesInFIFOOrder`, `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`, `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-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 | @@ -553,6 +553,8 @@ A guest read has a cooperative arrival budget; internal contextless readers keep Notes: +- `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). ### B.6 Workspace: chunk lifecycle, GC and delete @@ -655,3 +657,10 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a - `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. - The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. - Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. + + +## Part D. Wait ownership + +| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | +|---|---|---|---|---| +| 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. |