Merge pull request #911 from seaweedfs/feat/b1-candidate-bitmap

storage: a cut's guest pause does O(1) work; candidates by change
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-01 23:32:33 -08:00
commit 3cbb7cf2eb
16 files changed
+1152 -137

No files matched your search

+20 -14
View File
@@ -61,13 +61,16 @@ type ChunkCutResponse struct {
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
// step); every duration is in nanoseconds.
type ChunkCutStatsBody struct {
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
CandidateNs int64 `json:"candidateNs"`
WindowSetupNs int64 `json:"windowSetupNs"`
PublishPrepareNs int64 `json:"publishPrepareNs"`
ManifestNs int64 `json:"manifestNs"`
CommitStateNs int64 `json:"commitStateNs"`
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched
PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause
PauseCandidateOps int64 `json:"pauseCandidateOps"` // per-candidate operations done while the guest was paused
CandidateNs int64 `json:"candidateNs"`
WindowSetupNs int64 `json:"windowSetupNs"`
PublishPrepareNs int64 `json:"publishPrepareNs"`
ManifestNs int64 `json:"manifestNs"`
CommitStateNs int64 `json:"commitStateNs"`
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
PayloadNs int64 `json:"payloadNs"`
COWWALReadAttempts uint64 `json:"cowWALReadAttempts"`
@@ -111,13 +114,16 @@ type ChunkCutStatsBody struct {
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
return ChunkCutStatsBody{
SyncPhases: s.SyncPhases,
CandidateNs: s.CandidateNs,
WindowSetupNs: s.WindowSetupNs,
PublishPrepareNs: s.PublishPrepareNs,
ManifestNs: s.ManifestNs,
CommitStateNs: s.CommitStateNs,
NonPayloadCopyNs: s.NonPayloadCopyNs,
SyncPhases: s.SyncPhases,
CandidateVisits: s.CandidateVisits,
PreSyncNs: s.PreSyncNs,
PauseCandidateOps: s.PauseCandidateOps,
CandidateNs: s.CandidateNs,
WindowSetupNs: s.WindowSetupNs,
PublishPrepareNs: s.PublishPrepareNs,
ManifestNs: s.ManifestNs,
CommitStateNs: s.CommitStateNs,
NonPayloadCopyNs: s.NonPayloadCopyNs,
PayloadNs: s.PayloadNs,
COWWALReadAttempts: s.COWWALReadAttempts,
@@ -656,6 +656,9 @@ func (s *WALStore) markMapUnknownV3(lba uint64) {
}
e.LSN = max(e.LSN, birth)
v.mapEntries.set(index, e)
if h := s.chunk.Load(); h != nil {
h.sink.OnMapEntryChange(uint64(index))
}
}
// InstalledBaseLSN reports a completed local BASE obligation, not a normal
@@ -0,0 +1,372 @@
package storage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"path/filepath"
"testing"
"time"
)
// The guest pause does O(1) work: a cut's first barrier after writes to many
// chunks does no per-candidate operation between the barrier's lock and its
// release (counted, not timed), at 32 blocks and at the 1 TiB shape with
// 256 changed chunks. The candidates are judged, versioned and based after
// the pause, under the copy window.
func TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause(t *testing.T) {
t.Run("small", func(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks == 0 || r.Stats.PauseCandidateOps != 0 {
t.Fatalf("first cut over %d candidates: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, r.Stats.PauseCandidateOps)
}
})
t.Run("one-TiB-shape", func(t *testing.T) {
const n, changed = 262144, 256
s, l := freshShape(t, n)
for i := 0; i < changed; i++ {
if _, err := s.Write(uint32(i*997%n), []byte(fmt.Sprintf("%-512d", i))); err != nil {
t.Fatal(err)
}
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks < changed || r.Stats.PauseCandidateOps != 0 {
t.Fatalf("first cut over %d candidates of %d chunks: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, n, r.Stats.PauseCandidateOps)
}
})
}
// A layer's first cut finds its touched sets ready: the barrier only swaps
// them; no set is allocated in the pause (size-dependent work).
func TestAColdFirstCutAllocatesNoSetInThePause(t *testing.T) {
const n = 262144
s, l := freshShape(t, n)
if _, err := s.Write(3, []byte(fmt.Sprintf("%-512s", "cold"))); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("a layer's first cut over %d chunks did %d size-dependent operations in the pause, want 0", n, r.Stats.PauseCandidateOps)
}
}
// A recovery that lands between a cut's pre-barrier work and its barrier
// moves every clean fill's version: the cut still judges those fills (their
// proofs are gone), after the pause, and the pause does no per-fill work.
func TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause(t *testing.T) {
_, l, _ := filledFreshVolume(t)
l.stMu.Lock()
fills := len(l.filledClean)
l.stMu.Unlock()
if fills == 0 {
t.Fatal("setup: no clean fills")
}
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() }
r, err := l.Cut(ctTimeout(t))
l.testBeforeBarrierLockHook = nil
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("a recovery just before the barrier cost %d per-fill operations in the pause, want 0", r.Stats.PauseCandidateOps)
}
if r.Stats.CandidateChunks < fills {
t.Fatalf("the cut after the recovery judged %d candidates, want all %d clean fills (their proofs are gone)", r.Stats.CandidateChunks, fills)
}
}
// A reader of the candidates (status, pre-copy, the shadow) running beside
// cuts and recoveries never charges its work to a cut's pause nor touches the
// capture's pause accounting: run with -race, the schedule (a reader that
// can consume a recovery's request while a cut enters its barrier) has no
// race, and every cut's pause does no per-candidate work.
func TestAReaderBesideCutsAndRecoveriesIsNotChargedToThePause(t *testing.T) {
_, l, _ := filledFreshVolume(t)
stop := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-stop:
return
default:
}
_ = l.captureCandidates() // the readers' path: peekTouched, resolveTouchFilled
}
}()
defer func() {
close(stop)
select {
case <-done:
case <-time.After(ctLocalBound):
t.Error("the reader did not stop")
}
}()
for i := 0; i < 20; i++ {
l.noteAllMutated() // a recovery the reader may consume first
if i%2 == 1 {
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } // or one just before the barrier
}
r, err := l.Cut(ctTimeout(t))
l.testBeforeBarrierLockHook = nil
if err != nil {
t.Fatal(err)
}
if r.Stats.PauseCandidateOps != 0 {
t.Fatalf("cut %d: %d per-candidate operations charged to the pause beside a reader", i, r.Stats.PauseCandidateOps)
}
}
}
// A fill whose fetch outlives a same-open recovery installs HEAD's bytes but
// no clean mark (the recovery moved the chunk's version), so the chunk is a
// candidate again, as the full scan says; the absent-to-present install
// touches it. (The package's candidate oracle checks the cut's barrier too.)
func TestAFillThatOutlivesARecoveryMakesItsChunkACandidate(t *testing.T) {
s, l, remote, _ := hydrationFixture(t, 2, 64)
// The engine's predicate is what is checked here. The chunk record names
// such a chunk HashPublished (the fill verified HEAD's hash), so the
// engine's conservative candidate is an extra to the record's shadow, as
// it was with the full scan: the shadow is off for this schedule.
l.shadow = nil
entered, release := holdGets(t, remote)
defer release()
read := make(chan error, 1)
go func() {
_, err := s.Read(0)
read <- err
}()
select {
case <-entered:
case <-time.After(ctLocalBound):
t.Fatal("the read miss never reached the remote")
}
if l.captureCandidates()[0] {
t.Fatal("setup: the absent chunk is already a candidate")
}
l.noteAllMutated() // a same-open recovery, while the fetch is held
release()
select {
case err := <-read:
if err != nil {
t.Fatal(err)
}
case <-time.After(ctLocalBound):
t.Fatal("the read did not complete")
}
l.stMu.Lock()
absent, marked := l.absent[0], l.filledClean[0] != (filledMark{})
l.stMu.Unlock()
if absent || marked {
t.Fatalf("setup: after the fill, absent=%v clean-marked=%v; want present without a mark", absent, marked)
}
if !l.captureCandidates()[0] {
t.Fatal("a chunk filled across a recovery, present without a clean mark, is not a candidate")
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
}
// freshShape attaches a lazy fresh-from-HEAD layer over n one-block chunks
// (512-byte blocks), every chunk named by HEAD and absent locally, as the
// SPACE test builds the 1 TiB shape (n = 262,144).
func freshShape(t *testing.T, n int) (*WALStore, *chunkLayerImpl) {
t.Helper()
const bs = 512
f := newFakeChunkRemote()
head := chunkHead{Epoch: 1, Holder: "seed", RemoteLSN: 10, Chunks: make(map[uint64]chunkRef, n)}
for i := 0; i < n; i++ {
data := make([]byte, bs)
binary.LittleEndian.PutUint64(data, uint64(i)+1)
key := fmt.Sprintf("seed/%d", i)
f.objs[key] = data
f.everStored[key] = true
head.Chunks[uint64(i)] = chunkRef{Key: key, SHA256: sha256.Sum256(data), Encoding: "full"}
}
f.mu.Lock()
f.installLocked(head)
f.mu.Unlock()
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), uint32(n), bs, WALStoreOptions{ChunkBlocks: 1})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { closeBounded(t, s) })
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "host-a", Bitmap: newFakeBitmap(), ReadMissTimeout: ctLocalBound, FreshFromHead: true}
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
// Publishing a write to an absent chunk of a fresh-from-HEAD layer makes
// the chunk record refuse its Commit (U/Commit), with or without the
// candidate set; that record question is apart from what these tests
// count, so the shadow is off for this shape.
l.shadow = nil
return s, l
}
// visitBound is the candidate step's allowance for a cut with changed chunks
// at n chunks: the changed chunks plus one summary word per 4,096 chunks,
// and a small constant.
func visitBound(changed, n int) int64 { return int64(changed + n/4096 + 16) }
// An idle cut's candidate step does work flat in S: at the 1 TiB shape it
// visits no more chunk indices than at 4,096 chunks (counted, not timed).
func TestIdleCutCandidateWorkIsFlatInS(t *testing.T) {
for _, n := range []int{4096, 262144} {
t.Run(fmt.Sprintf("chunks-%d", n), func(t *testing.T) {
s, l := freshShape(t, n)
if _, err := s.Write(0, make([]byte, 512)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if got, max := r.Stats.CandidateVisits, visitBound(0, n); got > max {
t.Fatalf("an idle cut over %d chunks visited %d chunk indices in its candidate step, want <= %d", n, got, max)
}
})
}
}
// A cut with one changed chunk at the 1 TiB shape scans no chunk map: its
// candidate step visits the changed chunk and the summary words only.
func TestOneChangedChunkCutVisitsNoFullScan(t *testing.T) {
const n = 262144
s, l := freshShape(t, n)
if _, err := s.Write(0, make([]byte, 512)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if _, err := s.Write(7*1, []byte(fmt.Sprintf("%-512s", "changed"))); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if got, max := r.Stats.CandidateVisits, visitBound(1, n); got > max {
t.Fatalf("a one-chunk cut over %d chunks visited %d chunk indices, want <= %d", n, got, max)
}
}
// The cut syncs the store before its barrier, outside the guest pause, so
// the pause's own sync has only what came after; the pre-sync's time is
// reported apart from the pause.
func TestCutSyncsBeforeItsBarrier(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
before := s.syncs.Load()
var atLock uint64
l.testBeforeBarrierLockHook = func() { atLock = s.syncs.Load() }
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if after := s.syncs.Load(); after <= atLock {
t.Fatalf("the counter missed the pause's own sync (%d then %d): the measure is wrong", atLock, after)
}
if atLock <= before {
t.Fatalf("no store sync between the cut's start and its barrier (sync count %d then %d): the pause syncs the whole fill", before, atLock)
}
}
// A cut whose commit outcome is unknown (and did not land) loses no chunk:
// its captured chunks, and a write made after it, are all published by the
// next cut, and no other chunk changes.
func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
w := newWriteLog()
for lba := uint32(0); lba < ctNumBlocks; lba++ {
w.write(t, s, lba, byte(lba+1))
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
base := f.imageOf(t, f.stats().head) // the remote's full image, any format
w.write(t, s, 0*ctChunkBlocks, 0xa0) // chunk 0
w.write(t, s, 2*ctChunkBlocks, 0xa2) // chunk 2
f.mu.Lock()
f.casModes = []fakeCASMode{casUnknownNotApplied}
f.mu.Unlock()
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("the injected cut answered %v, want its outcome unknown", err)
}
w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
var err error
var last chunkCutResult
for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish
if last, err = l.Cut(ctTimeout(t)); err == nil && !last.Noop {
break
}
}
if err != nil {
t.Fatal(err)
}
img := f.imageOf(t, f.stats().head)
chunkBytes := ctChunkBlocks * ctBlockSize
for idx := 0; idx < ctNumBlocks/ctChunkBlocks; idx++ {
at := idx * chunkBytes
changed := !bytes.Equal(img[at:at+chunkBytes], base[at:at+chunkBytes])
want := idx == 0 || idx == 2 || idx == 5
if changed != want {
t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want)
}
}
}
// The candidate set's OR keeps the summary, so a set ORed back is listed in
// full; each lists exactly the set bits.
func TestCandidateSetOrBackKeepsTheSummary(t *testing.T) {
const n = 64 * 64 * 3
taken, live := newCandidateSet(n), newCandidateSet(n)
want := []uint64{1, 64*64 + 5, n - 1}
for _, c := range want {
taken.set(c)
}
live.set(7)
live.or(taken)
var got []uint64
live.each(func(c uint64) { got = append(got, c) })
exp := []uint64{1, 7, 64*64 + 5, n - 1}
if fmt.Sprint(got) != fmt.Sprint(exp) || live.Len() != len(exp) {
t.Fatalf("after OR-back the set lists %v (len %d), want %v", got, live.Len(), exp)
}
live.clear()
got = nil
live.each(func(c uint64) { got = append(got, c) })
if len(got) != 0 || live.Len() != 0 {
t.Fatalf("a cleared set lists %v", got)
}
}
+102 -29
View File
@@ -106,6 +106,10 @@ type cutCOWEntry struct {
// were captured: their image at H is HEAD's, filled by the copier from the
// cut's base HEAD after it released the entry (never under a guest write).
missing []uint64
// version is the chunk's mutation version when a guest write's save
// claimed the entry: the version of the bytes it saves (the write's own
// version move comes after its mutation).
version uint64
}
type cutCOWWindow struct {
layer *chunkLayerImpl
@@ -137,6 +141,19 @@ type cutCOWWindow struct {
saveNs atomic.Int64
waitNs atomic.Int64
// Scheduling/fault controls are nil in production and set before installation.
// entries (above) are made on a chunk's first touch (a guest write's
// save, or the copier), never at the barrier: the window covers cand, the
// cut's candidate set (immutable once installed), and staged marks the
// ones a pre-copy already holds. nextSlot hands out side-file slots in
// touch order. The barrier's work is O(1), not one entry per candidate.
cand map[uint64]bool
staged map[uint64]bool
nextSlot int64
// covers is the window's reach from the barrier until narrow sets cand:
// the sets the barrier took (O(1) a lookup), a superset of the
// candidates, judged after the pause.
covers func(uint64) bool
}
func (s *WALStore) beforeChunkMutation(first, count uint64) {
@@ -200,12 +217,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() {
}
// The caller owns captureMu exclusive, so no writer can miss this publication.
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) {
func (l *chunkLayerImpl) installCOWWindow(covers func(uint64) bool, spill cowSpillCap) (*cutCOWWindow, error) {
size := uint64(l.blockSize) * l.chunkBlocks
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
if size == 0 || size > math.MaxInt64 || l.numChunks > 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), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), covers: covers, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
w.ctx, w.cancel = context.WithCancel(context.Background())
_, reserved, limit := l.cutPayloadWorkers()
savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size))))
@@ -214,15 +231,6 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he
reserved += int64(2*savers) * int64(size)
w.memory, w.memoryLimit = reserved, limit
w.saverSlots = make(chan struct{}, savers)
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 {
@@ -266,7 +274,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
if w.terminal {
return nil, cowDone, nil
}
e := w.entries[idx]
e := w.entryLocked(idx)
if e == nil {
return nil, cowDone, nil
}
@@ -277,6 +285,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
case cowPending:
if saving {
e.state = cowSaving
e.version = w.layer.chunkVersion(idx) // before the write's own move
} else {
e.state = cowCopying
}
@@ -302,6 +311,57 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
return nil, cowDone, nil
}
}
// entryLocked is idx's entry, made on its first touch: nil when the window
// does not cover idx, done when a pre-copy holds it. Caller holds w.mu.
func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry {
if e := w.entries[idx]; e != nil {
return e
}
if w.cand != nil {
if !w.cand[idx] {
return nil
}
} else if w.covers == nil || !w.covers(idx) {
return nil
}
state := cowPending
if w.staged[idx] {
state = cowDone
}
e := &cutCOWEntry{state: state, ready: make(chan struct{}), slot: w.nextSlot}
w.nextSlot++
w.entries[idx] = e
return e
}
// versionAt is chunk idx's version at the barrier, read atomically with the
// write path: the version a guest write's save recorded with the bytes it
// saved, else the live version, read under w.mu so no writer can claim the
// entry (and move the version) in between.
func (w *cutCOWWindow) versionAt(idx uint64) uint64 {
w.mu.Lock()
defer w.mu.Unlock()
if e := w.entries[idx]; e != nil {
e.mu.Lock()
state, v := e.state, e.version
e.mu.Unlock()
if state == cowSaving || state == cowSaved {
return v
}
}
return w.layer.chunkVersion(idx)
}
// narrow sets the window's final reach after the candidates are judged (and
// versioned): the candidates, the staged ones a pre-copy holds, and the cut's
// base HEAD for missing blocks. Entries already made stay as they are.
func (w *cutCOWWindow) narrow(cand, staged map[uint64]bool, head map[uint64]chunkRef) {
w.mu.Lock()
w.cand, w.staged, w.head, w.covers = cand, staged, head, nil
w.mu.Unlock()
}
func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool {
w.mu.Lock()
defer w.mu.Unlock()
@@ -613,6 +673,18 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
// Each worker owns one immutable image from local read through remote Put.
// Once copied, its entry is done: guest writes need not wait for remote I/O.
// The window remains installed for candidates not yet read by a worker.
// endCOWWindow ends a window: abort, join its savers, and unpublish it.
func (l *chunkLayerImpl) endCOWWindow(w *cutCOWWindow) {
w.abort(errCutCOWAborted)
w.join()
l.cowMu.Lock()
if l.cow == w {
l.cow = nil
l.cowActive.Store(nil)
}
l.cowMu.Unlock()
}
func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, error) {
parent := ctx
abortStop := context.AfterFunc(parent, func() { w.abort(parent.Err()) })
@@ -621,25 +693,26 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec
stop := context.AfterFunc(w.ctx, cancel)
defer stop()
defer cancel()
defer func() {
w.abort(errCutCOWAborted)
w.join()
l.cowMu.Lock()
if l.cow == w {
l.cow = nil
l.cowActive.Store(nil)
defer l.endCOWWindow(w)
// The copier's work: every covered chunk a pre-copy does not hold and no
// touch has finished. Outside the pause (writers are back), O(candidates).
indices := make(map[uint64]bool, len(w.cand))
w.mu.Lock()
for idx := range w.cand {
if w.staged[idx] {
continue
}
l.cowMu.Unlock()
}()
indices := make(map[uint64]bool, len(w.entries))
for idx, e := range w.entries {
e.mu.Lock()
done := e.state == cowDone
e.mu.Unlock()
if !done {
indices[idx] = true
if e := w.entries[idx]; e != nil {
e.mu.Lock()
done := e.state == cowDone
e.mu.Unlock()
if done {
continue
}
}
indices[idx] = true
}
w.mu.Unlock()
order := hotChunkKeys(indices, recent)
out, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) {
c, ok, err := l.copyCOWEntry(w, idx)
@@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) {
for i := 0; i < candidates; i++ {
pending[uint64(i)] = true
}
w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit())
w, err := l.installCOWWindow(func(i uint64) bool { return pending[i] }, l.cowSpillLimit())
if err != nil {
t.Fatal(err)
}
+486 -91
View File
@@ -182,6 +182,29 @@ type chunkLayerImpl struct {
// own names the chunks OwnBatch re-uploads under this layer's own keys in
// the cut it runs (set and cleared under capMu, read under stMu).
own map[uint64]bool
// paused is set from a capture's barrier lock to its release, and
// pauseOps counts per-candidate operations done meanwhile (pauseOp);
// both are touched only by the capturing goroutine.
paused bool
pauseOps int64
// touched holds the chunks whose candidacy may have changed since a
// capture last took them: a map entry change (OnMapEntryChange), a HEAD
// ref change of a clean fill, and, once per layer, every entry UNKNOWN
// or above remoteLSN (seedTouched). The candidate step judges only these
// members against the same predicate the map scan used, so it never
// walks the map; the barrier takes the set whole. unkMu is a leaf lock.
// The set is a chunk bitmap with a per-word summary (candidateSet: 1 bit
// a chunk, 32 KiB at 1 TiB), and touchedSpare is its cleared twin, so
// the barrier's take is a pointer swap.
unkMu sync.Mutex
touched *candidateSet
touchedSpare *candidateSet
touchedSeed sync.Once // the once-per-layer seed (seedTouched)
// touchFilled asks the next set user to touch every clean fill: a
// recovery moved every chunk's version (noteAllMutated), ending their
// knownEqual proofs, at a point that may hold the layer's locks.
touchFilled atomic.Bool
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkMut counts the mutations of each chunk: every dirty-map insert
@@ -485,6 +508,7 @@ func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) {
func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
if !chunkV11Format {
l.head, l.refs = h, nil
l.touchRefChangedLocked()
return
}
if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks {
@@ -493,6 +517,162 @@ func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
l.refs.fillAll(h.Chunks)
h.Chunks = nil
l.head = h
l.touchRefChangedLocked()
}
// touchRefChangedLocked adds to the touched set every clean fill whose HEAD
// ref no longer matches its mark (a whole HEAD install): its knownEqual
// proof is gone, so the next candidate step must judge it. Caller holds stMu.
func (l *chunkLayerImpl) touchRefChangedLocked() {
var gone []uint64
for idx, m := range l.filledClean {
if l.headChunk(idx) != m.ref {
gone = append(gone, idx)
}
}
l.touch(gone...)
}
// resolveTouchFilled touches every clean fill if a recovery asked for it.
// The caller holds neither stMu nor WALStore.mu. byCapture is true only on
// the capturing goroutine: the pause accounting (paused, pauseOps) is its
// own, so a reader's work (status, pre-copy, the shadow) is never charged to
// a cut nor touches those fields.
func (l *chunkLayerImpl) resolveTouchFilled(byCapture bool) {
if !l.touchFilled.Swap(false) {
return
}
l.stMu.Lock()
filled := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
filled = append(filled, idx)
}
l.stMu.Unlock()
if byCapture {
l.pauseOp(len(filled))
}
l.touch(filled...)
}
// newTouchedSet allocates a touched set (its words and summary: size
// dependent, counted as pause work when the capturing goroutine allocates it
// while the guest is paused).
func (l *chunkLayerImpl) newTouchedSet(byCapture bool) *candidateSet {
if byCapture {
l.pauseOp(int(l.numChunks/64) + 1)
}
return newCandidateSet(l.numChunks)
}
// candidateOracle, when set (by this package's tests), receives every chunk
// the full predicate scan finds that a barrier's touched-set candidate step
// missed. Production leaves it nil: the scan is O(chunks).
var candidateOracle func(string)
// candidateOracleScan is the oracle's half at the barrier (tests only, nil
// in production, never counted as pause work): the full scan of the old
// candidate step, the chunks it would make candidates now.
func (l *chunkLayerImpl) candidateOracleScan() map[uint64]bool {
if candidateOracle == nil {
return nil
}
l.stMu.Lock()
base := l.remoteLSN
l.stMu.Unlock()
want := map[uint64]bool{}
l.s.mu.RLock()
defer l.s.mu.RUnlock()
l.stMu.Lock()
defer l.stMu.Unlock()
pendingFilled := l.touchFilled.Load()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
i := uint64(idx)
if l.absent[i] && !l.chunkHasLocalLocked(i) {
continue
}
e := l.s.v3.mapEntries.at(idx)
if (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
if pendingFilled && l.filledClean[i] != (filledMark{}) {
continue // a recovery's touches are pending: the next cut's
}
want[i] = true
}
}
return want
}
// candidateOracleCompare is the oracle's half after the judgement: a chunk
// the barrier's full scan makes a candidate that the judged candidates miss
// is a finding.
func candidateOracleCompare(want, got map[uint64]bool) {
report := candidateOracle
if report == nil {
return
}
for i := range want {
if !got[i] {
report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan at the barrier but not by the judged touched set", i))
return
}
}
}
// requeueTaken returns a cut's taken sets when it ends before judging them
// (a refusal in or right after the pause): the touched members are touched
// again, the dirty set rejoins l.dirty, and a BASE write's allDirty stays.
func (l *chunkLayerImpl) requeueTaken(taken *candidateSet, dirty map[uint64]bool, all bool) {
var back []uint64
taken.each(func(c uint64) { back = append(back, c) })
l.touch(back...)
l.returnTouched(taken)
l.stMu.Lock()
for idx := range dirty {
l.dirty[idx] = true
}
if all {
l.allDirty = true
}
l.dirtyVer++
l.stMu.Unlock()
}
// writtenSinceTake reports whether chunk idx was touched since the barrier
// took the set: a write after the barrier (the live set holds it).
func (l *chunkLayerImpl) writtenSinceTake(idx uint64) bool {
l.unkMu.Lock()
defer l.unkMu.Unlock()
return l.touched != nil && idx < l.numChunks && l.touched.has(idx)
}
// pauseOp counts n per-candidate operations if the guest is paused.
func (l *chunkLayerImpl) pauseOp(n int) {
if l.paused {
l.pauseOps += int64(n)
}
}
// touch adds chunks to the touched set (leaf lock).
func (l *chunkLayerImpl) touch(chunks ...uint64) {
if len(chunks) == 0 {
return
}
l.unkMu.Lock()
set := l.touchedLocked(false) // any goroutine
for _, c := range chunks {
if c < l.numChunks {
set.set(c)
}
}
l.unkMu.Unlock()
}
// touchedLocked is the live touched set, made on first use. Caller holds
// unkMu; byCapture as in resolveTouchFilled.
func (l *chunkLayerImpl) touchedLocked(byCapture bool) *candidateSet {
if l.touched == nil {
l.touched = l.newTouchedSet(byCapture)
}
return l.touched
}
// readAttachHead reads HEAD at attach and installs it. On the v1.1 format,
@@ -591,6 +771,92 @@ func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool {
// ---- sink callbacks ----
// OnMapEntryChange is O(1): it only marks memory, under the leaf unkMu.
func (l *chunkLayerImpl) OnMapEntryChange(chunk uint64) { l.touch(chunk) }
// seedTouched adds, once per layer, every chunk whose map entry is UNKNOWN
// or above remoteLSN now (writes a restart left behind, which no
// OnExtentWrite of this layer saw). It runs on the set's first use: before
// the first capture's barrier (outside the guest pause), or at an earlier
// reader. An entry that turns UNKNOWN later arrives through OnMapEntryChange,
// which may already have run (the set is a union). The caller holds neither
// stMu nor WALStore.mu.
func (l *chunkLayerImpl) seedTouched() {
l.stMu.Lock()
base := l.remoteLSN
l.stMu.Unlock()
var seed []uint64
l.s.mu.RLock()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
if e := l.s.v3.mapEntries.at(idx); e.Unknown || e.LSN > base {
seed = append(seed, uint64(idx))
}
}
l.s.mu.RUnlock()
// An absent chunk with no local write is HEAD's content: it is left out
// here, outside the pause (a fresh attach makes nearly every chunk so),
// as the candidate step would drop it.
kept := seed[:0]
l.stMu.Lock()
for _, idx := range seed {
if !l.absent[idx] || l.chunkHasLocalLocked(idx) {
kept = append(kept, idx)
}
}
l.stMu.Unlock()
l.touch(kept...)
}
// peekTouched lists the touched set's members, for a reader.
func (l *chunkLayerImpl) peekTouched() []uint64 {
l.touchedSeed.Do(l.seedTouched)
l.resolveTouchFilled(false)
l.unkMu.Lock()
defer l.unkMu.Unlock()
set := l.touchedLocked(false)
out := make([]uint64, 0, set.Len())
set.each(func(c uint64) { out = append(out, c) })
return out
}
// takeTouched hands the touched set to a capture's barrier and puts the
// cleared spare in its place, a pointer swap: a chunk marked after the take
// is the next cut's. The caller gives the set back (returnTouched).
func (l *chunkLayerImpl) takeTouched() *candidateSet {
l.unkMu.Lock()
defer l.unkMu.Unlock()
taken := l.touchedLocked(true)
if l.touchedSpare == nil {
l.touchedSpare = l.newTouchedSet(true) // only if prepareTouched was skipped
}
l.touched, l.touchedSpare = l.touchedSpare, nil
return taken
}
// prepareTouched readies the touched sets before a barrier, outside the
// pause: the once-per-layer seed, a pending recovery's clean-fill touches,
// and the cleared spare the barrier swaps in. The barrier then only swaps.
func (l *chunkLayerImpl) prepareTouched() {
l.touchedSeed.Do(l.seedTouched)
l.resolveTouchFilled(true)
l.unkMu.Lock()
l.touchedLocked(true)
if l.touchedSpare == nil {
l.touchedSpare = l.newTouchedSet(true)
}
l.unkMu.Unlock()
}
// returnTouched clears a taken set (O(members)) and keeps it as the spare.
func (l *chunkLayerImpl) returnTouched(set *candidateSet) {
set.clear()
l.unkMu.Lock()
if l.touchedSpare == nil {
l.touchedSpare = set
}
l.unkMu.Unlock()
}
// OnExtentWrite is O(1): it only marks memory. It runs under extent or
// publication locks.
func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) {
@@ -631,9 +897,11 @@ func (l *chunkLayerImpl) noteMutation(lba, lsn uint64) {
cov = func() string { return localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local) }
}
sh.write(idx, lsn, func() { l.chunkMut[idx].Add(1) }, cov)
l.touch(idx)
return
}
l.chunkMut[idx].Add(1)
l.touch(idx) // its version moved: a clean fill's proof ends
}
}
@@ -644,6 +912,7 @@ func (l *chunkLayerImpl) noteAllMutated() {
for i := range l.chunkMut {
l.chunkMut[i].Add(1)
}
l.touchFilled.Store(true)
if sh := l.shadow; sh != nil {
l.recoveredLocked(sh)
}
@@ -726,6 +995,52 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) {
// UNKNOWN never certifies clean; a max LSN beyond HEAD must be captured even
// after the WAL entry has checkpointed and the legacy bitmap says clean.
func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
members := l.peekTouched()
out, _ := l.candidatesFrom(func(f func(uint64)) {
for _, c := range members {
f(c)
}
}, math.MaxUint64)
return out
}
// The candidate predicate, per chunk i (INV-WAL-V3-CAPTURE-CANDIDATES-001):
//
// (entry.Unknown && !knownEqualToHead(i)) || entry.LSN > remoteLSN,
// unless absent(i) && !chunkHasLocal(i)
//
// The touched set must hold every chunk whose answer can turn true between
// two barriers. Each input that moves, and what touches the chunk:
//
// input mover touch
// entry.LSN up recordMapWriteV3 (write, replay) OnMapEntryChange
// entry.Unknown on markMapUnknownV3, recordMapWriteV3 OnMapEntryChange
// (reused LSN); map creation, open seedTouched
// entry.Unknown off capture's clear, known-zero clear none: true to false only
// (persistCapturedMapV3)
// remoteLSN up finishCut none: true to false only
// version (proof) noteMutation touch(i)
// noteAllMutated (Recover, BASE resume touchFilled, resolved at
// under WALStore.mu; BASE transition the next take or peek
// under capMu)
// HEAD ref (proof) setHeadLocked, applyCommitLocked touchRefChangedLocked,
// touch(changed)
// clean mark added a fill none: true to false only
// clean marks gone BASE install (allDirty: every chunk) none: allDirty
// own (proof) OwnBatch addOwnCandidatesLocked
// absent off a fill's install touch(i)
// a local write; BASE install noteMutation; allDirty
// absent on an evict none: true to false only
//
// A recovery that lands after a barrier's take is the next cut's, as a write
// after the barrier is. Under tests, every barrier also runs the full scan as
// an oracle (candidateOracle) and reports any chunk the set missed.
//
// candidatesFrom is the candidate step over a touched set (peeked by a
// reader, taken by the barrier). Its work is O(changed): the WAL's dirty
// entries, the own batch, and the set's members, each judged on its own; no
// map of every chunk is walked. visits counts every chunk index it touched.
func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64)), upTo uint64) (map[uint64]bool, int64) {
out := map[uint64]bool{}
var base uint64
@@ -733,42 +1048,40 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
base = l.remoteLSN
l.stMu.Unlock()
visits := int64(0)
for _, e := range l.s.dm.snapshot() {
visits++
// Retention in the local WAL is not dirt since HEAD. Lower-LSN
// BASE/direct changes remain conservative through UNKNOWN below.
if e.LSN > base {
if e.LSN > base && e.LSN <= upTo {
out[l.chunkOf(e.LBA)] = true
}
}
{
l.stMu.Lock()
absent := map[uint64]bool{}
for idx := range l.absent {
if !l.chunkHasLocalLocked(idx) {
absent[idx] = true
}
l.s.mu.RLock() // before stMu, the established order
defer l.s.mu.RUnlock()
l.stMu.Lock()
visits += int64(len(l.own))
l.addOwnCandidatesLocked(out)
// The map is not scanned. An entry above remoteLSN is a write that is
// either still in the WAL (the dirty map above), flushed above the last
// cut (l.dirty, OnExtentWrite) or captured by a cut that did not land
// (requeued into l.dirty); the first use seeds every entry above
// remoteLSN at that time (a restart's earlier writes) with the UNKNOWN
// ones. An absent chunk with no local write is HEAD's content and leaves
// the set: it becomes present only by a fill (known equal to HEAD) or by
// local writes (l.dirty). A clean fill still equal to HEAD is not
// compared again.
members(func(i uint64) {
visits++
if i >= uint64(l.s.v3.mapEntries.len()) || (l.absent[i] && !l.chunkHasLocalLocked(i)) {
return
}
filled := map[uint64]bool{}
for idx := range l.filledClean {
if l.knownEqualToHeadLocked(idx) {
filled[idx] = true
}
if e := l.s.v3.mapEntries.at(int(i)); (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
out[i] = true
}
l.addOwnCandidatesLocked(out)
l.stMu.Unlock()
l.s.mu.RLock()
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
e := l.s.v3.mapEntries.at(idx)
i := uint64(idx)
if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) {
out[i] = true
}
}
l.s.mu.RUnlock()
}
return out
})
l.stMu.Unlock()
return out, visits
}
// filledMark is a clean fill: the chunk's version and the HEAD ref it was
@@ -898,6 +1211,10 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat
sh.fill(idx, ref.SHA256)
}
delete(l.absent, idx)
// Absent to present: the predicate's exclusion ends. Without a fresh
// clean mark (a version moved during the fetch, e.g. by a recovery) the
// chunk may now be a candidate, so the next candidate step judges it.
l.touch(idx)
for i := uint64(0); i < l.chunkBlocks; i++ {
delete(l.localBlocks, first+i)
}
@@ -1308,6 +1625,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{}, cause
}
// Before the pause: the once-per-layer UNKNOWN seed, and one sync so the
// pause's own sync flushes only what came after it (the first cut after a
// fill pays its write-back here). The in-pause sync still fixes H.
l.prepareTouched()
preSync := time.Now()
if _, err := l.s.syncWithPhases(nil); err != nil {
st.PreSyncNs = time.Since(preSync).Nanoseconds()
return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err)
}
st.PreSyncNs = time.Since(preSync).Nanoseconds()
// Quiesced cut. The guest pause starts at the Lock REQUEST: a pending
// writer blocks new readers of captureMu, so a write arriving while the cut
// waits for writers already holding it (e.g. parked in WAL admission) is
@@ -1334,6 +1662,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
// Resume rejected tentative admission before any ordinary COW upload.
unlockCapture := func() {
l.paused = false
l.s.captureMu.Unlock()
if !detach && releasePrecopy != nil {
releasePrecopy()
@@ -1344,6 +1673,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
hook()
}
l.s.captureMu.Lock()
l.paused, l.pauseOps = true, 0
defer func() { st.PauseCandidateOps = l.pauseOps }()
barrier := time.Now()
st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds()
h, err := l.s.syncWithPhases(&st.SyncPhases)
@@ -1358,17 +1689,89 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
l.cutPhase("candidates")
candidateStart := time.Now()
candidates := map[uint64]bool{}
for idx := range l.captureCandidates() {
// The pause does O(1) work: the touched set and the dirty set are taken
// by pointer swaps and the copy window opens over what they name (a
// superset of the candidates). Every per-candidate step runs after the
// pause, under the window: the judgement, the versions (atomic with the
// write path), staged reuse, the base refs and the copy-order hint.
taken := l.takeTouched()
// A recovery that landed after prepareTouched moved every clean fill's
// version: its request is taken here as a flag (O(1)); the window covers
// every chunk until it narrows, and the fills are judged after the pause.
filledTaken := l.touchFilled.Swap(false)
oracleWant := l.candidateOracleScan() // tests only (nil in production)
l.stMu.Lock()
dirtyTaken, all := l.dirty, l.allDirty
l.dirty, l.allDirty = map[uint64]bool{}, false
l.cutLSN = h
l.stMu.Unlock()
own := l.own // stable for the cut (set and cleared under capMu)
covers := func(idx uint64) bool { return all || filledTaken || taken.has(idx) || dirtyTaken[idx] || own[idx] }
windowStart := time.Now()
w, installErr := l.installCOWWindow(covers, spill)
if installErr == nil {
w.budget = budget
}
// The barrier ends here. A pre-copy attempt's drained frontend stays
// drained until its freeze decision below, made on the judged tail: its
// guest pause runs to that release, as before. An ordinary cut's guest
// is back now, and its pause did O(1) work.
drained := releasePrecopy != nil
l.s.captureMu.Unlock()
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
if !drained {
l.paused = false
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
}
releaseDrain := func() {
if drained {
if releasePrecopy != nil && !detach {
releasePrecopy()
releasePrecopy = nil
}
l.paused = false
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
drained = false
}
}
if installErr != nil {
releaseDrain()
if filledTaken {
l.touchFilled.Store(true)
}
l.requeueTaken(taken, dirtyTaken, all)
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr)
}
// After the pause. The judgement: the touched set's members with the
// map scan's predicate, the WAL entries up to H, the own batch, the
// taken dirty set, and every chunk after a BASE write.
members := taken.each
if filledTaken {
l.stMu.Lock()
filled := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
filled = append(filled, idx)
}
l.stMu.Unlock()
members = func(f func(uint64)) {
taken.each(f)
for _, idx := range filled {
f(idx)
}
}
}
candidates, visits := l.candidatesFrom(members, h)
visits += int64(len(taken.summary)) // the summary words the walk read
l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause
for idx := range dirtyTaken {
visits++
candidates[idx] = true
}
l.stMu.Lock()
all := l.allDirty
for idx := range l.dirty {
candidates[idx] = true
}
if all {
for i := uint64(0); i < l.numChunks; i++ {
visits++
// An absent chunk with no local write is HEAD's content by
// definition: comparing it would only fetch it back.
if l.absent[i] && !l.chunkHasLocalLocked(i) {
@@ -1377,72 +1780,79 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
candidates[i] = true
}
}
l.stMu.Unlock()
candidateOracleCompare(oracleWant, candidates) // tests only
// A chunk known to hold HEAD's bytes at its current version (a clean
// fill, or a compare by a cut that did not publish) is not compared
// again, whatever returned it to the dirty set: any write since raises
// its version, and a newer HEAD changes its ref. A chunk an own batch
// re-uploads under this layer's key stays: equal bytes are its point.
l.stMu.Lock()
l.pauseOp(len(candidates))
for idx := range candidates {
if l.knownEqualToHeadLocked(idx) {
delete(candidates, idx)
}
}
if sh := l.shadow; sh != nil {
// Extras are judged only for a cut that can proceed: a store behind
// HEAD (H below its RemoteLSN) is refused before any upload, and its
// writes are not dirt above HEAD to the engine.
proceeds := h >= l.head.RemoteLSN
miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != nil && proceeds, proceeds)
if hook := l.testShadowCheck; hook != nil {
hook(miss, extra)
}
}
// A staged chunk stands for the barrier copy while no write reached
// it since staging (its version is unchanged) and HEAD is the one it
// was compared against.
l.stMu.Unlock()
// Each candidate's version at the barrier: the version a guest write's
// save recorded with its bytes, else the live one, read atomically with
// the write path; the window closes on a chunk only after this and its
// upload. A staged chunk stands for the barrier copy while its version
// is the barrier's and HEAD is the one it was compared against.
var captured []capturedChunk
var capturedVersions map[uint64]uint64
capturedVersions = make(map[uint64]uint64, len(candidates))
useStaged := map[uint64]bool{}
capturedVersions := make(map[uint64]uint64, len(candidates))
l.pauseOp(2 * len(candidates)) // versions, staged reuse
for idx := range candidates {
if capturedVersions != nil {
capturedVersions[idx] = l.chunkVersion(idx)
}
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen {
capturedVersions[idx] = w.versionAt(idx)
}
useStaged := map[uint64]bool{}
l.stMu.Lock()
for idx := range candidates {
if sc, ok := staged[idx]; ok && sc.ver == capturedVersions[idx] && sc.headGen == l.head.Gen {
useStaged[idx] = true
captured = append(captured, sc.capturedChunk)
}
}
if sh := l.shadow; sh != nil {
// Extras are judged only for a cut that can proceed: a store behind
// HEAD (H below its RemoteLSN) is refused before any upload, and its
// writes are not dirt above HEAD to the engine. A chunk written since
// the barrier is in the live touched set: the record counts its write.
proceeds := h >= l.head.RemoteLSN
after := l.writtenSinceTake
skip := func(idx uint64) bool { return l.shadowExemptLocked(idx) || after(idx) }
miss, extra := sh.checkAfter(candidates, skip, after, l.testShadowCheck != nil && proceeds, proceeds)
if hook := l.testShadowCheck; hook != nil {
hook(miss, extra)
}
}
st.CandidateVisits = visits
l.inflight = candidates
l.dirty = map[uint64]bool{}
l.allDirty = false
l.cutLSN = h
l.pauseOp(2 * len(candidates)) // the shadow check, the base refs
baseHead := l.cutBaseLocked(candidates)
l.stMu.Unlock()
w.narrow(candidates, useStaged, baseHead.Chunks)
l.returnTouched(taken)
l.cutPhase("compare")
// Candidates, mutation versions and the copy-order hint belong to the same barrier.
// Do not sample the owned map after COW writers are admitted again.
l.pauseOp(len(candidates))
recent := l.chunkRecency(candidates, h)
st.CandidateNs += time.Since(candidateStart).Nanoseconds()
// The authoritative candidate set is fixed with mutation admission closed.
// The owner callback is nonblocking and may stop only an already drained
// frontend; rejected attempts remain ordinary COW cuts.
if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil {
tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
detach = freeze(tail, pauseStart, st)
}
releaseDrain()
if guestFrozen && !detach {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.endCOWWindow(w)
l.requeueCut(all)
return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit())
}
if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.endCOWWindow(w)
// HEAD holds the image of a later LSN than this host's log has
// reached: publishing would move remote_lsn backwards. Refused
// before any upload. (A HEAD of a newer holder fences below.)
@@ -1451,35 +1861,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
st.CandidateChunks = max(st.CandidateChunks, len(candidates))
var copyErr error
copyStart := time.Now()
bytesBeforeCopy := st.UploadedBytes
{
var w *cutCOWWindow
windowStart := time.Now()
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill)
if copyErr == nil {
w.budget = budget
}
unlockCapture()
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
copyStart = time.Now()
if copyErr == nil {
var copied []capturedChunk
copied, copyErr = l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
for _, c := range copied {
if c.key != "" {
st.UploadedChunks++
st.UploadedBytes += int64(c.size)
}
}
captured = append(captured, copied...)
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
st.COWSavedChunks = int(w.saved.Load())
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
copied, copyErr := l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
for _, c := range copied {
if c.key != "" {
st.UploadedChunks++
st.UploadedBytes += int64(c.size)
}
}
captured = append(captured, copied...)
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
st.COWSavedChunks = int(w.saved.Load())
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
st.CopyNs = time.Since(copyStart).Nanoseconds()
if st.UploadedBytes > bytesBeforeCopy {
@@ -2145,6 +2539,7 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) {
d := *id.DetachedBy
h.DetachedBy = &d
}
l.touch(changed...) // their refs changed: the next candidate step judges them
for _, idx := range changed {
r, ok := id.Chunks[idx]
switch {
@@ -0,0 +1,67 @@
package storage
import "math/bits"
// candidateSet is the record's chunk candidate set of one cut interval:
// one bit per chunk, and a summary of one bit per 64-chunk word
// that has any bit set. Setting a bit is O(1); walking the set is O(C + S/4096)
// (the summary's words, then only the words it names); clearing it is O(C).
// It is a superset: a bit stays set when the chunk later leaves the candidate
// kinds (committed, evicted), and the reader keeps only the chunks whose kind
// is still a candidate.
type candidateSet struct {
words []uint64
summary []uint64
n int // bits set (a chunk counted once)
}
func newCandidateSet(chunks uint64) *candidateSet {
w := (chunks + 63) / 64
return &candidateSet{words: make([]uint64, w), summary: make([]uint64, (w+63)/64)}
}
func (s *candidateSet) set(chunk uint64) {
w, b := chunk/64, uint64(1)<<(chunk%64)
if s.words[w]&b != 0 {
return
}
s.words[w] |= b
s.summary[w/64] |= 1 << (w % 64)
s.n++
}
func (s *candidateSet) has(chunk uint64) bool { return s.words[chunk/64]&(1<<(chunk%64)) != 0 }
// each calls f for every chunk in the set, in chunk order.
func (s *candidateSet) each(f func(chunk uint64)) {
for si, sw := range s.summary {
for sw != 0 {
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
sw &= sw - 1
for word := s.words[w]; word != 0; word &= word - 1 {
f(w*64 + uint64(bits.TrailingZeros64(word)))
}
}
}
}
// or adds every chunk of o (same shape).
func (s *candidateSet) or(o *candidateSet) {
o.each(s.set)
}
// clear empties the set, touching only the words it names.
func (s *candidateSet) clear() {
for si, sw := range s.summary {
for sw != 0 {
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
sw &= sw - 1
s.words[w] = 0
}
s.summary[si] = 0
}
s.n = 0
}
// Len is the number of chunks in the set.
func (s *candidateSet) Len() int { return s.n }
@@ -139,6 +139,13 @@ type chunkRecordRuntime struct {
changes []int // changes since the page was last written
firstDirty []time.Time // when the page went dirty
headerG uint64 // the G last written
// cand is the candidate set of the current cut interval: every
// applied event whose result is a candidate kind (P, U, HU) sets its
// chunk, a write that leaves U as U included (new dirt since the last
// take). A cut takes it whole and leaves the empty spare in its place;
// candTaken counts the takes (the barrier's O(1) work, for its counters).
cand, spare *candidateSet
candTaken uint64
}
// newChunkRecordRuntime builds the runtime from the record as the open left
@@ -157,12 +164,16 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u
valid: append([]uint64(nil), valid...),
dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs), since: make([]uint64, segs),
changes: make([]int, segs), firstDirty: make([]time.Time, segs), headerG: headerG}
r.cand, r.spare = newCandidateSet(chunks), newCandidateSet(chunks)
for c, k := range kinds {
code, err := chunkRecordStateCode(k)
if err != nil {
return nil, err
}
r.kinds[c] = code
if isRecordCandidate(k) { // at open: the persisted kinds are the source of truth
r.cand.set(uint64(c))
}
}
now := time.Now()
for seg, changed := range changedAtOpen {
@@ -250,6 +261,9 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
delete(r.unmarked, chunk) // an evict: nothing local is claimed
}
}
if isRecordCandidate(res.State.Kind) {
r.cand.set(chunk)
}
if res.State.Kind != cur || newHash != r.hashes[chunk] {
code, err := chunkRecordStateCode(res.State.Kind)
if err != nil {
@@ -274,6 +288,46 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
return eff, nil
}
// TakeCandidates hands the current interval's candidate set to a cut and
// starts an empty one, in O(1): the record keeps setting chunks into the new
// set, so a write after the take is the next cut's. The cut gives the set
// back with ReturnCandidates (its candidates OR'd back if the cut did not
// commit them), never keeps it.
func (r *chunkRecordRuntime) TakeCandidates() *candidateSet {
r.mu.Lock()
defer r.mu.Unlock()
taken := r.cand
if r.spare == nil { // a second take before the first set came back
r.spare = newCandidateSet(r.chunks)
}
r.cand, r.spare = r.spare, nil
r.candTaken++
return taken
}
// ReturnCandidates gives a taken set back. With keep (a refused, unknown or
// aborted cut) its chunks join the current interval's set again, so no
// candidate is lost; the set is then cleared (O(C)) and becomes the spare.
func (r *chunkRecordRuntime) ReturnCandidates(taken *candidateSet, keep bool) {
r.mu.Lock()
defer r.mu.Unlock()
if keep {
r.cand.or(taken)
}
taken.clear()
if r.spare == nil {
r.spare = taken
}
}
// IsCandidate reports whether a chunk's kind is a candidate now (a taken
// set is a superset: the cut keeps only these).
func (r *chunkRecordRuntime) IsCandidate(chunk uint64) bool {
r.mu.Lock()
defer r.mu.Unlock()
return isRecordCandidate(kindByCode[r.kinds[chunk]])
}
// PersistSegmentOf writes the page holding chunk if it is dirty (no-op if
// its last written content is current): the durable receipt an evict needs
// before the store's bits may clear, also when the in-memory state was
@@ -376,6 +376,13 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat
// the misses and, when withExtra (tests: a full scan of the record, too
// slow for a barrier), the record's extra candidates. Caller holds stMu.
func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
return s.checkAfter(engine, skip, nil, withExtra, proceeds)
}
// checkAfter is check for candidates judged after the guest pause: after,
// when set, names the chunks written since the barrier (the record already
// counts those writes), which are no record extra of this cut.
func (s *chunkRecordShadow) checkAfter(engine map[uint64]bool, skip, after func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
s.rec.mu.Lock()
for idx := range engine {
if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) {
@@ -387,7 +394,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool
s.fullScans++
for idx, code := range s.rec.kinds {
k := kindByCode[code]
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) {
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) && (after == nil || !after(uint64(idx))) {
extra = append(extra, uint64(idx))
}
}
@@ -18,6 +18,12 @@ func TestMain(m *testing.M) {
found = append(found, msg)
mu.Unlock()
}
// Every barrier also checks its touched-set candidates against the full
// scan; a chunk the set missed is a finding too.
candidateOracle = func(msg string) {
fmt.Fprintln(os.Stderr, msg) // in place, next to the test that ran it
shadowFindings(msg)
}
// CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store
// format (the lab build's mode); it selects a format, it turns no check
// off.
@@ -28,7 +34,7 @@ func TestMain(m *testing.M) {
mu.Lock()
defer mu.Unlock()
if len(found) > 0 {
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0])
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow or candidate oracle findings; first: %s\n", len(found), found[0])
if code == 0 {
code = 1
}
@@ -42,8 +48,13 @@ func TestMain(m *testing.M) {
func forgetMarksAsARestart(t *testing.T, l *chunkLayerImpl) {
t.Helper()
l.stMu.Lock()
forgotten := make([]uint64, 0, len(l.filledClean))
for idx := range l.filledClean {
forgotten = append(forgotten, idx)
}
l.filledClean = map[uint64]filledMark{}
l.stMu.Unlock()
l.touch(forgotten...) // a restarted layer's seed judges them again
sh, err := newChunkRecordShadow(l)
if err != nil {
t.Fatal(err)
+15
View File
@@ -79,6 +79,10 @@ import (
// under-report.
type chunkSink interface {
OnExtentWrite(lba uint64, lsn uint64)
// OnMapEntryChange is called when the store changes a chunk's map entry
// (a write's LSN, or UNKNOWN by a direct/BASE mutation or a reused LSN):
// O(1), under WALStore.mu; it takes only a leaf lock.
OnMapEntryChange(chunk uint64)
BeforeCheckpointAdvance(lsn uint64) error
BeginBaseInstall() error
EndBaseInstall(frontier uint64) error
@@ -413,6 +417,17 @@ type SyncPhaseStats struct {
type chunkCutStats struct {
SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it)
// CandidateVisits counts the chunk indices the barrier's candidate step
// visited (scanned entries and set members), the work a pause pays for.
CandidateVisits int64
// PauseCandidateOps counts per-candidate operations done while the guest
// is paused (from the barrier lock to its release): zero when the pause
// does O(1) work.
PauseCandidateOps int64
// PreSyncNs is the sync right before the barrier, outside the guest
// pause (never part of BarrierPauseNs): the pause's own sync then has
// only what came after it.
PreSyncNs int64
// Disjoint non-payload intervals within barrier-to-settlement fixed cost.
CandidateNs int64
WindowSetupNs int64
@@ -34,6 +34,9 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) {
e.Local = e.Local.mark(lba%cb, count)
}
v.mapEntries.set(index, e)
if h := s.chunk.Load(); h != nil {
h.sink.OnMapEntryChange(uint64(index))
}
}
// Recover may scan retained records already represented by the durable bitmap.
@@ -18,6 +18,7 @@ func (h *heldWALReadMiss) OnReadMiss(uint64) ([]byte, error) {
return nil, nil
}
func (*heldWALReadMiss) OnExtentWrite(uint64, uint64) {}
func (*heldWALReadMiss) OnMapEntryChange(uint64) {}
func (*heldWALReadMiss) BeforeCheckpointAdvance(uint64) error { return nil }
func (*heldWALReadMiss) BeginBaseInstall() error { return nil }
func (*heldWALReadMiss) EndBaseInstall(uint64) error { return nil }
+1
View File
@@ -637,6 +637,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-TOUCHED-001` | The barrier's candidate step judges only a touched set (a chunk bitmap with a word summary) with INV-WAL-V3-CAPTURE-CANDIDATES-001's predicate, never every chunk; the set covers every chunk whose answer may have changed since the barrier took it. The cut syncs before the barrier, outside the pause. | M5 candidate selection (CandBitmap: NoBitLost, SummaryCovers) | `chunk_layer.go` `candidatesFrom`, `takeTouched`, `seedTouched`, `touch`, `OnMapEntryChange`, `noteMutation`, `setHeadLocked`, `applyCommitLocked`; `walstore_map_checkpoint_v3.go` `recordMapWriteV3`; `base_install_v3.go` `markMapUnknownV3`; `chunk_record_candidates.go` `candidateSet` | `TestIdleCutCandidateWorkIsFlatInS`, `TestOneChangedChunkCutVisitsNoFullScan`, `TestCutSyncsBeforeItsBarrier`, `TestUnknownCommitOutcomeLosesNoChunk`, `TestCandidateSetOrBackKeepsTheSummary` (`chunk_cut_candidate_set_test.go`); `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestACleanFillRecordEndsWithItsHeadRef` (`chunk_fresh_readback_candidates_test.go`); `TestSpacePerChunkAt1TiBShape` (`chunk_space_baseline_test.go`) | The candidate set is the same; an idle cut's candidate work no longer grows with S | ACTIVE |
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE |
| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB |
| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE |
+4
View File
@@ -24,6 +24,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one
`level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An
explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses.
- A cut's barrier no longer walks every chunk to find its candidates: its candidate work is the chunks that
changed plus one summary word per 4,096 chunks, so an idle cut's pause does not grow with the volume's size. The
cut also syncs the store once right before its barrier, outside the guest pause (reported as `PreSyncNs`), so the
pause's own sync has only what was written after it.
## Upgrade
- With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was
+3
View File
@@ -273,6 +273,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock |
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable |
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion |
| `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. |
| `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. |
| `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. |
| `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. |
| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. |
| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. |