mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
storage: copy native chunk cut images outside the write barrier
Fix H and candidates under the short barrier; save pending chunks before mutation. Drain owners and waiters before cleanup, recovery, reset and close. Preserve intent/CAS and local durability contracts. Include native caller controls, existing model correspondence and a real-mount rehearsal note.
This commit is contained in:
1 parent
cc5cf09af0
commit
cd6dff4f67
30 files changed
+2541
-85
No files matched your search
@@ -55,6 +55,9 @@ type ChunkCutResponse struct {
|
||||
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
|
||||
// step); every duration is in nanoseconds.
|
||||
type ChunkCutStatsBody struct {
|
||||
COWSavedChunks int `json:"cowSavedChunks"`
|
||||
COWSaveNs int64 `json:"cowSaveNs"`
|
||||
COWWaitNs int64 `json:"cowWaitNs"`
|
||||
BarrierPauseNs int64 `json:"barrierPauseNs"`
|
||||
SyncNs int64 `json:"syncNs"`
|
||||
CopyNs int64 `json:"copyNs"`
|
||||
@@ -79,6 +82,9 @@ func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
|
||||
BarrierPauseNs: s.BarrierPauseNs,
|
||||
SyncNs: s.SyncNs,
|
||||
CopyNs: s.CopyNs,
|
||||
COWSavedChunks: s.COWSavedChunks,
|
||||
COWSaveNs: s.COWSaveNs,
|
||||
COWWaitNs: s.COWWaitNs,
|
||||
CandidateChunks: s.CandidateChunks,
|
||||
UploadedChunks: s.UploadedChunks,
|
||||
UploadedBytes: s.UploadedBytes,
|
||||
@@ -254,6 +260,8 @@ func chunkErrorCode(err error) (int, string, bool) {
|
||||
return http.StatusConflict, chunkstore.CodeNotChunkVolume, false
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true
|
||||
case errors.Is(err, storage.ErrCutCOWAborted):
|
||||
return http.StatusServiceUnavailable, "cut_aborted", true
|
||||
default:
|
||||
return http.StatusInternalServerError, codeInternal, false
|
||||
}
|
||||
|
||||
@@ -218,6 +218,7 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) {
|
||||
{fmt.Errorf("%w: %w", storage.ErrChunkReconciling, context.DeadlineExceeded), "reconciling", 409, true},
|
||||
{fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true},
|
||||
{fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true},
|
||||
{fmt.Errorf("save: %w", storage.ErrCutCOWAborted), "cut_aborted", 503, true},
|
||||
{fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true},
|
||||
{fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false},
|
||||
{fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false},
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Keep the new cut-body counters as a caller-visible contract. Reflection
|
||||
// lets this RED compile on main before the COW fields are implemented.
|
||||
func TestChunkCutStatsBody_ExposesCOWCounters(t *testing.T) {
|
||||
var stats storage.ChunkCutStats
|
||||
fields := []struct {
|
||||
goName, jsonName string
|
||||
value int64
|
||||
}{
|
||||
{"COWSavedChunks", "cowSavedChunks", 31},
|
||||
{"COWSaveNs", "cowSaveNs", 47},
|
||||
{"COWWaitNs", "cowWaitNs", 59},
|
||||
}
|
||||
value := reflect.ValueOf(&stats).Elem()
|
||||
for _, field := range fields {
|
||||
target := value.FieldByName(field.goName)
|
||||
if !target.IsValid() {
|
||||
t.Errorf("RED: storage cut stats lack %s", field.goName)
|
||||
continue
|
||||
}
|
||||
if target.Kind() != reflect.Int && target.Kind() != reflect.Int64 {
|
||||
t.Errorf("counter %s has unexpected kind %s", field.goName, target.Kind())
|
||||
continue
|
||||
}
|
||||
target.SetInt(field.value)
|
||||
}
|
||||
raw, err := json.Marshal(cutStatsBody(stats))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Other cut-body fields include strings/bools, so decode only the named
|
||||
// integer counters from RawMessage rather than accepting a partial decode.
|
||||
var members map[string]json.RawMessage
|
||||
if err = json.Unmarshal(raw, &members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, field := range fields {
|
||||
member, exists := members[field.jsonName]
|
||||
if !exists {
|
||||
t.Errorf("RED: cut response lacks %s", field.jsonName)
|
||||
continue
|
||||
}
|
||||
var number int64
|
||||
if err = json.Unmarshal(member, &number); err != nil {
|
||||
t.Fatalf("counter %s: %v", field.jsonName, err)
|
||||
}
|
||||
if number != field.value {
|
||||
t.Errorf("counter %s=%d want %d", field.jsonName, number, field.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -394,11 +394,12 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane
|
||||
v := s.v3
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if err := s.checkInstallBlockV3(lba, data); err != nil {
|
||||
return err
|
||||
}
|
||||
s.beforeChunkMutation(uint64(lba), 1)
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
package storage
|
||||
|
||||
// Cut-window ownership. Lock order: layer.cowMu -> window.mu -> entry.mu.
|
||||
// None of these locks spans a read, side-store I/O, wait, or store lock.
|
||||
// captureMu shared covers the write hook, but lifecycleMu is acquired AFTER it.
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cutCOWMemoryLimit = 64 << 20
|
||||
const (
|
||||
cowPending uint8 = iota
|
||||
cowCopying
|
||||
cowSaving
|
||||
cowSaved
|
||||
cowDone
|
||||
)
|
||||
|
||||
var errCutCOWAborted = errors.New("storage: cut copy window aborted; retry cut")
|
||||
|
||||
type cutCOWEntry struct {
|
||||
mu sync.Mutex
|
||||
state uint8
|
||||
ready chan struct{}
|
||||
data []byte
|
||||
slot int64
|
||||
spilled bool
|
||||
readingSaved bool
|
||||
}
|
||||
type cutCOWWindow struct {
|
||||
layer *chunkLayerImpl
|
||||
mu sync.Mutex
|
||||
terminal bool
|
||||
err error
|
||||
ended chan struct{}
|
||||
refs sync.WaitGroup // Add under mu, only while OPEN; Wait only after terminal
|
||||
sideReady chan struct{}
|
||||
cleanupErr error
|
||||
entries map[uint64]*cutCOWEntry
|
||||
memory int64
|
||||
chunkBytes int64
|
||||
side *os.File
|
||||
sideErr error
|
||||
cleanup sync.Once
|
||||
saved atomic.Int64
|
||||
saveNs atomic.Int64
|
||||
waitNs atomic.Int64
|
||||
// Scheduling/fault controls are nil in production and set before installation.
|
||||
}
|
||||
|
||||
func (s *WALStore) beforeChunkMutation(first, count uint64) {
|
||||
if h := s.chunk.Load(); h != nil && h.beforeMutation != nil {
|
||||
h.beforeMutation(first, count)
|
||||
}
|
||||
}
|
||||
|
||||
// Return with the requested capture barrier held. A first attach that races the
|
||||
// optimistic hook snapshot forces admission/drain to be repeated with its hooks.
|
||||
func (s *WALStore) holdChunkDestructive(exclusive bool) func() {
|
||||
for {
|
||||
h := s.chunk.Load()
|
||||
if hook := s.testDestructiveSnapshot; hook != nil {
|
||||
hook()
|
||||
}
|
||||
var release func()
|
||||
if h != nil && h.beforeDestructive != nil {
|
||||
release = h.beforeDestructive()
|
||||
}
|
||||
if exclusive {
|
||||
s.captureMu.Lock()
|
||||
} else {
|
||||
s.captureMu.RLock()
|
||||
}
|
||||
if s.chunk.Load() == h {
|
||||
return func() {
|
||||
if exclusive {
|
||||
s.captureMu.Unlock()
|
||||
} else {
|
||||
s.captureMu.RUnlock()
|
||||
}
|
||||
if release != nil {
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
if exclusive {
|
||||
s.captureMu.Unlock()
|
||||
} else {
|
||||
s.captureMu.RUnlock()
|
||||
}
|
||||
if release != nil {
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) holdCOWDestructive() func() {
|
||||
l.cowMu.Lock()
|
||||
l.cowTransitions++
|
||||
w := l.cow
|
||||
if w != nil {
|
||||
w.abort(errCutCOWAborted)
|
||||
}
|
||||
l.cowMu.Unlock()
|
||||
if w != nil {
|
||||
w.join()
|
||||
}
|
||||
return func() { l.cowMu.Lock(); l.cowTransitions--; l.cowMu.Unlock() }
|
||||
}
|
||||
|
||||
// The caller owns captureMu exclusive, so no writer can miss this publication.
|
||||
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool) (*cutCOWWindow, error) {
|
||||
size := uint64(l.blockSize) * l.chunkBlocks
|
||||
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
|
||||
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
|
||||
}
|
||||
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), chunkBytes: int64(size)}
|
||||
var slot int64
|
||||
for _, idx := range sortedKeys(candidates) {
|
||||
state := cowPending
|
||||
if staged[idx] {
|
||||
state = cowDone
|
||||
}
|
||||
w.entries[idx] = &cutCOWEntry{state: state, ready: make(chan struct{}), slot: slot}
|
||||
slot++
|
||||
}
|
||||
l.cowMu.Lock()
|
||||
defer l.cowMu.Unlock()
|
||||
if l.cowClosed || l.cowTransitions != 0 {
|
||||
return nil, errCutCOWAborted
|
||||
}
|
||||
l.cow = w
|
||||
l.cowActive.Store(w)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *cutCOWWindow) abort(err error) {
|
||||
w.mu.Lock()
|
||||
if !w.terminal {
|
||||
w.terminal, w.err = true, fmt.Errorf("%w: %w", errCutCOWAborted, err)
|
||||
close(w.ended)
|
||||
}
|
||||
w.mu.Unlock()
|
||||
}
|
||||
func (w *cutCOWWindow) join() error {
|
||||
w.refs.Wait()
|
||||
// Only terminal windows are joined. Saved readers never outlive their ref.
|
||||
w.cleanup.Do(func() {
|
||||
if w.side != nil {
|
||||
name := w.side.Name()
|
||||
w.cleanupErr = errors.Join(w.side.Close(), os.Remove(name))
|
||||
}
|
||||
for _, e := range w.entries {
|
||||
e.data = nil
|
||||
}
|
||||
})
|
||||
return w.cleanupErr
|
||||
}
|
||||
func (w *cutCOWWindow) status() error { w.mu.Lock(); defer w.mu.Unlock(); return w.err }
|
||||
|
||||
// A nil result without a notification means done/terminal. Waiters own a
|
||||
// lifetime reference through wakeup/accounting, never an entry or I/O lock.
|
||||
func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-chan struct{}) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.terminal {
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
e := w.entries[idx]
|
||||
if e == nil {
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
state := e.state
|
||||
switch state {
|
||||
case cowPending:
|
||||
if saving {
|
||||
e.state = cowSaving
|
||||
} else {
|
||||
e.state = cowCopying
|
||||
}
|
||||
w.refs.Add(1)
|
||||
return e, state, nil
|
||||
case cowSaved:
|
||||
if saving {
|
||||
return nil, cowDone, nil
|
||||
} // live bytes are already saved
|
||||
if e.readingSaved {
|
||||
w.refs.Add(1)
|
||||
return nil, state, e.ready
|
||||
}
|
||||
e.readingSaved = true
|
||||
w.refs.Add(1)
|
||||
return e, state, nil
|
||||
case cowSaving, cowCopying:
|
||||
// Waiters acquire while OPEN too: drain includes their accounting
|
||||
// before the coordinator snapshots aggregate wait time.
|
||||
w.refs.Add(1)
|
||||
return nil, state, e.ready
|
||||
default:
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
}
|
||||
func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if w.terminal {
|
||||
return false
|
||||
}
|
||||
e.state = state
|
||||
e.readingSaved = false
|
||||
close(e.ready)
|
||||
e.ready = make(chan struct{})
|
||||
return true
|
||||
}
|
||||
func (w *cutCOWWindow) wait(ch <-chan struct{}) {
|
||||
defer w.refs.Done()
|
||||
start := time.Now()
|
||||
if hook := w.layer.testCOWWait; hook != nil {
|
||||
hook()
|
||||
}
|
||||
select {
|
||||
case <-ch:
|
||||
case <-w.ended:
|
||||
}
|
||||
w.waitNs.Add(time.Since(start).Nanoseconds())
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) {
|
||||
w := l.cowActive.Load()
|
||||
if w == nil || count == 0 {
|
||||
return
|
||||
}
|
||||
last := (first + count - 1) / l.chunkBlocks
|
||||
for idx := first / l.chunkBlocks; idx <= last; idx++ {
|
||||
for {
|
||||
e, _, wait := w.claim(idx, true)
|
||||
if wait != nil {
|
||||
w.wait(wait)
|
||||
continue
|
||||
}
|
||||
if e == nil {
|
||||
break
|
||||
}
|
||||
start := time.Now()
|
||||
data, err := l.readCOWChunk(w, idx)
|
||||
if err == nil {
|
||||
err = w.save(e, data)
|
||||
}
|
||||
if err != nil {
|
||||
w.abort(err)
|
||||
} else if w.finish(e, cowSaved) {
|
||||
w.saved.Add(1)
|
||||
}
|
||||
w.saveNs.Add(time.Since(start).Nanoseconds())
|
||||
// In particular an aborting saver releases itself BEFORE anyone joins.
|
||||
w.refs.Done()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte) error {
|
||||
if hook := w.layer.testCOWSave; hook != nil {
|
||||
if err := hook(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
w.mu.Lock()
|
||||
if w.terminal {
|
||||
w.mu.Unlock()
|
||||
return errCutCOWAborted
|
||||
}
|
||||
inMemory := w.memory+w.chunkBytes <= cutCOWMemoryLimit
|
||||
if inMemory {
|
||||
w.memory += w.chunkBytes
|
||||
}
|
||||
w.mu.Unlock()
|
||||
if inMemory {
|
||||
e.data = data
|
||||
return nil
|
||||
}
|
||||
if err := w.openSide(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.sideErr != nil {
|
||||
return w.sideErr
|
||||
}
|
||||
n, err := w.side.WriteAt(data, e.slot*w.chunkBytes)
|
||||
if err == nil && n != len(data) {
|
||||
err = fmt.Errorf("short COW side write: %d/%d", n, len(data))
|
||||
}
|
||||
e.spilled = true
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, error) {
|
||||
buf := make([]byte, int(w.chunkBytes))
|
||||
for i := uint64(0); i < l.chunkBlocks; i++ {
|
||||
select {
|
||||
case <-w.ended:
|
||||
return nil, errCutCOWAborted
|
||||
default:
|
||||
}
|
||||
lba := idx*l.chunkBlocks + i
|
||||
if lba >= uint64(l.s.NumBlocks()) {
|
||||
break
|
||||
}
|
||||
b, err := l.s.Read(uint32(lba))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
copy(buf[int(i)*l.blockSize:], b)
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChunk, bool, error) {
|
||||
for {
|
||||
if err := l.admit(); err != nil {
|
||||
w.abort(err)
|
||||
return capturedChunk{}, false, err
|
||||
}
|
||||
e, state, wait := w.claim(idx, false)
|
||||
if wait != nil {
|
||||
w.wait(wait)
|
||||
continue
|
||||
}
|
||||
if e == nil {
|
||||
return capturedChunk{}, false, w.status()
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if state == cowSaved {
|
||||
if e.spilled {
|
||||
data = make([]byte, int(w.chunkBytes))
|
||||
_, err = w.side.ReadAt(data, e.slot*w.chunkBytes)
|
||||
} else {
|
||||
data = e.data
|
||||
}
|
||||
} else {
|
||||
data, err = l.readCOWChunk(w, idx)
|
||||
}
|
||||
if hook := l.testCOWRead; hook != nil {
|
||||
hook(idx, state == cowSaved)
|
||||
}
|
||||
if err == nil {
|
||||
err = l.admit()
|
||||
}
|
||||
if err != nil {
|
||||
w.abort(err)
|
||||
}
|
||||
kept := false
|
||||
if err == nil {
|
||||
kept = w.finish(e, cowDone)
|
||||
}
|
||||
w.refs.Done()
|
||||
if !kept {
|
||||
return capturedChunk{}, false, w.status()
|
||||
}
|
||||
return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data), zero: isAllZero(data)}, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow) ([]capturedChunk, error) {
|
||||
stop := context.AfterFunc(ctx, func() { w.abort(ctx.Err()) })
|
||||
defer stop()
|
||||
defer func() {
|
||||
w.abort(errCutCOWAborted)
|
||||
w.join()
|
||||
l.cowMu.Lock()
|
||||
if l.cow == w {
|
||||
l.cow = nil
|
||||
l.cowActive.Store(nil)
|
||||
}
|
||||
l.cowMu.Unlock()
|
||||
}()
|
||||
indices := make(map[uint64]bool, len(w.entries))
|
||||
for idx := range w.entries {
|
||||
indices[idx] = true
|
||||
}
|
||||
keys := sortedKeys(indices)
|
||||
out := make([]capturedChunk, len(keys))
|
||||
kept := make([]bool, len(keys))
|
||||
var next atomic.Int64
|
||||
var workers sync.WaitGroup
|
||||
for n := 0; n < min(l.cfg.UploadConcurrency, len(keys)); n++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for {
|
||||
i := int(next.Add(1) - 1)
|
||||
if i >= len(keys) {
|
||||
return
|
||||
}
|
||||
c, ok, err := l.copyCOWEntry(w, keys[i])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
out[i], kept[i] = c, ok
|
||||
}
|
||||
}()
|
||||
}
|
||||
workers.Wait()
|
||||
w.mu.Lock()
|
||||
if !w.terminal {
|
||||
w.terminal = true
|
||||
close(w.ended)
|
||||
}
|
||||
err := w.err
|
||||
w.mu.Unlock()
|
||||
cleanupErr := w.join()
|
||||
if cleanupErr != nil {
|
||||
err = errors.Join(err, errCutCOWAborted, cleanupErr)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result []capturedChunk
|
||||
for i, c := range out {
|
||||
if kept[i] {
|
||||
result = append(result, c)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Creation is single-owner, but no allocation/lifetime lock spans filesystem I/O.
|
||||
func (w *cutCOWWindow) openSide() error {
|
||||
w.mu.Lock()
|
||||
if w.sideReady != nil {
|
||||
ready := w.sideReady
|
||||
w.mu.Unlock()
|
||||
select {
|
||||
case <-ready:
|
||||
return w.sideErr
|
||||
case <-w.ended:
|
||||
return errCutCOWAborted
|
||||
}
|
||||
}
|
||||
w.sideReady = make(chan struct{})
|
||||
w.mu.Unlock()
|
||||
side, err := os.CreateTemp(filepath.Dir(w.layer.s.path), filepath.Base(w.layer.s.path)+".cut-cow-")
|
||||
w.mu.Lock()
|
||||
w.side, w.sideErr = side, err
|
||||
close(w.sideReady)
|
||||
w.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// Called only by an exclusive, locked RW open. Side payloads are never decoded
|
||||
// or imported, and directories/symlinks/other volume prefixes are untouched.
|
||||
func discardCutCOWFiles(path string) error {
|
||||
dir := filepath.Dir(path)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prefix := filepath.Base(path) + ".cut-cow-"
|
||||
for _, e := range entries {
|
||||
if !strings.HasPrefix(e.Name(), prefix) || !e.Type().IsRegular() {
|
||||
continue
|
||||
}
|
||||
// Type zero includes regular files only; Info also protects unknown dir types.
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, e.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Called only after releasing stMu; it invalidates without joining its caller.
|
||||
func (l *chunkLayerImpl) abortCOW(err error) {
|
||||
if w := l.cowActive.Load(); w != nil {
|
||||
w.abort(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// File-backed backend proxy, not a guest/mount benchmark. Writers are released
|
||||
// by the actual Sync/H handshake and issue one 4K write+Sync each per cut.
|
||||
// This file is intentionally source-identical on the parent comparison ref.
|
||||
func BenchmarkCutCOWProxy(b *testing.B) {
|
||||
for _, chunks := range []int{8, 64} {
|
||||
for _, qd := range []int{1, 8} {
|
||||
b.Run(fmt.Sprintf("chunks%d/QD%d", chunks, qd), func(b *testing.B) {
|
||||
const blocksPerChunk = 1024
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(b.TempDir(), "volume"), uint32(chunks*blocksPerChunk), 4096, WALStoreOptions{ChunkBlocks: blocksPerChunk})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.Cleanup(func() { _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
remote := NewMemChunkRemote()
|
||||
layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: blocksPerChunk, Epoch: 1, Holder: "proxy", UploadConcurrency: 8, FreshFromHead: true})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
l := layer.(*chunkLayerImpl)
|
||||
if _, err = l.Cut(context.Background()); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
var latencies []int64
|
||||
var barrier, copyNs, syncNs, total, uploads, bytes int64
|
||||
b.ResetTimer()
|
||||
b.StopTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
data := makeBlock(4096, byte(1+n%100))
|
||||
for c := 0; c < chunks; c++ {
|
||||
if _, err = s.Write(uint32(c*blocksPerChunk), data); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if err = s.flusher.flushOnce(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
start := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
durations := make([]int64, qd)
|
||||
errs := make([]error, qd)
|
||||
l.testAfterBarrierSyncHook = func(uint64) { close(start) }
|
||||
var wg sync.WaitGroup
|
||||
for writer := 0; writer < qd; writer++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
t := time.Now()
|
||||
_, e := s.Write(uint32((chunks-1-i%chunks)*blocksPerChunk+1), makeBlock(4096, byte(0xa0+i)))
|
||||
if e == nil {
|
||||
_, e = s.Sync()
|
||||
}
|
||||
durations[i] = time.Since(t).Nanoseconds()
|
||||
errs[i] = e
|
||||
}(writer)
|
||||
}
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
b.StartTimer()
|
||||
r, e := l.Cut(context.Background())
|
||||
b.StopTimer()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(30 * time.Second):
|
||||
stack := make([]byte, 1<<20)
|
||||
nn := runtime.Stack(stack, true)
|
||||
b.Fatalf("proxy writers stalled\n%s", stack[:nn])
|
||||
}
|
||||
if e != nil {
|
||||
b.Fatal(e)
|
||||
}
|
||||
for _, e := range errs {
|
||||
if e != nil {
|
||||
b.Fatal(e)
|
||||
}
|
||||
}
|
||||
l.testAfterBarrierSyncHook = nil
|
||||
latencies = append(latencies, durations...)
|
||||
barrier += r.Stats.BarrierPauseNs
|
||||
copyNs += r.Stats.CopyNs
|
||||
syncNs += r.Stats.SyncNs
|
||||
total += r.Stats.TotalNs
|
||||
uploads += int64(r.Stats.UploadedChunks)
|
||||
bytes += r.Stats.UploadedBytes
|
||||
// The proxy is not measuring retained old remote versions. Retain only
|
||||
// current HEAD objects between iterations, identically in both arms.
|
||||
remote.mu.Lock()
|
||||
live := map[string]bool{}
|
||||
for _, ref := range remote.head.Chunks {
|
||||
live[ref.Key] = true
|
||||
}
|
||||
for key := range remote.objs {
|
||||
if !live[key] {
|
||||
delete(remote.objs, key)
|
||||
}
|
||||
}
|
||||
remote.mu.Unlock()
|
||||
}
|
||||
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||
percentile := func(p int) float64 {
|
||||
i := (len(latencies)*p+99)/100 - 1
|
||||
if i < 0 {
|
||||
i = 0
|
||||
}
|
||||
return float64(latencies[i])
|
||||
}
|
||||
b.ReportMetric(percentile(50), "writer-p50-ns")
|
||||
b.ReportMetric(percentile(99), "writer-p99-ns")
|
||||
b.ReportMetric(float64(latencies[len(latencies)-1]), "writer-max-ns")
|
||||
for name, value := range map[string]int64{"barrier-ns": barrier, "copy-ns": copyNs, "sync-ns": syncNs, "cut-ns": total, "uploaded-chunks": uploads, "uploaded-bytes": bytes} {
|
||||
b.ReportMetric(float64(value)/float64(b.N), name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,853 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// These fixtures use the public v3 factory, real reads/WAL/flusher, and actual
|
||||
// cut/write/recovery/close callers. Hooks only hold an identified I/O boundary.
|
||||
func cowFixture(t *testing.T) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, *cowReadGate) {
|
||||
t.Helper()
|
||||
gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) {
|
||||
return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { gate.unblock(); _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
if _, err = l.Cut(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lba := range []uint32{1, 5} {
|
||||
if _, err = s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gate.mu.Lock()
|
||||
gate.armed = true
|
||||
gate.mu.Unlock()
|
||||
return s, l, f, gate
|
||||
}
|
||||
func cowStartCut(t *testing.T, l *chunkLayerImpl, gate *cowReadGate) (<-chan struct{}, <-chan error) {
|
||||
t.Helper()
|
||||
done := make(chan struct{})
|
||||
errs := make(chan error, 1)
|
||||
t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, done, "cut cleanup") })
|
||||
go func() { defer close(done); _, err := l.Cut(context.Background()); errs <- err }()
|
||||
cowWaitSignal(t, gate.entered, "live copier")
|
||||
return done, errs
|
||||
}
|
||||
|
||||
func TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves(t *testing.T) {
|
||||
s, l, f, gate := cowFixture(t)
|
||||
waiting := make(chan struct{})
|
||||
var once sync.Once
|
||||
l.testCOWWait = func() { once.Do(func() { close(waiting) }) }
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
writeDone := make(chan struct{})
|
||||
var writeErr error
|
||||
t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "writer cleanup") })
|
||||
go func() { defer close(writeDone); _, writeErr = s.Write(1, makeBlock(ctBlockSize, 0xa1)) }()
|
||||
cowWaitSignal(t, waiting, "same-chunk wait admission")
|
||||
select {
|
||||
case <-writeDone:
|
||||
t.Fatal("copying chunk changed before old image finished")
|
||||
default:
|
||||
}
|
||||
if _, err := s.Write(5, makeBlock(ctBlockSize, 0xa5)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, writeDone, "same-chunk write")
|
||||
cowWaitSignal(t, cutDone, "cut")
|
||||
if writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
if err := <-cutErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l.Stats().LastCut.COWWaitNs <= 0 {
|
||||
t.Fatal("drained window omitted its real wait time")
|
||||
}
|
||||
image := f.imageOf(t, f.stats().head)
|
||||
if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 1)) || !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 5)) {
|
||||
t.Fatal("torn or post-H cut image")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_SaveFailureAbortsOnlyCut(t *testing.T) {
|
||||
s, l, f, gate := cowFixture(t)
|
||||
var calls atomic.Int32
|
||||
l.testCOWSave = func() error { calls.Add(1); return errors.New("injected side ENOSPC") }
|
||||
before := f.stats().head
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
if _, err := s.Write(5, makeBlock(ctBlockSize, 0xb5)); err != nil {
|
||||
t.Fatalf("COW failure escaped into guest write: %v", err)
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "aborted cut")
|
||||
if err := <-cutErr; !errors.Is(err, errCutCOWAborted) {
|
||||
t.Fatalf("cut error=%v", err)
|
||||
}
|
||||
if f.stats().head.Gen != before.Gen || calls.Load() != 1 {
|
||||
t.Fatal("failed cut published or save not exercised")
|
||||
}
|
||||
l.testCOWSave = nil
|
||||
r, err := l.Cut(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
image := f.imageOf(t, r.Head)
|
||||
if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 1)) || !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 0xb5)) {
|
||||
t.Fatal("retry lost original candidates or new dirt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_RecoveryAndCloseDrainSavingOwner(t *testing.T) {
|
||||
for _, action := range []string{"Recover", "Reset", "LayerClose", "StoreClose", "Cancel"} {
|
||||
t.Run(action, func(t *testing.T) {
|
||||
s, l, _, gate := cowFixture(t)
|
||||
saveEntered, saveRelease := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
releaseSave := func() { once.Do(func() { close(saveRelease) }) }
|
||||
l.testCOWSave = func() error { close(saveEntered); <-saveRelease; return nil }
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
cutDone, writeDone, actionDone := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var writeErr, actionErr, cutErr error
|
||||
actionStarted := false
|
||||
t.Cleanup(func() {
|
||||
releaseSave()
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, writeDone, "save writer cleanup")
|
||||
cowWaitSignal(t, cutDone, "cut cleanup")
|
||||
if actionStarted {
|
||||
cowWaitSignal(t, actionDone, "transition cleanup")
|
||||
}
|
||||
})
|
||||
go func() { defer close(cutDone); _, cutErr = l.Cut(ctx) }()
|
||||
cowWaitSignal(t, gate.entered, "held copier")
|
||||
w := l.cowActive.Load()
|
||||
if w == nil {
|
||||
t.Fatal("window not installed")
|
||||
}
|
||||
go func() { defer close(writeDone); _, writeErr = s.Write(5, makeBlock(ctBlockSize, 0xc5)) }()
|
||||
cowWaitSignal(t, saveEntered, "saving owner")
|
||||
actionStarted = true
|
||||
go func() {
|
||||
defer close(actionDone)
|
||||
switch action {
|
||||
case "Recover":
|
||||
_, actionErr = s.Recover()
|
||||
case "Reset":
|
||||
actionErr = s.resetIncarnationV3()
|
||||
case "LayerClose":
|
||||
actionErr = l.Close()
|
||||
case "StoreClose":
|
||||
actionErr = s.Close()
|
||||
case "Cancel":
|
||||
cancel()
|
||||
<-cutDone
|
||||
}
|
||||
}()
|
||||
// Store Close first takes capture exclusive, held by the saver; release
|
||||
// the actual saver for that arm before expecting layer/window cancellation.
|
||||
if action == "StoreClose" {
|
||||
releaseSave()
|
||||
}
|
||||
cowWaitSignal(t, w.ended, "terminal notification")
|
||||
if action != "StoreClose" {
|
||||
// ended is the real abort handshake, not a scheduling guess.
|
||||
// Keep actual I/O held for this bounded non-completion check;
|
||||
// an immediate default select could miss a no-join mutant.
|
||||
select {
|
||||
case <-actionDone:
|
||||
t.Fatal("transition returned with saver/live copy still held")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
releaseSave()
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, writeDone, "saving writer")
|
||||
cowWaitSignal(t, cutDone, "aborted cut")
|
||||
cowWaitSignal(t, actionDone, "transition")
|
||||
if writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
if cutErr == nil {
|
||||
t.Fatal("terminal window published")
|
||||
}
|
||||
if actionErr != nil && action != "Reset" {
|
||||
t.Fatal(actionErr)
|
||||
}
|
||||
if action == "Recover" || action == "Reset" || action == "Cancel" {
|
||||
l.testCOWSave = nil
|
||||
if _, err := l.Cut(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
unblock := func() { once.Do(func() { close(release) }) }
|
||||
s.testCloseSnapshot = func() { close(entered); <-release }
|
||||
first, second := make(chan struct{}), make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
unblock()
|
||||
cowWaitSignal(t, first, "first close cleanup")
|
||||
cowWaitSignal(t, second, "second close cleanup")
|
||||
})
|
||||
go func() { defer close(first); _ = s.Close() }()
|
||||
cowWaitSignal(t, entered, "Close stable snapshot")
|
||||
go func() { defer close(second); _ = s.Close() }()
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
layer, err := attachChunkLayer(s, newFakeChunkRemote(), cfg)
|
||||
if err == nil {
|
||||
// Isolated missing-gate negative: the real first layer installs an
|
||||
// OPEN window while Close is parked after its nil snapshot. No fake
|
||||
// sentinel hook stands in for that snapshot.
|
||||
l := layer.(*chunkLayerImpl)
|
||||
live, releaseLive := make(chan struct{}), make(chan struct{})
|
||||
var liveOnce sync.Once
|
||||
unblockLive := func() { liveOnce.Do(func() { close(releaseLive) }) }
|
||||
l.testCOWRead = func(idx uint64, _ bool) {
|
||||
if idx == 0 {
|
||||
close(live)
|
||||
<-releaseLive
|
||||
}
|
||||
}
|
||||
cutDone := make(chan struct{})
|
||||
t.Cleanup(func() { unblockLive(); cowWaitSignal(t, cutDone, "missed first-attach cut"); _ = l.Close() })
|
||||
go func() { defer close(cutDone); _, _ = l.Cut(context.Background()) }()
|
||||
cowWaitSignal(t, live, "missed first-attach live owner")
|
||||
unblock()
|
||||
cowWaitSignal(t, first, "Close after missing first attach")
|
||||
select {
|
||||
case <-cutDone:
|
||||
default:
|
||||
t.Error("Close returned before newly admitted live owner drained")
|
||||
}
|
||||
unblockLive()
|
||||
t.Error("first attach admitted after permanent shutdown")
|
||||
} else if !errors.Is(err, errChunkLayerClosed) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-second:
|
||||
t.Fatal("second Close skipped the first drain")
|
||||
default:
|
||||
}
|
||||
unblock()
|
||||
cowWaitSignal(t, first, "first close")
|
||||
cowWaitSignal(t, second, "second close")
|
||||
}
|
||||
|
||||
func TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped(t *testing.T) {
|
||||
s, l, _, gate := cowFixture(t)
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
w := l.cowActive.Load()
|
||||
w.mu.Lock()
|
||||
w.memory = cutCOWMemoryLimit
|
||||
w.mu.Unlock() // force real file spill without a large volume
|
||||
if _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.mu.Lock()
|
||||
side := w.side
|
||||
w.mu.Unlock()
|
||||
if side == nil {
|
||||
t.Fatal("spill not exercised")
|
||||
}
|
||||
name := side.Name()
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "spilled cut")
|
||||
if err := <-cutErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(name); !os.IsNotExist(err) {
|
||||
t.Fatalf("side store survives terminal drain: %v", err)
|
||||
}
|
||||
path := s.path
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale := path + ".cut-cow-stale"
|
||||
other := path + "-other.cut-cow-stale"
|
||||
directory := path + ".cut-cow-dir"
|
||||
if err := os.WriteFile(stale, []byte("corrupt side, not recovery input"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(other, []byte("other owner"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(directory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reopened.Close()
|
||||
reopened.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = os.Stat(stale); !os.IsNotExist(err) {
|
||||
t.Fatal("stale own side payload retained")
|
||||
}
|
||||
for _, p := range []string{other, directory} {
|
||||
if _, err = os.Stat(p); err != nil {
|
||||
t.Fatal("cleanup touched other data", err)
|
||||
}
|
||||
}
|
||||
got, err := reopened.Read(5)
|
||||
if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0xd5)) {
|
||||
t.Fatal("reopen trusted side payload or lost synced bytes", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader(t *testing.T) {
|
||||
s, l, f, gate := cowFixture(t)
|
||||
saved, releaseSave := make(chan struct{}), make(chan struct{})
|
||||
reader, releaseReader := make(chan struct{}), make(chan struct{})
|
||||
waiting := make(chan struct{})
|
||||
var waitOnce, saveOnce, readerOnce sync.Once
|
||||
var saves atomic.Int32
|
||||
unblockSave := func() { saveOnce.Do(func() { close(releaseSave) }) }
|
||||
unblockReader := func() { readerOnce.Do(func() { close(releaseReader) }) }
|
||||
l.testCOWSave = func() error { saves.Add(1); close(saved); <-releaseSave; return nil }
|
||||
l.testCOWWait = func() { waitOnce.Do(func() { close(waiting) }) }
|
||||
l.testCOWRead = func(idx uint64, side bool) {
|
||||
if idx == 1 && side {
|
||||
close(reader)
|
||||
<-releaseReader
|
||||
}
|
||||
}
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
w := l.cowActive.Load()
|
||||
w.mu.Lock()
|
||||
w.memory = cutCOWMemoryLimit
|
||||
w.mu.Unlock()
|
||||
first, second, closeDone := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var err1, err2, closeErr error
|
||||
closeStarted := false
|
||||
t.Cleanup(func() {
|
||||
unblockSave()
|
||||
unblockReader()
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, first, "first writer")
|
||||
cowWaitSignal(t, second, "second writer")
|
||||
if closeStarted {
|
||||
cowWaitSignal(t, closeDone, "saved reader close")
|
||||
}
|
||||
})
|
||||
go func() { defer close(first); _, err1 = s.Write(5, makeBlock(ctBlockSize, 0xe1)) }()
|
||||
cowWaitSignal(t, saved, "single saving owner")
|
||||
go func() { defer close(second); _, err2 = s.Write(6, makeBlock(ctBlockSize, 0xe2)) }()
|
||||
cowWaitSignal(t, waiting, "second writer waits on same chunk")
|
||||
select {
|
||||
case <-second:
|
||||
t.Fatal("second writer bypassed saving owner")
|
||||
default:
|
||||
}
|
||||
unblockSave()
|
||||
cowWaitSignal(t, first, "first write")
|
||||
cowWaitSignal(t, second, "second write")
|
||||
if err1 != nil || err2 != nil || saves.Load() != 1 {
|
||||
t.Fatalf("single owner: %v %v saves=%d", err1, err2, saves.Load())
|
||||
}
|
||||
w.mu.Lock()
|
||||
side := w.side
|
||||
w.mu.Unlock()
|
||||
if side == nil {
|
||||
t.Fatal("saved read must use real spill file")
|
||||
}
|
||||
name := side.Name()
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, reader, "actual saved-file read completed, reference held")
|
||||
thirdDone := make(chan struct{})
|
||||
var thirdErr error
|
||||
t.Cleanup(func() { unblockReader(); cowWaitSignal(t, thirdDone, "writer during saved-file read") })
|
||||
go func() { defer close(thirdDone); _, thirdErr = s.Write(7, makeBlock(ctBlockSize, 0xe3)) }()
|
||||
cowWaitSignal(t, thirdDone, "saved chunk remains writable during saved-file read")
|
||||
if thirdErr != nil {
|
||||
t.Fatal(thirdErr)
|
||||
}
|
||||
closeStarted = true
|
||||
go func() { defer close(closeDone); closeErr = l.Close() }()
|
||||
cowWaitSignal(t, w.ended, "close aborts saved-reader window")
|
||||
select {
|
||||
case <-closeDone:
|
||||
t.Fatal("Close returned before saved reader released")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
if _, err := os.Stat(name); err != nil {
|
||||
t.Fatal("side removed before reader reference drained", err)
|
||||
}
|
||||
unblockReader()
|
||||
cowWaitSignal(t, closeDone, "saved reader drain")
|
||||
cowWaitSignal(t, cutDone, "aborted saved-read cut")
|
||||
if closeErr != nil || <-cutErr == nil {
|
||||
t.Fatal("Close/cut result", closeErr)
|
||||
}
|
||||
if _, err := os.Stat(name); !os.IsNotExist(err) {
|
||||
t.Fatal("side survived saved-reader drain", err)
|
||||
}
|
||||
if f.stats().head.RemoteLSN >= s.NextLSN()-1 {
|
||||
t.Fatal("aborted cut published post-H mutations")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_ObservedFenceAbortsAndWakesWriters(t *testing.T) {
|
||||
s, l, f, gate := cowFixture(t)
|
||||
var fenced atomic.Bool
|
||||
l.cfg.CaptureAllowed = func() error {
|
||||
if fenced.Load() {
|
||||
return errChunkLayerFenced
|
||||
}
|
||||
return nil
|
||||
}
|
||||
l.cfg.UploadConcurrency = 2
|
||||
other, releaseOther := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
unblock := func() { once.Do(func() { close(releaseOther) }) }
|
||||
l.testCOWRead = func(idx uint64, _ bool) {
|
||||
if idx == 1 {
|
||||
close(other)
|
||||
<-releaseOther
|
||||
}
|
||||
}
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
t.Cleanup(unblock)
|
||||
cowWaitSignal(t, other, "second copier before ordinary authority recheck")
|
||||
w := l.cowActive.Load()
|
||||
before := f.stats().head.Gen
|
||||
fenced.Store(true)
|
||||
unblock()
|
||||
cowWaitSignal(t, w.ended, "ordinary capture gate observes fence")
|
||||
if _, err := s.Write(1, makeBlock(ctBlockSize, 0xf1)); err != nil {
|
||||
t.Fatalf("COW fence refused ordinary write: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-cutDone:
|
||||
t.Fatal("cut returned while live read reference held")
|
||||
default:
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "fenced cut drain")
|
||||
if !errors.Is(<-cutErr, errCutCOWAborted) || f.stats().head.Gen != before {
|
||||
t.Fatal("fenced window published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_InvalidInputsDoNotSaveOrAbortWindow(t *testing.T) {
|
||||
s, l, _, gate := cowFixture(t)
|
||||
var saves atomic.Int32
|
||||
l.testCOWSave = func() error { saves.Add(1); return errors.New("invalid input touched COW") }
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
w := l.cowActive.Load()
|
||||
if _, err := s.Write(ctNumBlocks, makeBlock(ctBlockSize, 1)); err == nil {
|
||||
t.Fatal("invalid Write accepted")
|
||||
}
|
||||
if _, err := s.Write(5, []byte{1}); err == nil {
|
||||
t.Fatal("short Write accepted")
|
||||
}
|
||||
if _, err := s.WriteBatch(ctNumBlocks-1, [][]byte{makeBlock(ctBlockSize, 1), makeBlock(ctBlockSize, 2)}); err == nil {
|
||||
t.Fatal("invalid batch accepted")
|
||||
}
|
||||
if _, err := s.WriteBatch(5, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ApplyEntry(5, []byte{1}, s.NextLSN()); err == nil {
|
||||
t.Fatal("short Apply accepted")
|
||||
}
|
||||
if saves.Load() != 0 {
|
||||
t.Fatal("invalid caller performed COW I/O")
|
||||
}
|
||||
select {
|
||||
case <-w.ended:
|
||||
t.Fatal("invalid input aborted cut")
|
||||
default:
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "valid cut after invalid requests")
|
||||
if err := <-cutErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_OverlappingRealBatchesPreserveCut(t *testing.T) {
|
||||
s, l, f, gate := cowFixture(t)
|
||||
for _, lba := range []uint32{9, 13} {
|
||||
if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cutDone, cutErr := cowStartCut(t, l, gate)
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 2)
|
||||
done := make(chan struct{})
|
||||
t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, done, "batch cleanup") })
|
||||
for _, start := range []uint32{5, 9} {
|
||||
wg.Add(1)
|
||||
go func(start uint32) {
|
||||
defer wg.Done()
|
||||
blocks := make([][]byte, 5)
|
||||
for i := range blocks {
|
||||
blocks[i] = makeBlock(ctBlockSize, byte(start)+0x80+byte(i))
|
||||
}
|
||||
_, err := s.WriteBatch(start, blocks)
|
||||
errs <- err
|
||||
}(start)
|
||||
}
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
cowWaitSignal(t, done, "overlapping batches while earlier copy held")
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "batch cut")
|
||||
if err := <-cutErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
for _, lba := range []int{1, 5, 9, 13} {
|
||||
copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(lba)))
|
||||
}
|
||||
if !bytes.Equal(f.imageOf(t, f.stats().head), want) {
|
||||
t.Fatal("batch published into the pre-H cut")
|
||||
}
|
||||
for lba := uint32(0); lba < ctNumBlocks; lba++ {
|
||||
data, err := s.Read(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy(want[int(lba)*ctBlockSize:], data)
|
||||
}
|
||||
r, err := l.Cut(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(f.imageOf(t, r.Head), want) {
|
||||
t.Fatal("following cut lost overlapping batch writes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment(t *testing.T) {
|
||||
for _, reset := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "Recover", true: "Reset"}[reset], func(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
snapshot, release := make(chan struct{}), make(chan struct{})
|
||||
var once, releaseOnce sync.Once
|
||||
unblock := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
s.testDestructiveSnapshot = func() { once.Do(func() { close(snapshot); <-release }) }
|
||||
done := make(chan struct{})
|
||||
var transitionErr error
|
||||
t.Cleanup(func() { unblock(); cowWaitSignal(t, done, "first-attach transition cleanup") })
|
||||
go func() {
|
||||
defer close(done)
|
||||
if reset {
|
||||
transitionErr = s.resetIncarnationV3()
|
||||
} else {
|
||||
_, transitionErr = s.Recover()
|
||||
}
|
||||
}()
|
||||
cowWaitSignal(t, snapshot, "nil hook snapshot before barrier")
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl)
|
||||
live, releaseLive := make(chan struct{}), make(chan struct{})
|
||||
var liveOnce sync.Once
|
||||
unblockLive := func() { liveOnce.Do(func() { close(releaseLive) }) }
|
||||
l.testCOWRead = func(idx uint64, _ bool) {
|
||||
if idx == 0 {
|
||||
close(live)
|
||||
<-releaseLive
|
||||
}
|
||||
}
|
||||
cutDone := make(chan struct{})
|
||||
var cutErr error
|
||||
t.Cleanup(func() { unblockLive(); cowWaitSignal(t, cutDone, "first attach cut cleanup") })
|
||||
go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }()
|
||||
cowWaitSignal(t, live, "newly attached OPEN live-copy owner")
|
||||
w := l.cowActive.Load()
|
||||
unblock()
|
||||
cowWaitSignal(t, w.ended, "hook snapshot retry aborts new window")
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("destructive path missed first attach's owner")
|
||||
default:
|
||||
}
|
||||
unblockLive()
|
||||
cowWaitSignal(t, cutDone, "first attach cut drain")
|
||||
cowWaitSignal(t, done, "destructive retry")
|
||||
if cutErr == nil {
|
||||
t.Fatal("first-attach window survived destructive transition")
|
||||
}
|
||||
if transitionErr != nil {
|
||||
t.Fatal(transitionErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A process stop while OPEN deliberately bypasses all Close/abort cleanups.
|
||||
// The parent gets the actual last remote HEAD, not a reconstructed proposal.
|
||||
func TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage(t *testing.T) {
|
||||
if path := os.Getenv("SWBLOCK_COW_CRASH_PATH"); path != "" {
|
||||
gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
s, err := CreateWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) {
|
||||
return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { gate.unblock(); _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
baseline, err := l.Cut(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lba := range []uint32{1, 5} {
|
||||
if _, err = s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gate.mu.Lock()
|
||||
gate.armed = true
|
||||
gate.mu.Unlock()
|
||||
cutDone, _ := cowStartCut(t, l, gate)
|
||||
w := l.cowActive.Load()
|
||||
w.mu.Lock()
|
||||
w.memory = cutCOWMemoryLimit
|
||||
w.mu.Unlock()
|
||||
if _, err = s.Write(5, makeBlock(ctBlockSize, 0x77)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.side == nil {
|
||||
t.Fatal("child has no live side file")
|
||||
}
|
||||
head := f.stats().head
|
||||
if head.Gen != baseline.Head.Gen {
|
||||
t.Fatal("OPEN cut already moved HEAD")
|
||||
}
|
||||
raw, err := json.Marshal(head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(path+".remote-head.json", raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-cutDone:
|
||||
t.Fatal("cut not OPEN at crash")
|
||||
default:
|
||||
}
|
||||
os.Exit(0) // intentional process crash: no cleanup runs
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "volume")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage$", "-test.timeout=20s")
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_COW_CRASH_PATH="+path)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("crash child: %v: %s", err, output)
|
||||
}
|
||||
stale, err := filepath.Glob(path + ".cut-cow-*")
|
||||
if err != nil || len(stale) != 1 {
|
||||
t.Fatalf("OPEN crash did not leave one spill: %v %v", stale, err)
|
||||
}
|
||||
raw, err := os.ReadFile(path + ".remote-head.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var head chunkHead
|
||||
if err = json.Unmarshal(raw, &head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head.RemoteLSN != 0 || len(head.Chunks) != 0 {
|
||||
t.Fatal("OPEN crash changed old HEAD")
|
||||
}
|
||||
s, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := s.Read(5); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0x77)) {
|
||||
t.Fatal("synced post-H write lost on reopen", err)
|
||||
}
|
||||
for _, name := range stale {
|
||||
if _, err = os.Stat(name); !os.IsNotExist(err) {
|
||||
t.Fatal("crash side not discarded", err)
|
||||
}
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
f.head = head
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
r, err := l.Cut(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(want[ctBlockSize:], makeBlock(ctBlockSize, 1))
|
||||
copy(want[5*ctBlockSize:], makeBlock(ctBlockSize, 0x77))
|
||||
if !bytes.Equal(f.imageOf(t, r.Head), want) {
|
||||
t.Fatal("next cut imported stale side bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD(t *testing.T) {
|
||||
for _, flushed := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "WAL-only-batch", true: "flushed-batch"}[flushed], func(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
source := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
for lba := 0; lba < 8; lba++ {
|
||||
copy(source[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x30+lba)))
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
f.seedHead(t, source, 0, 1)
|
||||
cfg := ctConfig(2)
|
||||
cfg.Bitmap = nil
|
||||
cfg.FreshFromHead = true
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
if _, err := s.Write(1, makeBlock(ctBlockSize, 0x51)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.WriteBatch(4, [][]byte{makeBlock(ctBlockSize, 0x54), makeBlock(ctBlockSize, 0x55)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if flushed {
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
live, releaseLive := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
unblockLive := func() { once.Do(func() { close(releaseLive) }) }
|
||||
l.testCOWRead = func(idx uint64, _ bool) {
|
||||
if idx == 0 {
|
||||
close(live)
|
||||
<-releaseLive
|
||||
}
|
||||
}
|
||||
cutDone, writeDone := make(chan struct{}), make(chan struct{})
|
||||
var cutErr, writeErr error
|
||||
writeStarted := false
|
||||
t.Cleanup(func() {
|
||||
unblockLive()
|
||||
cowWaitSignal(t, cutDone, "lazy cut cleanup")
|
||||
if writeStarted {
|
||||
cowWaitSignal(t, writeDone, "lazy saver cleanup")
|
||||
}
|
||||
})
|
||||
go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }()
|
||||
cowWaitSignal(t, live, "first actual copied chunk")
|
||||
gets, releaseGet := holdGets(t, f) // only the pending chunk still needs HEAD bytes
|
||||
writeStarted = true
|
||||
go func() { defer close(writeDone); _, writeErr = s.Write(6, makeBlock(ctBlockSize, 0x96)) }()
|
||||
waitKey(t, gets, "saving owner's actual lazy fetch")
|
||||
releaseGet()
|
||||
cowWaitSignal(t, writeDone, "lazy saving write")
|
||||
if writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
unblockLive()
|
||||
cowWaitSignal(t, cutDone, "lazy cut")
|
||||
if cutErr != nil {
|
||||
t.Fatal(cutErr)
|
||||
}
|
||||
want := append([]byte(nil), source...)
|
||||
for lba, value := range map[int]byte{1: 0x51, 4: 0x54, 5: 0x55} {
|
||||
copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, value))
|
||||
}
|
||||
if !bytes.Equal(f.imageOf(t, f.stats().head), want) {
|
||||
t.Fatal("COW saver lost WAL/batch bytes or lazy HEAD backing")
|
||||
}
|
||||
l.testCOWRead = nil
|
||||
next, err := l.Cut(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy(want[6*ctBlockSize:], makeBlock(ctBlockSize, 0x96))
|
||||
if !bytes.Equal(f.imageOf(t, next.Head), want) {
|
||||
t.Fatal("post-save mutation omitted by next cut")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This test-only metadata adapter parks a real extent read after ReadAt.
|
||||
// It changes no bytes and does not replace the v3 reader, WAL or flusher.
|
||||
type cowReadGate struct {
|
||||
mu sync.Mutex
|
||||
armed bool
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (g *cowReadGate) OnExtentWrite(uint32, []byte) error { return nil }
|
||||
func (g *cowReadGate) BeforeCheckpointAdvance(uint64) error { return nil }
|
||||
func (g *cowReadGate) VerifyExtent(lba uint32, _ []byte) error {
|
||||
g.mu.Lock()
|
||||
hold := g.armed && lba == 0
|
||||
if hold {
|
||||
g.armed = false
|
||||
}
|
||||
g.mu.Unlock()
|
||||
if hold {
|
||||
close(g.entered)
|
||||
<-g.release
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (g *cowReadGate) unblock() { g.once.Do(func() { close(g.release) }) }
|
||||
func cowWaitSignal(t *testing.T, ch <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(ctLocalBound):
|
||||
stacks := make([]byte, 1<<20)
|
||||
n := runtime.Stack(stacks, true)
|
||||
t.Fatalf("%s did not finish within %v\n%s", what, ctLocalBound, stacks[:n])
|
||||
}
|
||||
}
|
||||
|
||||
// R1/R11: a cut copying chunk 0 must allow an at-H image of pending chunk 1
|
||||
// to be saved and a new mutation published there. With one copy worker, the
|
||||
// second chunk is still pending. The first HEAD stays at H; the next cut
|
||||
// publishes the post-H mutation. Main's full-copy barrier fails progress.
|
||||
func TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld(t *testing.T) {
|
||||
for _, method := range []string{"Write", "WriteBatch", "ApplyEntry", "ApplyInstallEntry", "WriteOutsideD"} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
opts := WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) {
|
||||
return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil
|
||||
}}
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := s.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var completed InstallHandle
|
||||
if method == "ApplyInstallEntry" {
|
||||
completed, err = s.BeginBaseInstall(7, [16]byte{0xc1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = completed.MarkBaseComplete(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
remote := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
layer := mustAttach(t, s, remote, cfg)
|
||||
// Certify initially UNKNOWN chunks through the real capture, so the
|
||||
// measured cut has precisely chunks 0 and 1 as its candidates.
|
||||
if _, err = layer.Cut(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba, value := range map[uint32]byte{1: 0x21, 5: 0x65} {
|
||||
if _, err = s.Write(lba, makeBlock(ctBlockSize, value)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextLSN := s.NextLSN()
|
||||
gate.mu.Lock()
|
||||
gate.armed = true
|
||||
gate.mu.Unlock()
|
||||
type cutResult struct {
|
||||
cut chunkCutResult
|
||||
err error
|
||||
}
|
||||
cutResultCh := make(chan cutResult, 1)
|
||||
cutDone, writeDone := make(chan struct{}), make(chan struct{})
|
||||
writeErr := make(chan error, 1)
|
||||
writerStarted := false
|
||||
// Register release and actual joins before starting either worker.
|
||||
t.Cleanup(func() {
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "cut cleanup")
|
||||
if writerStarted {
|
||||
cowWaitSignal(t, writeDone, "mutation cleanup")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(cutDone)
|
||||
result, e := layer.Cut(context.Background())
|
||||
cutResultCh <- cutResult{result, e}
|
||||
}()
|
||||
cowWaitSignal(t, gate.entered, "actual chunk 0 extent-read admission")
|
||||
writerStarted = true
|
||||
go func() {
|
||||
defer close(writeDone)
|
||||
var e error
|
||||
switch method {
|
||||
case "Write":
|
||||
_, e = s.Write(5, makeBlock(ctBlockSize, 0xa5))
|
||||
case "WriteBatch":
|
||||
_, e = s.WriteBatch(5, [][]byte{makeBlock(ctBlockSize, 0xa5), makeBlock(ctBlockSize, 0xa6), makeBlock(ctBlockSize, 0xa7), makeBlock(ctBlockSize, 0xa8)})
|
||||
case "ApplyEntry":
|
||||
e = s.ApplyEntry(5, makeBlock(ctBlockSize, 0xa5), nextLSN)
|
||||
case "ApplyInstallEntry":
|
||||
e = completed.ApplyInstallEntry(5, makeBlock(ctBlockSize, 0xa5), nextLSN)
|
||||
case "WriteOutsideD":
|
||||
_, e = s.Write(21, makeBlock(ctBlockSize, 0xa5))
|
||||
}
|
||||
writeErr <- e
|
||||
}()
|
||||
// Require positive completion while the extent-read handshake is held.
|
||||
// The deadline bounds a liveness requirement, not a sleep proving entry.
|
||||
writeResultRead := false
|
||||
select {
|
||||
case e := <-writeErr:
|
||||
writeResultRead = true
|
||||
if e != nil {
|
||||
t.Fatalf("post-H mutation: %v", e)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Error("RED: mutation blocked behind another chunk's held copy; capture barrier still covers chunk I/O")
|
||||
}
|
||||
if writeResultRead {
|
||||
// Post-H bytes may checkpoint before this cut settles. Captured
|
||||
// versions must not certify that newer owned-map state as clean.
|
||||
if _, e := s.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := s.flusher.flushOnce(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "cut after read release")
|
||||
cowWaitSignal(t, writeDone, "mutation after read release")
|
||||
if !writeResultRead {
|
||||
if e := <-writeErr; e != nil {
|
||||
t.Fatalf("post-release mutation: %v", e)
|
||||
}
|
||||
}
|
||||
result := <-cutResultCh
|
||||
if result.err != nil {
|
||||
t.Fatal(result.err)
|
||||
}
|
||||
if method != "WriteOutsideD" && (result.cut.Stats.COWSavedChunks != 1 || result.cut.Stats.COWSaveNs <= 0) {
|
||||
t.Fatalf("real cut did not report its save: %+v", result.cut.Stats)
|
||||
}
|
||||
if result.cut.Stats.BarrierCopyChunks != 0 {
|
||||
t.Fatal("native cut reports data copied under barrier")
|
||||
}
|
||||
if result.cut.H != nextLSN-1 {
|
||||
t.Fatalf("cut H=%d want %d", result.cut.H, nextLSN-1)
|
||||
}
|
||||
image := remote.imageOf(t, result.cut.Head)
|
||||
want := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(want[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x21))
|
||||
copy(want[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 0x65))
|
||||
if !bytes.Equal(image, want) {
|
||||
t.Fatal("first HEAD is not the literal pre-H image")
|
||||
}
|
||||
changedLBA := 5
|
||||
if method == "WriteOutsideD" {
|
||||
changedLBA = 21
|
||||
}
|
||||
if got, e := s.Read(uint32(changedLBA)); e != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0xa5)) {
|
||||
t.Fatalf("local post-H image: %v", e)
|
||||
}
|
||||
second, e := layer.Cut(context.Background())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
copy(want[changedLBA*ctBlockSize:(changedLBA+1)*ctBlockSize], makeBlock(ctBlockSize, 0xa5))
|
||||
if method == "WriteBatch" {
|
||||
for i, value := range []byte{0xa6, 0xa7, 0xa8} {
|
||||
copy(want[(6+i)*ctBlockSize:(7+i)*ctBlockSize], makeBlock(ctBlockSize, value))
|
||||
}
|
||||
}
|
||||
if second.H <= result.cut.H || !bytes.Equal(remote.imageOf(t, second.Head), want) {
|
||||
t.Fatal("next cut omitted post-H mutation")
|
||||
}
|
||||
assertNoRemoteMisuse(t, remote)
|
||||
t.Logf("image controls passed: first H=%d has pre-H bytes, second H=%d has %s bytes", result.cut.H, second.H, method)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// R8 first-attachment race through the real Close/Attach callers. Holding
|
||||
// lifecycle shared lets us observe Close queued at lifecycle exclusive:
|
||||
// its initial nil hook snapshot has already happened on the parent. This
|
||||
// arm does not claim a live copier can start after that writer is queued.
|
||||
func TestCutCOWV3_CloseCannotMissFirstAttachment(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.chunk.Load() != nil {
|
||||
t.Fatal("fixture must start unattached")
|
||||
}
|
||||
s.lifecycleMu.RLock()
|
||||
var unlockOnce sync.Once
|
||||
unlock := func() { unlockOnce.Do(s.lifecycleMu.RUnlock) }
|
||||
closeDone := make(chan struct{})
|
||||
closeErr := make(chan error, 1)
|
||||
t.Cleanup(func() { unlock(); cowWaitSignal(t, closeDone, "Close cleanup") })
|
||||
go func() { defer close(closeDone); closeErr <- s.Close() }()
|
||||
deadline := time.NewTimer(ctLocalBound)
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
if !s.lifecycleMu.TryRLock() {
|
||||
break
|
||||
}
|
||||
s.lifecycleMu.RUnlock()
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatal("Close did not reach actual lifecycle-exclusive admission")
|
||||
case <-closeDone:
|
||||
t.Fatal("Close returned through a held lifecycle reader")
|
||||
default:
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
layer, err := attachChunkLayer(s, newFakeChunkRemote(), cfg)
|
||||
if err != nil && !errors.Is(err, errChunkLayerClosed) {
|
||||
t.Fatalf("unexpected first-attach refusal: %v", err)
|
||||
}
|
||||
if err == nil {
|
||||
t.Cleanup(func() { _ = layer.Close() })
|
||||
}
|
||||
unlock()
|
||||
cowWaitSignal(t, closeDone, "Close after lifecycle release")
|
||||
if err = <-closeErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if layer != nil {
|
||||
impl := layer.(*chunkLayerImpl)
|
||||
impl.stMu.Lock()
|
||||
drained := impl.closed
|
||||
impl.stMu.Unlock()
|
||||
if !drained {
|
||||
t.Error("RED: first attach succeeded after Close's nil snapshot and Close returned without closing that layer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// R8 live-copy arm: unlike the first-attach test, the real copier is already
|
||||
// inside its validated extent read. Close must not complete while it is held.
|
||||
// This is a preservation control on the barrier parent, not a claimed COW RED.
|
||||
func TestCutCOWV3_CloseJoinsHeldLiveCopy(t *testing.T) {
|
||||
for _, which := range []string{"Layer", "Store"} {
|
||||
t.Run(which, func(t *testing.T) {
|
||||
gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
opts := WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) {
|
||||
return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil
|
||||
}}
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap = nil
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
layer := mustAttach(t, s, newFakeChunkRemote(), cfg)
|
||||
gate.mu.Lock()
|
||||
gate.armed = true
|
||||
gate.mu.Unlock()
|
||||
cutDone, closeDone := make(chan struct{}), make(chan struct{})
|
||||
cutErr := make(chan error, 1)
|
||||
closeErr := make(chan error, 1)
|
||||
early := make(chan bool, 1)
|
||||
closeStarted := false
|
||||
t.Cleanup(func() {
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "live-copy cut cleanup")
|
||||
if closeStarted {
|
||||
cowWaitSignal(t, closeDone, "live-copy Close cleanup")
|
||||
}
|
||||
})
|
||||
go func() { defer close(cutDone); _, e := layer.Cut(context.Background()); cutErr <- e }()
|
||||
cowWaitSignal(t, gate.entered, "actual held live-copy read")
|
||||
closeStarted = true
|
||||
go func() {
|
||||
defer close(closeDone)
|
||||
var e error
|
||||
if which == "Layer" {
|
||||
e = layer.Close()
|
||||
} else {
|
||||
e = s.Close()
|
||||
}
|
||||
// Check actual event order rather than assuming an attempted call
|
||||
// reached Close based only on goroutine scheduling or a sleep.
|
||||
select {
|
||||
case <-gate.release:
|
||||
early <- false
|
||||
default:
|
||||
early <- true
|
||||
}
|
||||
closeErr <- e
|
||||
}()
|
||||
impl := layer.(*chunkLayerImpl)
|
||||
deadline := time.NewTimer(ctLocalBound)
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
impl.stMu.Lock()
|
||||
closing := impl.closed
|
||||
impl.stMu.Unlock()
|
||||
if closing {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatal("Close did not enter actual layer shutdown")
|
||||
default:
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
gate.unblock()
|
||||
cowWaitSignal(t, cutDone, "cut after live read release")
|
||||
cowWaitSignal(t, closeDone, "Close after live read release")
|
||||
if <-early {
|
||||
t.Error("Close returned before the live-copy read completed")
|
||||
}
|
||||
if e := <-closeErr; e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := <-cutErr; e == nil {
|
||||
t.Error("closed layer's cut unexpectedly published")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,9 @@ import (
|
||||
|
||||
// chunkHooks is what the WALStore holds for an attached layer.
|
||||
type chunkHooks struct {
|
||||
beforeMutation func(first, count uint64)
|
||||
beforeDestructive func() func()
|
||||
|
||||
sink chunkSink
|
||||
closer func() error
|
||||
// mutated runs after every dirty-map insert (a write, a batch write,
|
||||
@@ -61,6 +64,12 @@ type chunkLayerImpl struct {
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup // captures and fills in flight
|
||||
|
||||
cowMu sync.Mutex // window admission only; never held during reads or joins
|
||||
cow *cutCOWWindow
|
||||
cowActive atomic.Pointer[cutCOWWindow]
|
||||
cowTransitions int
|
||||
cowClosed bool
|
||||
|
||||
capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall
|
||||
bmMu sync.Mutex // serializes bitmap store calls
|
||||
presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version
|
||||
@@ -114,6 +123,9 @@ type chunkLayerImpl struct {
|
||||
keySeq uint64
|
||||
|
||||
// Test-only scheduling hooks; nil in production.
|
||||
testCOWWait func()
|
||||
testCOWRead func(idx uint64, saved bool)
|
||||
testCOWSave func() error
|
||||
testPresenceSnapshotHook func() // after a presence snapshot, before it is written
|
||||
testBaseTransitionBeforeLock func() // test handshake before capMu drain
|
||||
testAfterAdmitHook func() // right after a capture is admitted
|
||||
@@ -139,11 +151,14 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
return nil, errors.New("storage: chunk layer needs a remote, ChunkBlocks > 0 and a legacy bitmap unless the store owns an impl3 map")
|
||||
}
|
||||
var localBase bool
|
||||
s.captureMu.Lock()
|
||||
defer s.captureMu.Unlock()
|
||||
if s.attachClosed {
|
||||
return nil, errChunkLayerClosed
|
||||
}
|
||||
if mapped {
|
||||
// Serialize hook publication with begin/complete. Their outer hook
|
||||
// snapshot is rechecked after taking this same barrier.
|
||||
s.captureMu.Lock()
|
||||
defer s.captureMu.Unlock()
|
||||
d := s.v3.pub.current()
|
||||
if d.BaseState == BaseInstalling {
|
||||
return nil, ErrBaseIncomplete
|
||||
@@ -284,6 +299,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated}
|
||||
if mapped {
|
||||
hooks.baseTransitionV3 = l.holdBaseTransitionV3
|
||||
hooks.beforeMutation = l.beforeCOWMutation
|
||||
hooks.beforeDestructive = l.holdCOWDestructive
|
||||
}
|
||||
if !s.chunk.CompareAndSwap(nil, hooks) {
|
||||
l.cancel()
|
||||
@@ -686,7 +703,12 @@ func (l *chunkLayerImpl) register() (done func(), err error) {
|
||||
return l.wg.Done, nil
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) admit() error {
|
||||
func (l *chunkLayerImpl) admit() (err error) {
|
||||
defer func() {
|
||||
if err != nil {
|
||||
l.abortCOW(err)
|
||||
}
|
||||
}()
|
||||
if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling {
|
||||
return fmt.Errorf("%w: %w", errChunkCaptureRefused, errChunkBaseInstalling)
|
||||
}
|
||||
@@ -872,23 +894,38 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.stMu.Unlock()
|
||||
|
||||
st.CandidateChunks = len(candidates)
|
||||
st.BarrierCopyChunks = len(candidates) - len(useStaged)
|
||||
var copyErr error
|
||||
copyStart := time.Now()
|
||||
for _, idx := range sortedKeys(candidates) {
|
||||
if useStaged[idx] {
|
||||
continue
|
||||
if l.usesOwnedMapV3() {
|
||||
var w *cutCOWWindow
|
||||
w, copyErr = l.installCOWWindow(candidates, useStaged)
|
||||
l.s.captureMu.Unlock()
|
||||
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
|
||||
copyStart = time.Now()
|
||||
if copyErr == nil {
|
||||
var copied []capturedChunk
|
||||
copied, copyErr = l.copyCOWWindow(ctx, w)
|
||||
captured = append(captured, copied...)
|
||||
st.COWSavedChunks = int(w.saved.Load())
|
||||
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
|
||||
}
|
||||
buf, err := l.readChunk(idx)
|
||||
if err != nil {
|
||||
copyErr = err
|
||||
break
|
||||
} else {
|
||||
st.BarrierCopyChunks = len(candidates) - len(useStaged)
|
||||
for _, idx := range sortedKeys(candidates) {
|
||||
if useStaged[idx] {
|
||||
continue
|
||||
}
|
||||
buf, err := l.readChunk(idx)
|
||||
if err != nil {
|
||||
copyErr = err
|
||||
break
|
||||
}
|
||||
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
|
||||
}
|
||||
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
|
||||
l.s.captureMu.Unlock()
|
||||
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
|
||||
}
|
||||
st.CopyNs = time.Since(copyStart).Nanoseconds()
|
||||
l.s.captureMu.Unlock()
|
||||
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
|
||||
if copyErr != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
@@ -1002,6 +1039,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.stMu.Lock()
|
||||
l.fenced, l.head = true, copyHead(cur)
|
||||
l.stMu.Unlock()
|
||||
l.abortCOW(errChunkLayerFenced)
|
||||
return chunkCutResult{}, errChunkLayerFenced
|
||||
}
|
||||
l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS
|
||||
@@ -1020,6 +1058,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.stMu.Lock()
|
||||
l.fenced = true
|
||||
l.stMu.Unlock()
|
||||
l.abortCOW(errChunkLayerFenced)
|
||||
return chunkCutResult{}, errChunkLayerFenced
|
||||
}
|
||||
expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch}
|
||||
@@ -1077,6 +1116,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.fenced = true
|
||||
l.head = copyHead(cur)
|
||||
l.stMu.Unlock()
|
||||
l.abortCOW(errChunkLayerFenced)
|
||||
return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
@@ -1162,7 +1202,13 @@ func sameProposal(cur, next chunkHead) bool {
|
||||
}
|
||||
|
||||
// resolvePending re-reads HEAD when an earlier CAS outcome is unresolved.
|
||||
func (l *chunkLayerImpl) resolvePending(ctx context.Context) error {
|
||||
func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
|
||||
// Registered before the state unlock, so invalidation runs without stMu.
|
||||
defer func() {
|
||||
if errors.Is(err, errChunkLayerFenced) {
|
||||
l.abortCOW(err)
|
||||
}
|
||||
}()
|
||||
l.stMu.Lock()
|
||||
pending, base, intents := l.pending, l.pendingBase, l.pendingIntents
|
||||
l.stMu.Unlock()
|
||||
@@ -1877,7 +1923,17 @@ func (l *chunkLayerImpl) Close() error {
|
||||
}
|
||||
l.closed = true
|
||||
l.stMu.Unlock()
|
||||
l.cowMu.Lock()
|
||||
l.cowClosed = true
|
||||
w := l.cow
|
||||
if w != nil {
|
||||
w.abort(errChunkLayerClosed)
|
||||
}
|
||||
l.cowMu.Unlock()
|
||||
l.cancel()
|
||||
if w != nil {
|
||||
w.join()
|
||||
}
|
||||
l.wg.Wait()
|
||||
close(l.closeDone)
|
||||
return nil
|
||||
|
||||
@@ -286,10 +286,10 @@ func TestChunkIntent_AdmissionRefusedBeforeCASDeletesIntent(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
calls := 0
|
||||
cfg.CaptureAllowed = func() error {
|
||||
calls++
|
||||
if calls >= 2 { // the cut's start passes; the check before the CAS refuses
|
||||
// The gate is checked concurrently between COW claims as well. Bind
|
||||
// demotion to the real upload event, not a call count/schedule.
|
||||
if f.stats().puts > 0 { // uploaded under an intent, before the CAS
|
||||
return errors.New("demoted")
|
||||
}
|
||||
return nil
|
||||
@@ -300,6 +300,9 @@ func TestChunkIntent_AdmissionRefusedBeforeCASDeletesIntent(t *testing.T) {
|
||||
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
|
||||
t.Fatalf("cut refused before its CAS: %v", err)
|
||||
}
|
||||
if f.stats().puts == 0 {
|
||||
t.Fatal("control did not reach the intent-protected upload")
|
||||
}
|
||||
if n := f.stats().cas; n != 0 {
|
||||
t.Fatalf("refused cut issued %d CAS", n)
|
||||
}
|
||||
|
||||
@@ -44,8 +44,8 @@ func assertNoIntentsLeft(t *testing.T, f *fakeChunkRemote) {
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk re-dirtied between staging and the barrier is copied again under
|
||||
// the barrier: HEAD has the newer bytes, never the stale stage. Both ways a
|
||||
// A chunk re-dirtied between staging and the barrier is copied again in
|
||||
// the COW window: HEAD has the newer bytes, never the stale stage. Both ways a
|
||||
// write can reach a staged chunk are covered: flushed to the extent (its
|
||||
// chunk version moves) and still in the WAL.
|
||||
func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) {
|
||||
@@ -68,8 +68,8 @@ func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) {
|
||||
if r.Stats.StageRounds != 1 || r.Stats.StagedChunks != 2 {
|
||||
t.Fatalf("staging: %d rounds, %d chunks; want 1 round of 2", r.Stats.StageRounds, r.Stats.StagedChunks)
|
||||
}
|
||||
if r.Stats.StagedChunksUsed != 1 || r.Stats.BarrierCopyChunks != 2 || r.Stats.BarrierOverBound {
|
||||
t.Fatalf("barrier: %d staged used, %d copied, over bound %v; want chunk 1 from staging, chunks 0 and 2 copied, within the bound",
|
||||
if r.Stats.StagedChunksUsed != 1 || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != 3 || r.Stats.BarrierOverBound {
|
||||
t.Fatalf("barrier: %d staged used, %d copied, over bound %v; want chunk 1 from staging, chunks 0 and 2 copied outside the barrier",
|
||||
r.Stats.StagedChunksUsed, r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
@@ -78,8 +78,8 @@ func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Writes that outpace the staging: after three rounds the barrier copies
|
||||
// the rest even above the bound, counts it, and the image is still exact.
|
||||
// Writes that outpace staging: after three rounds the COW window copies
|
||||
// all remaining chunks outside the barrier, keeping the image exact.
|
||||
func TestChunkPrecopy_WritesOutpacingStagingGoOverBound(t *testing.T) {
|
||||
s, f, l, w := precopyLayer(t, 2, 4)
|
||||
l.testAfterStageHook = func(round int) {
|
||||
@@ -94,11 +94,11 @@ func TestChunkPrecopy_WritesOutpacingStagingGoOverBound(t *testing.T) {
|
||||
if r.Stats.StageRounds != 3 { // the ruling: at most three rounds
|
||||
t.Fatalf("%d staging rounds, want 3", r.Stats.StageRounds)
|
||||
}
|
||||
if !r.Stats.BarrierOverBound || r.Stats.BarrierCopyChunks != 4 {
|
||||
t.Fatalf("barrier copied %d chunks, over bound %v; want all 4, over the bound of 2", r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound)
|
||||
if r.Stats.BarrierOverBound || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != 4 {
|
||||
t.Fatalf("barrier copied %d chunks, over bound %v; want all 4 candidates copied outside the barrier", r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound)
|
||||
}
|
||||
if got := l.Stats().BarrierOverBound; got != 1 {
|
||||
t.Fatalf("BarrierOverBound counter %d, want 1", got)
|
||||
if got := l.Stats().BarrierOverBound; got != 0 {
|
||||
t.Fatalf("BarrierOverBound counter %d, want 0 for COW", got)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
assertNoIntentsLeft(t, f)
|
||||
@@ -112,8 +112,8 @@ func TestChunkPrecopy_NoStagingWithoutNeed(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.StageRounds != 0 || r.Stats.BarrierCopyChunks != tc.n || r.Stats.BarrierOverBound {
|
||||
t.Fatalf("bound %d, %d dirty: %d rounds, %d copied, over %v; want no staging, all copied under the barrier",
|
||||
if r.Stats.StageRounds != 0 || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != tc.n || r.Stats.BarrierOverBound {
|
||||
t.Fatalf("bound %d, %d dirty: %d rounds, %d copied, over %v; want no staging, all copied outside the barrier",
|
||||
tc.bound, tc.n, r.Stats.StageRounds, r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
|
||||
@@ -32,8 +32,8 @@ func TestChunkCutStats_PublishedZeroedUnchangedAndNoop(t *testing.T) {
|
||||
if st.CASResult != "ok" || st.CASNs < 0 || st.UploadNs < 0 || st.TotalNs <= 0 {
|
||||
t.Fatalf("first cut timings/result %+v", st)
|
||||
}
|
||||
if st.BarrierPauseNs <= 0 || st.BarrierPauseNs < st.SyncNs || st.BarrierPauseNs < st.CopyNs {
|
||||
t.Fatalf("barrier %d ns must cover sync %d and copy %d", st.BarrierPauseNs, st.SyncNs, st.CopyNs)
|
||||
if st.BarrierPauseNs <= 0 || st.BarrierPauseNs < st.SyncNs {
|
||||
t.Fatalf("barrier %d ns must cover sync %d; copy %d is outside it", st.BarrierPauseNs, st.SyncNs, st.CopyNs)
|
||||
}
|
||||
if st.TotalNs < st.BarrierPauseNs+st.UploadNs+st.CASNs {
|
||||
t.Fatalf("total %d ns shorter than barrier %d + upload %d + CAS %d", st.TotalNs, st.BarrierPauseNs, st.UploadNs, st.CASNs)
|
||||
|
||||
@@ -45,6 +45,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCutCOWAborted = errCutCOWAborted
|
||||
ErrChunkKeyExists = errChunkKeyExists
|
||||
ErrChunkHeadPrecondition = errChunkHeadPrecondition
|
||||
ErrChunkHeadDeleted = errChunkHeadDeleted
|
||||
|
||||
@@ -15,12 +15,12 @@ package storage
|
||||
// 1. blocks new writes at the store and waits for in-flight ones;
|
||||
// 2. Syncs; H is then the synced LSN (nextLSN-1) and no data newer than H
|
||||
// exists in the WAL or the extent. The flusher is not drained;
|
||||
// 3. under that barrier reads every chunk dirtied since the last HEAD
|
||||
// through the store's normal read path (dirty map/WAL entry if present,
|
||||
// else extent) into immutable buffers; that is exactly the image at H.
|
||||
// A chunk counts as dirty since HEAD whether its newer blocks are still
|
||||
// in the WAL or already in the extent;
|
||||
// 4. releases the barrier (pause = Sync + copy of the dirty chunks);
|
||||
// 3. fixes the candidate set and installs an owned-map v3 COW window under
|
||||
// that barrier, then releases it (pause = Sync + window installation);
|
||||
// 4. copies outside the barrier. Before publication, the first writer to a
|
||||
// pending candidate saves its at-H chunk; writers wait for a copying or
|
||||
// saving owner. Both paths use the validated store reader. Legacy test
|
||||
// fixtures retain the full-copy barrier;
|
||||
// 5. uploads the buffers, outside every walstore lock;
|
||||
// 6. CASes HEAD {gen, epoch} with RemoteLSN = H.
|
||||
//
|
||||
@@ -338,6 +338,7 @@ type chunkLayerConfig struct {
|
||||
// that last check and the CAS. Publication safety across a demotion
|
||||
// rests on the epoch: a new primary's takeover raises the HEAD epoch, so
|
||||
// the old primary's CAS fails and it fences (C6). Nil allows capture.
|
||||
// COW workers may call this concurrently, between chunk claims.
|
||||
CaptureAllowed func() error
|
||||
// ReadMissTimeout bounds one OnReadMiss remote fetch.
|
||||
ReadMissTimeout time.Duration
|
||||
@@ -368,6 +369,9 @@ type chunkLayerConfig struct {
|
||||
// chunkCutStats describes one cut. The periodic-cut work fills it; a zero
|
||||
// value means "not measured".
|
||||
type chunkCutStats struct {
|
||||
COWSavedChunks int
|
||||
COWSaveNs int64
|
||||
COWWaitNs int64
|
||||
BarrierPauseNs int64
|
||||
SyncNs int64
|
||||
CopyNs int64
|
||||
|
||||
@@ -81,8 +81,8 @@ func (s *WALStore) resetIncarnationV3() error {
|
||||
if v == nil {
|
||||
return errors.New("storage: reset on a non-v3 store")
|
||||
}
|
||||
s.captureMu.Lock()
|
||||
defer s.captureMu.Unlock()
|
||||
release := s.holdChunkDestructive(true)
|
||||
defer release()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
v.syncMu.Lock()
|
||||
|
||||
@@ -81,6 +81,13 @@ type WALStore struct {
|
||||
// (before lifecycleMu); a quiesced cut holds it exclusively. Order:
|
||||
// captureMu -> lifecycleMu -> mu.
|
||||
captureMu sync.RWMutex
|
||||
// captureMu orders permanent attachment shutdown with hook publication.
|
||||
attachClosed bool
|
||||
closeComplete chan struct{}
|
||||
closeResult error
|
||||
testDestructiveSnapshot func() // nil scheduling control, before any capture lock
|
||||
testCloseSnapshot func() // nil in production; called without captureMu
|
||||
|
||||
// chunk is the attached chunk layer's hooks; nil when none.
|
||||
chunk atomic.Pointer[chunkHooks]
|
||||
extentMu [64]sync.RWMutex
|
||||
@@ -603,12 +610,12 @@ func (s *WALStore) HolesSuspected() uint64 {
|
||||
// Idempotent: calling Recover twice on the same on-disk state yields
|
||||
// identical results.
|
||||
func (s *WALStore) Recover() (frontier uint64, err error) {
|
||||
// Recover republishes the dirty map like a write: it holds the capture
|
||||
// barrier shared, so it can never publish bytes between a quiesced
|
||||
// cut's Sync (which fixes H) and that cut's copy.
|
||||
// Order: captureMu -> lifecycleMu -> mu.
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
// Drain an attached COW window before taking any lower lock. The lease
|
||||
// blocks a replacement window and retries a racing first attachment.
|
||||
// Legacy fixtures retain their shared barrier ordering with full copying.
|
||||
// Order after drain: captureMu -> lifecycleMu -> syncMu -> mu.
|
||||
release := s.holdChunkDestructive(false)
|
||||
defer release() // also releases captureMu, after all lower locks
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if s.v3 != nil {
|
||||
@@ -720,8 +727,6 @@ func (s *WALStore) Recover() (frontier uint64, err error) {
|
||||
func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -736,6 +741,10 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
// is disabled (admission==nil), Write proceeds immediately. The
|
||||
// admission Acquire may block up to admissionTimeout — under
|
||||
// hard pressure it spins waiting for the flusher to drain.
|
||||
s.beforeChunkMutation(uint64(lba), 1)
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
|
||||
if s.admission != nil {
|
||||
if err := s.admission.Acquire(s.admissionTimeout); err != nil {
|
||||
return 0, fmt.Errorf("storage: WAL admission: %w", err)
|
||||
@@ -805,8 +814,6 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) {
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -823,6 +830,10 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error
|
||||
}
|
||||
}
|
||||
|
||||
s.beforeChunkMutation(uint64(startLBA), uint64(len(blocks)))
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
|
||||
if s.admission != nil {
|
||||
if err := s.admission.Acquire(s.admissionTimeout); err != nil {
|
||||
return nil, fmt.Errorf("storage: WAL admission: %w", err)
|
||||
@@ -1516,12 +1527,27 @@ func bytesAllZero(data, zero []byte) bool {
|
||||
// Close persists current WAL boundaries into the superblock,
|
||||
// fsyncs the file, stops the group committer, and releases the
|
||||
// underlying file. Idempotent.
|
||||
func (s *WALStore) Close() error {
|
||||
// Stop the chunk layer before taking the lifecycle lock: its captures
|
||||
// and fills call back into the store.
|
||||
if h := s.chunk.Load(); h != nil {
|
||||
func (s *WALStore) Close() (err error) {
|
||||
s.captureMu.Lock()
|
||||
if s.attachClosed {
|
||||
done := s.closeComplete
|
||||
s.captureMu.Unlock()
|
||||
<-done
|
||||
return s.closeResult
|
||||
}
|
||||
s.attachClosed = true
|
||||
s.closeComplete = make(chan struct{})
|
||||
h := s.chunk.Load()
|
||||
s.captureMu.Unlock()
|
||||
defer func() { s.closeResult = err; close(s.closeComplete) }()
|
||||
if s.testCloseSnapshot != nil {
|
||||
s.testCloseSnapshot()
|
||||
}
|
||||
// No capture or store lock is held while callbacks drain actual I/O.
|
||||
if h != nil {
|
||||
_ = h.closer()
|
||||
}
|
||||
|
||||
s.lifecycleMu.Lock()
|
||||
defer s.lifecycleMu.Unlock()
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -331,6 +331,10 @@ func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOption
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := discardCutCOWFiles(path); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return openWALStoreV3File(path, f, requireMap, opts, nil, false)
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ An agent workspace disk is a composition of core parts plus a SeaweedFS chunk ba
|
||||
flowchart LR
|
||||
G["guest microVM"] -->|"virtio-blk"| F["frontend: ublk or NVMe/TCP loopback"]
|
||||
F -->|"Read / Write / Sync"| W["local engine: walstore"]
|
||||
W -->|"dirty chunk bitmap"| C["chunk layer: quiesced cut"]
|
||||
W -->|"owned chunk LSN map + WAL dirt"| C["chunk layer: short barrier + COW cut"]
|
||||
C -->|"upload changed 4 MiB chunks, intents first"| S[("SeaweedFS: immutable chunks + segment manifests")]
|
||||
C -->|"CAS HEAD on {gen, epoch}"| H["HEAD root (about 2 KB)"]
|
||||
H -->|"snapshot / fork = copy the root"| H2["snapshot or forked volume"]
|
||||
@@ -70,7 +70,7 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t
|
||||
| Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost |
|
||||
| Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume |
|
||||
|
||||
- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) only bounds how much one cut copies under its barrier; it never triggers a cut.
|
||||
- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut.
|
||||
- **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer.
|
||||
- Multi-replica workspaces combined with chunk snapshots are not supported.
|
||||
|
||||
@@ -111,11 +111,9 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
|
||||
## 4. Dirty tracking
|
||||
|
||||
- **In memory:** every extent write marks its chunk dirty, in O(1), with no I/O and no remote call (`chunk_layer.go` `OnExtentWrite`; the set is `chunkLayerImpl.dirty`). A rebuild BASE write sets a constant-time all-dirty flag instead.
|
||||
- **Off the write path:** WAL entries carry their LBA, so the dirty set is the persisted bitmap plus the chunks of WAL entries above the checkpoint (`walChunks`). The bitmap is made durable before the checkpoint advances past those entries (`BeforeCheckpointAdvance`, called from walstore `persistCheckpointReleasing`); an error refuses the advance and the WAL keeps the entries.
|
||||
- **On disk:** `FileChunkBitmapStore` (`core/storage/chunk_bitmap_file.go`) is one state file (a header `{BaseLSN, HeadGen, Epoch, Base}` and the dirty chunk indices, with a SHA-256 over the body) replaced atomically on every change, plus an append-only delta log with one record per closed HEAD period.
|
||||
- **Reset:** only after a successful HEAD CAS at cut H. The new header is `{BaseLSN: H, HeadGen, Epoch}`; chunks dirtied after the cut stay set (`chunkBitmapStore.Reset`, stillDirty).
|
||||
- **Over-report, never under-report.** A lost bitmap, or a header that does not match HEAD `{RemoteLSN, Gen, Epoch}`, falls back to a background per-chunk SHA-256 comparison against HEAD; cuts are refused until it finishes (`startReconcile`, `errChunkReconciling`).
|
||||
- **Native v3:** the owned per-chunk LSN map and retained WAL/in-memory mutations determine dirt relative to HEAD (`captureCandidates`). UNKNOWN is conservative. Map coverage is durable with the checkpoint before reuse, and a cut certifies only unchanged captured versions after successful publication.
|
||||
- **Post-H writes:** per-chunk mutation versions prevent a cut from certifying newer local bytes as remotely clean. Abort merges every in-flight candidate back into dirt.
|
||||
- **Legacy evidence:** temporary v2 test constructors retain fake bitmap branches and old-format codec controls. There is no production FileChunkBitmapStore or C11 file; the owned map is authoritative for v3.
|
||||
|
||||
## 5. The cut
|
||||
|
||||
@@ -124,13 +122,13 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease).
|
||||
2. **Pre-copy:** while more than `BarrierBound` chunks would be copied under the barrier (`--chunk-dirty-threshold`, default 512), stage up to that many per round outside the barrier, for at most `chunkStageRounds` (3) rounds (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first.
|
||||
3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent.
|
||||
4. **Copy:** read every candidate chunk through the normal read path into immutable buffers and hash them; release the barrier. The pause is `Sync` plus this copy. A staged copy is reused only if its chunk was not written since and HEAD is unchanged.
|
||||
4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes.
|
||||
5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`).
|
||||
6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map.
|
||||
7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64).
|
||||
8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`).
|
||||
9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`).
|
||||
10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and reset the bitmap, keeping post-cut dirt.
|
||||
10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt.
|
||||
11. **Unknown outcome:** re-read HEAD; never retry blindly. If unresolved, keep the proposal pending and keep the intents.
|
||||
|
||||
`ChunkRemote.CASHead` (`core/frontend/chunkstore/chunk_remote.go`) refuses a lower epoch, any move of a `deleting`, `purging` or `deleted` HEAD, a `{gen, epoch}` mismatch and a lower `RemoteLSN`, then issues the filer's conditional `UpdateEntry` with `expected_extended = {swb.gen, swb.epoch}`. Only a definite refusal is a precondition failure; any other error is an unknown outcome.
|
||||
@@ -138,24 +136,24 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, bounded by `ReadMissTimeout` (default 30 s), and installed only if it does not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`).
|
||||
|
||||
|
||||
### Copy-before-write in the cut window (proposed, not implemented)
|
||||
### Copy-before-write in the cut window (native v3 implementation)
|
||||
|
||||
**Problem.** Steps 3–4 hold `captureMu` exclusively while every non-staged candidate chunk is copied; `Write`, `WriteBatch`, `ApplyEntry` and `WriteExtentDirect` take `captureMu` shared, so every write waits for the whole copy. A cut-stall measurement on two lab hosts gave a maximum stall of 1.50 s with 3 GiB dirty and 0.67 s with 512 MiB (p99 15–20 ms). Pre-copy staging shortens it only when the staging rounds converge.
|
||||
**Problem.** Steps 3–4 hold `captureMu` exclusively while every non-staged candidate chunk is copied; `Write`, `WriteBatch`, `ApplyEntry` and `WriteExtentDirect` take `captureMu` shared, so every write waited for the whole copy. A cut-stall measurement on two lab hosts gave a maximum stall of 1.50 s with 3 GiB dirty and 0.67 s with 512 MiB (p99 15–20 ms). Pre-copy staging shortens it only when the staging rounds converge.
|
||||
|
||||
**Design.**
|
||||
1. **Short barrier; `capMu` held for the whole cut.** The chunk layer's `capMu` stays held from admission to the end of the cut, as today; it already serializes Capture with Evict and Begin/EndBaseInstall, so no BASE install can start inside a window. Under `captureMu` exclusive the cut's `Sync` fixes H and the candidate set D is fixed as today (the dirty bitmap plus the chunks of WAL entries above the checkpoint). A COW window `{H, D, state per chunk, refcount}` is installed in the chunk layer, then only `captureMu` is released. The stall becomes `Sync` plus fixing D, independent of the bytes to copy.
|
||||
1. **Short barrier; `capMu` held for the whole cut.** The chunk layer's `capMu` stays held from admission to the end of the cut, as today; it already serializes Capture with Evict and Begin/EndBaseInstall, so no BASE install can start inside a window. Under `captureMu` exclusive the cut's `Sync` fixes H and the candidate set D is fixed as today (the owned chunk LSN map relative to HEAD plus retained WAL and in-memory mutations). A COW window `{H, D, state per chunk, refcount}` is installed in the chunk layer, then only `captureMu` is released. The stall becomes `Sync` plus fixing D, independent of the bytes to copy.
|
||||
2. **Per-chunk state and one owner.** Each chunk of D is `pending`, then exactly one owner moves it on, under a small per-chunk mutex that is never held across I/O:
|
||||
- the copier: `pending → copying → done`;
|
||||
- a writer: `pending → saving → saved` (the copier later reads the saved bytes: `saved → done`).
|
||||
- the copier: `pending â†' copying â†' done`;
|
||||
- a writer: `pending â†' saving â†' saved` (the copier later reads the saved bytes: `saved â†' done`).
|
||||
Everyone else who finds `copying` or `saving` waits on that chunk's condition until it reaches `done` or `saved`, or until the window is aborted (step 5).
|
||||
3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) → per-chunk COW mutex (leaf, released before any read) → the read path's own locks.
|
||||
3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) â†' per-chunk COW mutex (leaf, released before any read) â†' the read path's own locks.
|
||||
- chunk not in D, `done` or `saved`: proceed;
|
||||
- `pending`: become the owner (`saving`), read the chunk (still its content at H), put it in the side store, mark `saved`, wake waiters, proceed;
|
||||
- `copying` or `saving`: wait (step 2), then re-check.
|
||||
- **Batches across chunks** (`WriteBatch`, a multi-block `ApplyEntry`): visit the batch's chunks in ascending chunk index and finish each chunk's step (wait, or save) before the next; no chunk is held while waiting on another, so batches cannot deadlock with each other or with the copier, which owns one chunk at a time. The batch publishes only after all its chunks are `saved`, `done` or outside D.
|
||||
- **Batches across chunks** (`WriteBatch`; public `ApplyEntry` accepts one block): visit the batch's chunks in ascending chunk index and finish each chunk's step (wait, or save) before the next; no chunk is held while waiting on another, so batches cannot deadlock with each other or with the copier, which owns one chunk at a time. The batch publishes only after all its chunks are `saved`, `done` or outside D.
|
||||
4. **Copier**, outside the barrier and parallel: for each chunk of D, become the owner (`copying`) or find `saved`; read the live chunk (or the saved bytes) into the cut's immutable buffer, hash it, mark `done`, wake waiters. When every chunk of D is `done`, the window closes: no mutation runs the COW step any more. Upload, manifest and CAS are unchanged (steps 5–11) and work from the buffers, so an unknown CAS outcome keeps today's semantics (proposal pending, intents kept); it does not need the side store.
|
||||
5. **Terminal states: closed, or aborted.** The window ends exactly once, either closed (step 4) or aborted. Abort is taken on a save error (side store full or an I/O error), cut cancellation, fencing, and before `Recover`, a reset or `Close` in the same open. Abort happens **before** the mutation that hit the error proceeds: the cut is marked failed (retryable, `finishCut` does not run, so the dirty set keeps every candidate and the next cut takes them again), all waiters are woken and proceed without saving, and the copier stops. A guest write is never refused because of a cut problem. `Recover`, a reset and `Close` wait for the abort to finish and join every outstanding owner and reader (step 6) before they take their own locks.
|
||||
6. **Side store and drain.** Local and per cut: memory up to a bound, then a file in the volume's local root; at most |D| × 4 MiB, in practice the chunks written during the window. Every saving or copying owner holds a window reference from its state claim until all of its live-chunk reads and side-store I/O finish; every additional saved-buffer or side-store reader holds a reference too. Abort atomically invalidates the cut and wakes waiters without waiting for its caller's own reference. Owners release their references on every success and error path; an owner that initiates an abort releases its own reference before any join. `Recover`, a reset and `Close` join all outstanding owners and readers before their destructive transition. The side store is deleted exactly once, after the window is closed or aborted **and** no reference is outstanding; no later state claim or I/O may acquire a reference to that terminal window. Recovery never reads it: after a crash the cut is gone, HEAD is unchanged, and the dirty set is rebuilt from the bitmap and the WAL as today.
|
||||
6. **Side store and drain.** Local and per cut: memory up to a bound, then a file in the volume's local root; at most |D| × 4 MiB, in practice the chunks written during the window. Every saving or copying owner holds a window reference from its state claim until all of its live-chunk reads and side-store I/O finish; every additional saved-buffer or side-store reader holds a reference too. Abort atomically invalidates the cut and wakes waiters without waiting for its caller's own reference. Owners release their references on every success and error path; an owner that initiates an abort releases its own reference before any join. `Recover`, a reset and `Close` join all outstanding owners and readers before their destructive transition. The side store is deleted exactly once, after the window is closed or aborted **and** no reference is outstanding; no later state claim or I/O may acquire a reference to that terminal window. Recovery never reads it: after a crash the cut is gone, HEAD is unchanged, and the dirty set is rebuilt from the owned map and the WAL. A locked RW open discards only regular files with this volume's reserved `.cut-cow-` prefix; it never reads their contents.
|
||||
7. **Reads go through the store's read path as the format-v3 work defines it** (the stable, validated reader), both for the save and for the copier; COW adds no flusher hook and no raw extent read. The flusher moves WAL content to the extent without changing what a read returns, so saving at the flusher would miss writes still in the WAL.
|
||||
8. **After the CAS** the dirty set keeps every chunk written after H, as `finishCut` does today, so the next cut uploads them.
|
||||
|
||||
@@ -163,9 +161,25 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
|
||||
**Alternatives.** Holding the flusher for candidate chunks (reading the at-H content back from the extent and WAL entries up to H) needs no side store, but the WAL cannot be released for those chunks during the window, and a long upload fills it. Raising `BarrierBound` staging does not bound the stall when writes keep re-dirtying staged chunks. Redirect-on-write at the extent changes the on-disk layout and is out of scope for the current format work.
|
||||
|
||||
**Model.** [`docs/spec/CutCOW.tla`](../spec/CutCOW.tla) (S4c in the [spec README](../spec/README.md)) checks today's barrier cut and this design with one crash: every uploaded chunk equals the image at H (`HeadImage`, `BufFrozen`), reads return the newest write, and the side store never outlives its cut. Both pass exhaustively at MaxLSN 6 with 2 cuts. The model abstracts a write to one whole chunk, has one copier and no abort action (an abort behaves like a crash for HEAD: the cut is dropped and HEAD is unchanged), so owner races between writers, batch ordering and the abort protocol (steps 2, 3 and 5) are specified here, not model-checked. Each rule the model does cover is necessary: a saved copy taken after the write, no save, admitting writes before D is fixed, saving at the flusher, reusing the side store in the next cut, or skipping the per-chunk wait each uploads a chunk that is not the image at H.
|
||||
**Implementation and lifetime.** `chunk_cut_cow.go` owns the window, single-owner chunk claims and reference drain; the write hook runs before lifecycle/admission/store locks. Copier workers use the configured upload concurrency (default 8). Side payload retains at most 64 MiB in RAM, then spills to an ephemeral file beside the volume, in checked compact candidate slots. This is not an RSS cap: immutable upload buffers and transient owner reads remain additional memory. Side I/O failures abort the cut, not the guest write. Cleanup failures fail the cut diagnostically; side files are never durable evidence.
|
||||
|
||||
**Tests to write with the code.** RED first: a write during the window to an uncopied candidate, with the hook absent, must upload new bytes. Then: a write racing the copier on the same chunk (the per-chunk wait); two writers racing for one pending chunk (one owner, one wait); two batches over the same chunks in opposite LBA order (no deadlock); a save error (cut fails retryable, the write succeeds, the next cut uploads every candidate); `Close` and `Recover` during an open window, including with a held `saving` owner and a held live-copy owner (abort, join, side store deleted once); an unknown CAS outcome after the window closed; a crash during the window (reopen, no side store read, HEAD unchanged, next cut correct); the barrier pause no longer grows with dirty bytes; new statistics (`cowSavedChunks`, `cowSaveNs`, `cowWaitNs`) in `ChunkCutStats`, which the cut-body mirror test then forces into `/chunk/cut`.
|
||||
Store Close permanently closes attachment admission and captures hooks under captureMu, releases it, then aborts/joins the layer before closing storage. Every Close caller shares completion/result. Recover/reset acquire a window-admission lease and join owners before lower store locks; hook snapshot recheck includes racing first attachment. BASE begin/complete drain the whole cut through capMu. Resume is excluded by BaseInstalling state, not by capMu. A completed install handle's ApplyInstallEntry uses the same pre-publication hook as ordinary ApplyEntry.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> OPEN: Sync H and fix D under barrier
|
||||
OPEN --> CLOSED: every candidate staged or copied
|
||||
OPEN --> ABORTED: save/read failure, cancel, observed fence, destructive transition
|
||||
CLOSED --> Drain: no new claims
|
||||
ABORTED --> Drain: wake waiters, discard late results
|
||||
Drain --> Cleanup: all real owner/reader references returned
|
||||
Cleanup --> Upload: CLOSED only, immutable output owns bytes
|
||||
Cleanup --> Retry: ABORTED, merge all candidates back
|
||||
```
|
||||
|
||||
**Statistics.** `barrierPauseNs` covers Sync and window installation; native `barrierCopyChunks` is zero. `copyNs` covers outside-barrier materialization/drain. `cowSavedChunks` counts successful saves; `cowSaveNs` and `cowWaitNs` sum per-owner/per-wait elapsed time and are not wall-clock pause. These fields mirror into the actual cut response. Upload sizes and remote GC roots are unchanged.
|
||||
|
||||
**Model and tests.** The existing S4c r2 `CutCOW2` verdict and limits are bound in the [spec correspondence](../spec/README.md#cut-window-implementation-correspondence). One-copier whole-chunk modelling does not certify actual writer ownership, batches or Close/attach. `TestCutCOWV3_*` exercises real native mutation, abort, spill, recovery and close callers; earlier ACTIVE staging/image/intent/CAS controls remain. See [the implementation lock graph and mount rehearsal](cut-cow-validation.md).
|
||||
|
||||
## 6. Snapshots, forks, retention, GC, volume delete
|
||||
|
||||
@@ -183,7 +197,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
2. **Run GC with `--apply`.** The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates.
|
||||
3. **Volume vacuum in SeaweedFS.** GC deletes the needle; SeaweedFS returns the disk space when it vacuums that volume. Until then the bytes stay on the volume servers.
|
||||
- **Why a reachability mark and not reference counts.** Chunks and segments are shared by snapshots and forks of any number of volumes. A reference count kept in filer entries and changed by several hosts can be lost or applied twice by a crash or an unknown outcome; a lost increment would delete live data. The mark recomputes reachability from the roots on every pass, and the two-mark grace covers writers that are about to publish keys they already uploaded. The cost is delay: space comes back hours after a delete, not at once.
|
||||
- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting → purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again.
|
||||
- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting â†' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again.
|
||||
|
||||
HEAD states:
|
||||
|
||||
@@ -225,7 +239,7 @@ The attempt path is never removed, so a late create can never land after a delet
|
||||
|
||||
**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply).
|
||||
|
||||
**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS → revoke → the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation → blockmaster checks the detached HEAD and the matching acknowledgement → new epoch → the new host claims HEAD.
|
||||
**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS â†' revoke â†' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation â†' blockmaster checks the detached HEAD and the matching acknowledgement â†' new epoch â†' the new host claims HEAD.
|
||||
|
||||
**FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost.
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# Cut-window validation and mount rehearsal
|
||||
|
||||
The native v3 cut fixes H, candidate versions and a window under captureMu,
|
||||
then copies with bounded workers outside it. It preserves whole chunks, upload
|
||||
intents, manifest/CAS behavior and the local durability contract. The legacy
|
||||
engine retained only by test constructors still uses the older barrier cut.
|
||||
|
||||
## Lock and lifetime graph
|
||||
|
||||
```text
|
||||
BASE begin/complete: installMu X -> capMu -> captureMu -> lifecycleMu
|
||||
-> syncMu/store.mu -> descMu -> fileSyncMu
|
||||
completed handle write: installMu R -> captureMu R -> COW claim/release
|
||||
-> validated Read -> release reference
|
||||
-> lifecycleMu/admission/store.mu -> WAL/dirty map
|
||||
cut: capMu -> captureMu X (Sync, H/D, window); release captureMu -> copy
|
||||
claim/finish: layer.cowMu -> window.mu -> entry.mu; release before all I/O
|
||||
Close: captureMu X (permanent attach shutdown + stable hook snapshot); RELEASE
|
||||
-> layer abort + actual reference/waitgroup join -> lifecycleMu X
|
||||
Recover/reset: admission lease + abort/join, without lower store locks
|
||||
-> captureMu (hook snapshot recheck) -> existing lower locks
|
||||
```
|
||||
|
||||
Only short state transitions hold window/entry locks. No read, file create,
|
||||
spill read/write, wait, callback into the store or reference join holds them.
|
||||
A saver that aborts releases its own reference before any join. A terminal
|
||||
notification wakes waiters immediately; late I/O cannot publish a saved result.
|
||||
The active-window fast path is an atomic pointer load. With no window there
|
||||
is no chunk lock, allocation or side I/O.
|
||||
|
||||
Recover/reset keep their lease until their lower locks have been released;
|
||||
first-attach hook snapshots are retried under captureMu. BASE resume is
|
||||
excluded by BaseInstalling, not by a nonexistent capMu drain. Close atomically
|
||||
shuts attachment admission with its hook snapshot and all callers share the
|
||||
same completed shutdown result.
|
||||
|
||||
## Space and measurements
|
||||
|
||||
The 64 MiB budget covers retained in-memory saved payload only, not immutable
|
||||
upload buffers or transient owner reads. Spill offsets are compact candidate
|
||||
slots, checked against MaxInt64 before installation. Spill files are per cut,
|
||||
not fsynced or replayed, and are removed only after terminal plus zero actual
|
||||
references. A later exclusively locked RW open removes regular files with
|
||||
this volume's reserved `.cut-cow-` prefix; other prefixes, directories and
|
||||
symlinks are left alone. Cleanup failure fails the cut diagnostically, without
|
||||
changing any guest write outcome.
|
||||
|
||||
`barrierPauseNs` includes Sync/window setup, not chunk reads. `copyNs` is the
|
||||
outside-barrier copy and drain. Native `barrierCopyChunks`/`barrierOverBound`
|
||||
are zero; the configured threshold still bounds staging, not a hard COW-copy
|
||||
limit. `cowSavedChunks`, `cowSaveNs`, `cowWaitNs` are mirrored into the cut
|
||||
body. Save/wait times sum concurrent owners and must not be added to interpret
|
||||
a wall-clock pause. `cut_aborted` is retryable (503); a wrapped ordinary fence,
|
||||
shutdown or authority cause retains its existing classification.
|
||||
|
||||
## Real-mount rehearsal (planned, not executed)
|
||||
|
||||
This is a rehearsal note, not a lab packet or permission to run a mount. The
|
||||
existing frozen M5 ublk/NVMe packet and its host/volume allocation remain the
|
||||
starting point. Freeze the reviewed build SHA, weed SHA, map geometry,
|
||||
UploadConcurrency and frontend options in that packet before execution.
|
||||
Use only the assigned disposable volume, never a production/user filesystem.
|
||||
|
||||
1. Rebuild the existing blockvolume/sw-block binaries at the reviewed SHA and
|
||||
replay the unchanged M5 mount/setup. Record the device, filesystem and
|
||||
status URL. Verify the frontend reads/writes the expected v3 volume.
|
||||
2. Populate 8 then 64 distinct 4 MiB chunks with deterministic patterns and
|
||||
fsync. Capture a baseline HEAD and preserve its manifest/hash receipts.
|
||||
3. On the mounted file, run the existing 4K random-write/fsync workload at
|
||||
QD1 and QD8 while issuing cuts through the real route:
|
||||
|
||||
```sh
|
||||
sw-block ops chunk cut --volume "$VOLUME_ID" \
|
||||
--status-addr "$STATUS_URL" --timeout 2m
|
||||
```
|
||||
|
||||
Record fio JSON, all cut JSON, frontend durability-stage histograms,
|
||||
writer p50/p99/max, barrier/copy/total times, upload bytes, save/wait counts,
|
||||
RSS and spill bytes. Compare interleaved parent/candidate runs with identical
|
||||
setup. Backend proxy timings are not guest/mount results.
|
||||
4. Read back literal acknowledged patterns after the concurrent run. Validate
|
||||
each HEAD against the write-log prefix at its returned H, then make another
|
||||
cut and restore it on the packet's second host; verify the complete image.
|
||||
5. Repeat Close/cancel during a long cut and an abrupt process stop while a
|
||||
side file exists. Reopen the local v3 image, verify acknowledged data, then
|
||||
cut and restore again. Side data must not be imported; HEAD can only be
|
||||
either the last complete CAS or a complete newer CAS, never a partial image.
|
||||
6. Stop/join workloads before the packet's normal unmount/cleanup. Preserve
|
||||
receipts and report actual overhead/stalls; do not claim COW reduces upload
|
||||
volume. Save failure must abort the cut while ordinary writes keep working.
|
||||
|
||||
Deterministic native tests exercise held saving, saved-file and live-copy
|
||||
owners, first attach vs Close, hook-snapshot races in Recover/reset, overlapping
|
||||
public batches, cancellation and observed fencing. They complement the
|
||||
bounded one-copier/whole-chunk S4c r2 verdict; they are not a substitute for the
|
||||
future real-mount run.
|
||||
|
||||
## Caller closure
|
||||
|
||||
| Caller/path | COW admission or exclusion | Control |
|
||||
|---|---|---|
|
||||
| Write, WriteBatch | after immutable argument checks and captureMu R; before lifecycle/admission/store publication | MutationCompletesWhileEarlierChunkCopyIsHeld (including a checkpointed post-H rewrite); OverlappingRealBatchesPreserveCut; InvalidInputsDoNotSaveOrAbortWindow |
|
||||
| ordinary ApplyEntry, completed handle ApplyInstallEntry | actual applyEntryV3 hook; completed handle's existing install admission stays outside it | MutationCompletesWhileEarlierChunkCopyIsHeld / ApplyEntry and ApplyInstallEntry |
|
||||
| pending/saving/copying collisions | one owner, wait on per-entry notification or terminal | CopyingChunkWaitsButPendingChunkSaves; TwoWritersOneSaveAndCloseJoinsSavedReader |
|
||||
| Cut, Capture, Detach, MakeRemoteDurable | same capMu/captureLocked path; immutable buffers after terminal/drain | existing C1/C3 image, staged reuse, Detach, MakeRemoteDurable and unknown-CAS/intent controls remain native |
|
||||
| Recover and reset | beforeDestructive lease, abort/join, capture barrier snapshot recheck | RecoveryAndCloseDrainSavingOwner; DestructiveSnapshotRetriesFirstAttachment |
|
||||
| Store Close / standalone layer.Close / second Close | permanent attachment gate + stable snapshot; terminal and actual owner/waitgroup drain | CloseCannotMissFirstAttachment; CloseSnapshotRejectsFirstAttachAndSharesCompletion; CloseJoinsHeldLiveCopy; RecoveryAndCloseDrainSavingOwner; TwoWritersOneSaveAndCloseJoinsSavedReader |
|
||||
| BASE begin/complete | existing installMu/capMu transition drains whole cut | existing attached BASE lifecycle/capture-generation controls |
|
||||
| BASE WriteBase / resume | installing state excludes a cut; resume is not capMu-drained | existing install-handle state/owner controls; native COW hook does not weaken them |
|
||||
| SeedChunkFrontier / WriteExtentDirect | attached seed refused; public v3 direct write refused | existing seed/direct caller controls |
|
||||
| Flusher / lazy fill | materialize existing visible bytes; no new read-visible mutation, no new hook | SaverUsesValidatedWALBatchAndLazyHEAD (WAL-only and flushed batch); existing PostReadMissRechecksWALFormat |
|
||||
| Temporary v2 fixture mutation paths | remain behind the full-copy barrier; no production C11 file | existing legacy fixture controls and production reachability guard |
|
||||
|
||||
Test names above have prefix `TestCutCOWV3_` unless an existing control is named.
|
||||
The abrupt-process control `ProcessCrashDropsSideAndRestoresSyncedImage` exits
|
||||
with an OPEN spill and no cleanup, then the parent reopens, validates the
|
||||
synced post-H bytes, observes the actual old HEAD and publishes the next image.
|
||||
`SpillIsEphemeralAndCleanupIsPrefixScoped` additionally covers ignored corrupt
|
||||
side payloads and preservation of other-prefix files/directories.
|
||||
|
||||
## Backend proxy result
|
||||
|
||||
The source-identical `BenchmarkCutCOWProxy` was run parent/candidate interleaved
|
||||
three times, each row with three cuts, on tp04 (i7-13700, Go reports GOMAXPROCS
|
||||
24; actual work stays under the runner's quota). Parent is main d0e3895a plus
|
||||
only the benchmark, ref 3faecbd4. Candidate timing head is ee6c6f3b. Staging is
|
||||
disabled, copy/upload concurrency is 8, chunks are 4 MiB and each released
|
||||
writer performs one 4K write+Sync per cut. Writers start at the real Sync/H
|
||||
handshake. A memory ChunkRemote keeps identical upload work in both arms;
|
||||
this is file-backed storage with an in-process remote, not network, guest or
|
||||
mount performance. No throughput/fsync guarantee is inferred from it.
|
||||
|
||||
The table reports medians of the three per-run values, in milliseconds. Each
|
||||
per-run p99 has only 3 samples at QD1 or 24 at QD8; these are sample percentiles,
|
||||
not estimates of a production tail. The full raw stage/timing rows are kept
|
||||
with the review receipts. Later source changes are fence-observation ordering,
|
||||
cleanup-error reporting and additional caller controls; they are not timed by
|
||||
these earlier-head measurements.
|
||||
|
||||
| Geometry / writers | Barrier ms parent -> COW | Writer p50 ms parent -> COW | Writer p99 ms parent -> COW | Total cut ms parent -> COW |
|
||||
|---|---:|---:|---:|---:|
|
||||
| chunks8/QD1 | 41.15 -> 0.54 | 41.72 -> 8.38 | 44.79 -> 8.62 | 74.12 -> 45.44 |
|
||||
| chunks8/QD8 | 40.46 -> 0.47 | 43.24 -> 9.71 | 43.27 -> 12.48 | 71.84 -> 43.63 |
|
||||
| chunks64/QD1 | 312.68 -> 0.50 | 324.78 -> 8.35 | 346.51 -> 8.61 | 554.93 -> 356.54 |
|
||||
| chunks64/QD8 | 308.86 -> 0.54 | 309.59 -> 15.29 | 347.69 -> 20.42 | 531.13 -> 346.85 |
|
||||
|
||||
Each 8-chunk cut uploads 32 MiB and each 64-chunk cut uploads 256 MiB in both
|
||||
arms. COW reduces the barrier/copy stall and parallelizes materialization;
|
||||
it does not reduce remote upload volume. The native mutation control reports
|
||||
one real save (and positive save time), zero barrier copies, and verifies
|
||||
post-H map dirt even after the new bytes have checkpointed. No mounted result
|
||||
is claimed; use the rehearsal above for that separate measurement.
|
||||
@@ -55,7 +55,7 @@ stateDiagram-v2
|
||||
|---|---|---|---|---|
|
||||
| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` |
|
||||
| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` |
|
||||
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` |
|
||||
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` |
|
||||
| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` |
|
||||
| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001` |
|
||||
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` |
|
||||
@@ -187,9 +187,13 @@ stateDiagram-v2
|
||||
Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid
|
||||
Admit --> Stage: earlier unknown CAS settled
|
||||
Stage --> Quiesce: at most 3 pre-copy rounds
|
||||
Quiesce --> Copy: barrier held, Sync returns H
|
||||
Quiesce --> OpenWindow: Sync H and D fixed under barrier
|
||||
OpenWindow --> Copy: release barrier
|
||||
Copy --> Closed: all candidates done
|
||||
Copy --> Aborted: error, cancellation, observed fence, recovery or close
|
||||
Aborted --> Refused: drain owners, cleanup, merge candidates
|
||||
Copy --> Refused: H below HEAD RemoteLSN
|
||||
Copy --> Upload: intent durable first
|
||||
Closed --> Upload: drain and cleanup; intent durable first
|
||||
Upload --> Manifest
|
||||
Manifest --> Readmit
|
||||
Readmit --> Fenced: superseding HEAD
|
||||
@@ -205,9 +209,11 @@ stateDiagram-v2
|
||||
|---|---|---|---|
|
||||
| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-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 | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001` |
|
||||
| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `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-INTENT-FIRST-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` |
|
||||
| Copy | every candidate chunk (WAL chunks above the checkpoint, the dirty set, or all chunks in hash mode) is read into buffers; a staged copy is reused only if unchanged since staging | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` |
|
||||
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; 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` |
|
||||
| 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 a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` |
|
||||
| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` |
|
||||
@@ -389,9 +395,9 @@ Notes:
|
||||
|---|---|---|---|---|---|---|
|
||||
| `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-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again under the barrier. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-RECOVER-BARRIER-001` | `Recover` holds the capture barrier, so no record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover` | `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `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-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-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 |
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
------------------------------- MODULE CutCOW2 -------------------------------
|
||||
(***************************************************************************)
|
||||
(* S4c r2: copy-before-write in the cut window, with the save as I/O and *)
|
||||
(* an abort. Proposed design, not implemented (2026-11-18). *)
|
||||
(* *)
|
||||
(* As r1 (CutCOW): barrier vs COW; the barrier fixes H and D, then (COW) *)
|
||||
(* releases; a chunk copy is CopyStart + CopyFinish and a write to a chunk *)
|
||||
(* being copied waits. New in r2: *)
|
||||
(* - the writer's save is I/O too: SaveStart claims the chunk (state *)
|
||||
(* saving, it reads the at-H content), SaveFinish writes it to the side *)
|
||||
(* store. The write itself waits until its chunk is saved. The in- *)
|
||||
(* flight save lives in `pend`, outside the cut record, as real I/O *)
|
||||
(* outlives a cut record that someone else tears down. *)
|
||||
(* - an abort (save error, cancel, Close): AbortStart invalidates the cut *)
|
||||
(* and releases waiters; AbortFinish deletes the side store and ends *)
|
||||
(* the window only once no saving or copying owner is left (the join). *)
|
||||
(* Mut: *)
|
||||
(* noCopy a write in the window never saves *)
|
||||
(* noChunkLock a write proceeds while its chunk is being copied *)
|
||||
(* abortNoJoin AbortFinish does not wait for saving/copying owners: a *)
|
||||
(* save still in I/O completes into a side store that has *)
|
||||
(* already been deleted, i.e. into whatever window is next *)
|
||||
(***************************************************************************)
|
||||
EXTENDS Integers, FiniteSets, Sequences, TLC
|
||||
|
||||
CONSTANTS Chunks, MaxLSN, MaxCuts, MaxCrash, MaxAborts, Mode, Mut
|
||||
|
||||
NONE == -1
|
||||
Zero == [c \in Chunks |-> 0]
|
||||
NoSide == [c \in Chunks |-> NONE]
|
||||
Idle == [pc |-> "idle", H |-> 0, D |-> {}, copied |-> {}, copying |-> {}, saving |-> {}, buf |-> Zero]
|
||||
|
||||
VARIABLES hist, synced, vis, ext, side, pend, head, cut, dirty, cuts, crashes, aborts
|
||||
vars == <<hist, synced, vis, ext, side, pend, head, cut, dirty, cuts, crashes, aborts>>
|
||||
|
||||
VA(h, c, L) == LET ws == {i \in 1..L : i <= Len(h) /\ h[i] = c}
|
||||
IN IF ws = {} THEN 0 ELSE CHOOSE m \in ws : \A k \in ws : k <= m
|
||||
ValueAt(c, L) == VA(hist, c, L)
|
||||
WrittenAfter(h, L) == {h[i] : i \in {j \in (L + 1)..Len(h) : j >= 1}}
|
||||
|
||||
Init == /\ hist = <<>> /\ synced = 0 /\ vis = Zero /\ ext = Zero /\ side = NoSide /\ pend = NoSide
|
||||
/\ head = [lsn |-> 0, img |-> Zero] /\ cut = Idle /\ dirty = {}
|
||||
/\ cuts = 0 /\ crashes = 0 /\ aborts = 0
|
||||
|
||||
Open == Mode = "cow" /\ cut.pc = "copying" \* a live COW window (not aborting)
|
||||
\* c still needs a save before a write to it may publish
|
||||
NeedSave(c) == Open /\ c \in cut.D \ (cut.copied \cup cut.copying \cup cut.saving) /\ side[c] = NONE
|
||||
|
||||
Blocked(c) == \/ Mode = "barrier" /\ cut.pc \in {"barrier", "copying"}
|
||||
\/ Mode = "cow" /\ cut.pc = "barrier"
|
||||
\/ Open /\ c \in cut.copying /\ Mut # "noChunkLock" \* wait for the copier
|
||||
\/ Open /\ c \in cut.saving \* wait for the saving owner
|
||||
\/ NeedSave(c) /\ Mut # "noCopy" \* a save must come first
|
||||
|
||||
Write(c) ==
|
||||
/\ Len(hist) < MaxLSN /\ ~Blocked(c)
|
||||
/\ LET n == Len(hist) + 1 IN
|
||||
/\ hist' = Append(hist, c)
|
||||
/\ vis' = [vis EXCEPT ![c] = n]
|
||||
/\ dirty' = dirty \cup {c}
|
||||
/\ UNCHANGED <<synced, ext, side, pend, head, cut, cuts, crashes, aborts>>
|
||||
|
||||
\* a writer becomes the owner of a pending candidate and reads its current (= at-H) content
|
||||
SaveStart(c) == /\ NeedSave(c) /\ Mut # "noCopy" /\ Len(hist) < MaxLSN /\ pend[c] = NONE
|
||||
/\ cut' = [cut EXCEPT !.saving = @ \cup {c}]
|
||||
/\ pend' = [pend EXCEPT ![c] = vis[c]]
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, side, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
\* the save's I/O completes: into the live window's side store; discarded if the window is aborting;
|
||||
\* an orphan (only reachable with abortNoJoin) writes into whatever side store exists now
|
||||
SaveFinish(c) == /\ pend[c] # NONE
|
||||
/\ side' = IF cut.pc = "aborting" THEN side ELSE [side EXCEPT ![c] = pend[c]]
|
||||
/\ cut' = [cut EXCEPT !.saving = @ \ {c}]
|
||||
/\ pend' = [pend EXCEPT ![c] = NONE]
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
Sync == /\ synced < Len(hist) /\ synced' = Len(hist)
|
||||
/\ UNCHANGED <<hist, vis, ext, side, pend, head, cut, dirty, cuts, crashes, aborts>>
|
||||
|
||||
Flush(c) == /\ ext[c] # vis[c] /\ ext' = [ext EXCEPT ![c] = vis[c]]
|
||||
/\ UNCHANGED <<hist, synced, vis, side, pend, head, cut, dirty, cuts, crashes, aborts>>
|
||||
|
||||
CutBegin == /\ cut.pc = "idle" /\ cuts < MaxCuts /\ Len(hist) > head.lsn
|
||||
/\ synced' = Len(hist)
|
||||
/\ cut' = [Idle EXCEPT !.pc = "barrier", !.H = Len(hist)]
|
||||
/\ UNCHANGED <<hist, vis, ext, side, pend, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
FixD == /\ cut.pc = "barrier"
|
||||
/\ cut' = [cut EXCEPT !.pc = "copying", !.D = dirty]
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, side, pend, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
CopyStart(c) == /\ cut.pc = "copying" /\ c \in cut.D \ (cut.copied \cup cut.copying \cup cut.saving)
|
||||
/\ cut' = [cut EXCEPT !.copying = @ \cup {c}]
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, side, pend, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
CopyFinish(c) == /\ c \in cut.copying
|
||||
/\ cut' = IF cut.pc = "aborting" THEN [cut EXCEPT !.copying = @ \ {c}]
|
||||
ELSE [cut EXCEPT !.copying = @ \ {c}, !.copied = @ \cup {c},
|
||||
!.buf[c] = IF side[c] # NONE THEN side[c] ELSE vis[c]]
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, side, pend, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
CutCAS == /\ cut.pc = "copying" /\ cut.copied = cut.D /\ cut.copying = {} /\ cut.saving = {}
|
||||
/\ head' = [lsn |-> cut.H, img |-> [c \in Chunks |-> IF c \in cut.D THEN cut.buf[c] ELSE head.img[c]]]
|
||||
/\ dirty' = WrittenAfter(hist, cut.H)
|
||||
/\ side' = NoSide /\ cut' = Idle /\ cuts' = cuts + 1
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, pend, crashes, aborts>>
|
||||
|
||||
\* abort: invalidate and release waiters at once; the dirty set is kept (no finishCut)
|
||||
AbortStart == /\ cut.pc = "copying" /\ aborts < MaxAborts
|
||||
/\ cut' = [cut EXCEPT !.pc = "aborting"]
|
||||
/\ aborts' = aborts + 1
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, side, pend, head, dirty, cuts, crashes>>
|
||||
\* the join: delete the side store and end the window once no owner is in I/O (abortNoJoin: at once)
|
||||
AbortFinish == /\ cut.pc = "aborting"
|
||||
/\ Mut = "abortNoJoin" \/ (cut.saving = {} /\ cut.copying = {})
|
||||
/\ side' = NoSide /\ cut' = Idle
|
||||
/\ UNCHANGED <<hist, synced, vis, ext, pend, head, dirty, cuts, crashes, aborts>>
|
||||
|
||||
Crash == /\ crashes < MaxCrash
|
||||
/\ LET h == SubSeq(hist, 1, synced)
|
||||
img == [c \in Chunks |-> VA(h, c, Len(h))]
|
||||
IN /\ hist' = h /\ vis' = img /\ ext' = img /\ dirty' = WrittenAfter(h, head.lsn)
|
||||
/\ side' = NoSide /\ pend' = NoSide /\ cut' = Idle
|
||||
/\ crashes' = crashes + 1
|
||||
/\ UNCHANGED <<synced, head, cuts, aborts>>
|
||||
|
||||
Next == \/ \E c \in Chunks : Write(c) \/ SaveStart(c) \/ SaveFinish(c) \/ Flush(c) \/ CopyStart(c) \/ CopyFinish(c)
|
||||
\/ Sync \/ CutBegin \/ FixD \/ CutCAS \/ AbortStart \/ AbortFinish \/ Crash
|
||||
Spec == Init /\ [][Next]_vars
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
HeadImage == \A c \in Chunks : head.img[c] = ValueAt(c, head.lsn)
|
||||
BufFrozen == \A c \in cut.copied : cut.buf[c] = ValueAt(c, cut.H)
|
||||
SideFrozen == cut.pc = "copying" => \A c \in Chunks : side[c] # NONE => side[c] = ValueAt(c, cut.H)
|
||||
SideOnlyInCut == cut.pc = "idle" => side = NoSide
|
||||
ReadsNewest == \A c \in Chunks : vis[c] = ValueAt(c, Len(hist))
|
||||
HeadLeSynced == head.lsn <= synced /\ head.lsn <= Len(hist)
|
||||
TypeOK == /\ cut.pc \in {"idle", "barrier", "copying", "aborting"}
|
||||
/\ cut.copied \subseteq cut.D /\ cut.copying \subseteq cut.D /\ cut.saving \subseteq cut.D
|
||||
/\ cut.copied \cap cut.copying = {} /\ cut.copying \cap cut.saving = {}
|
||||
|
||||
\* Witnesses (expected VIOLATED = reachable):
|
||||
W_AbortWhileSaving == ~(cut.pc = "aborting" /\ cut.saving # {})
|
||||
W_SaveUsedByCopier == ~(Open /\ \E c \in cut.copied : side[c] # NONE)
|
||||
W_CASAfterAbort == ~(aborts >= 1 /\ cuts >= 1)
|
||||
=============================================================================
|
||||
@@ -92,7 +92,8 @@ Two kinds of config are **expected to violate**:
|
||||
| `WALReplica.tla` | `cfg/S3_rep_*` | |
|
||||
| `CutCapture.tla` | `cfg/S4_*` | |
|
||||
| `CutPipeline.tla` | `cfg/S4b_*` | |
|
||||
| `CutCOW.tla` | `cfg/S4c_*` | proposed design (copy-before-write), not implemented |
|
||||
| `CutCOW.tla` | `cfg/S4c_*` | earlier copy-window abstraction |
|
||||
| `CutCOW2.tla` | `cfg/S4r2_*` | selected native COW: save I/O and abort/drain |
|
||||
| `ControlPlane.tla` | `cfg/S5_*` | |
|
||||
| `ReplicationFailover.tla` | `cfg/S6_*` | design-level |
|
||||
| `RetentionGCTiming.tla` | `cfg/S9_*` | |
|
||||
@@ -224,3 +225,25 @@ TLC runs of these specs; comment-only edits were made since.
|
||||
The public selector now reaches the mapped impl3 paths in `walstore_v3.go`, `descriptor_v3.go`, `wal_io_v3.go` and `walstore_map_checkpoint_v3.go`. This is activation of the previously reviewed format contract, not a new abstract transition. Its canonical signed design is r17.4 (`e2a5304ef8fdc29f7e109883b8664a5c93d37a559e7b93e1d24964cb09cb7824`), with the composed external S3/BASE/install/map TLC receipts referenced by that design. The in-repository `WALRecovery.tla` remains an abstraction and is not a proof of every physical nonce/cursor/map/dual-slot rule. Pending external bounded runs remain pending; activation tests and source correspondence do not turn them into exhaustive proof.
|
||||
|
||||
Native Go controls and the temporary frozen-v2 fixture disposition are listed in [the activation inventory](../design/format-v3-legacy-test-inventory.md). Old-codec tests are preserved, and both default and tagged migration/caller suites are validation gates. No model equation is changed by the selector wiring; a new counterexample still requires an amendment before affected integration.
|
||||
|
||||
## Cut-window implementation correspondence
|
||||
|
||||
The mapped v3 cut now uses `chunk_cut_cow.go`. `CutCOW2.tla` is the unchanged
|
||||
S4c r2 model (SHA-256 `0b9bc89a9aed6c42dda6b1d23ba8515c406b1c2cb265cd83e78122238df6bcca`);
|
||||
its header records its pre-implementation status at the time of the run.
|
||||
The existing bounded verdict is not a new run: Chunks={a,b,c}, MaxLSN=6,
|
||||
MaxCuts=2, MaxCrash=1, MaxAborts=1. `S4r2_cow_safe` checked seven invariants,
|
||||
252,733,280 states, depth 36; barrier checked 27,790,736, depth 31.
|
||||
`abortNoJoin` violates SideOnlyInCut at 31,835 states; `noChunkLock` and
|
||||
`noCopy` violate BufFrozen at 6,982 and 7,484. The three witness configs
|
||||
reach AbortWhileSaving (1,682), SaveUsedByCopier (28,250), CASAfterAbort
|
||||
(614,292); their exit 12 is expected reachability, not a safe-config pass.
|
||||
|
||||
SaveStart/SaveFinish correspond to the saving owner's validated read and
|
||||
side-store publication. AbortStart is terminal invalidation/wakeup; AbortFinish
|
||||
is reference drain followed by one cleanup. The model has one copier and
|
||||
whole-chunk writes. Actual multi-writer/batch ownership, first-attach/Close,
|
||||
Recover/reset snapshot recheck and saved-file readers are covered by the
|
||||
native `TestCutCOWV3_*` caller controls, not claimed as model proofs.
|
||||
The earlier thirteen-spec parse statement above predates this imported model;
|
||||
no new independent TLC/parse or cloud run is claimed here.
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_barrier_safe (CutCOW2, S4c r2: save as I/O + abort): Mode=barrier Mut=none
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "barrier"
|
||||
Mut = "none"
|
||||
INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_cow_safe (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "none"
|
||||
INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_red_abortNoJoin (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=abortNoJoin
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "abortNoJoin"
|
||||
INVARIANTS HeadImage BufFrozen SideOnlyInCut
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_red_noChunkLock (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=noChunkLock
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "noChunkLock"
|
||||
INVARIANTS HeadImage BufFrozen
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_red_noCopy (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=noCopy
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "noCopy"
|
||||
INVARIANTS HeadImage BufFrozen
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_wit_AbortWhileSaving (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "none"
|
||||
INVARIANTS W_AbortWhileSaving
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_wit_CASAfterAbort (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "none"
|
||||
INVARIANTS W_CASAfterAbort
|
||||
@@ -0,0 +1,11 @@
|
||||
\* S4r2_wit_SaveUsedByCopier (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
Chunks = {"a", "b", "c"}
|
||||
MaxLSN = 6
|
||||
MaxCuts = 2
|
||||
MaxCrash = 1
|
||||
MaxAborts = 1
|
||||
Mode = "cow"
|
||||
Mut = "none"
|
||||
INVARIANTS W_SaveUsedByCopier
|
||||
Reference in new issue
Block a user