storage: reconciliation is owned by a generation; a BASE install supersedes a running worker

Every reconciliation start and every BeginBaseInstall bumps a generation.
A worker selects slices, records compare results and certifies the dirty
set only while its own generation is current, so:
- a worker running when a BASE install begins can no longer finish over
  it and clear the install guard (Base=Installing), in memory or on disk;
  finishReconcile also refuses while the guard is set (two independent
  guards);
- a worker that saw its set empty, or compared a chunk, before a BASE
  install restarted reconciliation can neither certify the replacement
  run nor delete from its set.
A replaced run closes its channel, and waitReconciled re-checks against
the current run.

Deterministic schedules (test hook at slice, compare and certify):
- held worker -> BeginBaseInstall -> worker resumes: cuts stay refused
  as base_installing, the persisted header keeps Installing, a restart
  still refuses;
- old worker paused at certify -> Begin/EndBaseInstall -> old resumes:
  the replacement stays reconciling and untouched, cuts refused;
- old worker paused after a compare -> Begin/End -> old resumes: the
  replacement set is untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 12:31:49 -08:00
1 parent df06318ef9
commit 7b7877e16f
3 files changed
+244 -26

No files matched your search

+64 -26
View File
@@ -95,10 +95,14 @@ type chunkLayerImpl struct {
hashMode bool // the dirty set is unknown: reconcile every chunk against HEAD before any cut
// reconcile holds the chunks the reconciler has not compared yet;
// reconcileTotal is the size of the current reconciliation, and
// reconciled is closed when it is done (under stMu).
// reconciled is closed when it is done or replaced (under stMu).
// reconcileGen names the current reconciliation: every start and every
// BeginBaseInstall bumps it, and a worker reads, updates and certifies
// only while its own generation is current.
reconcile map[uint64]bool
reconcileTotal int
reconciled chan struct{}
reconcileGen uint64
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkMut counts the mutations of each chunk: every dirty-map insert
// (any LSN, a replica apply's lower LSN included) and every BASE
@@ -523,7 +527,10 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func
func (l *chunkLayerImpl) BeginBaseInstall() error {
l.capMu.Lock()
defer l.capMu.Unlock()
return l.writeBaseState(chunkBaseInstalling, func() { l.allDirty = true })
// A running reconciliation is superseded: its worker can neither
// certify a dirty set nor clear the install guard. EndBaseInstall
// starts a new one.
return l.writeBaseState(chunkBaseInstalling, func() { l.allDirty = true; l.reconcileGen++ })
}
func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error {
@@ -1150,19 +1157,24 @@ func (l *chunkLayerImpl) startReconcile() {
}
set[i] = true
}
l.reconcileGen++
gen := l.reconcileGen
if l.reconciled != nil {
close(l.reconciled) // a waiter on the replaced run re-checks
}
l.reconcile, l.reconcileTotal, l.reconciled = set, len(set), make(chan struct{})
l.stMu.Unlock()
// Nothing to compare (a fresh host: every HEAD chunk is absent and no
// block was written): the dirty set is known now, with no window in
// which cuts are refused.
if len(set) == 0 && l.cfg.testReconcileHold == nil && l.finishReconcile() {
if len(set) == 0 && l.cfg.testReconcileHold == nil && l.cfg.testReconcileHook == nil && l.finishReconcile(gen) {
return
}
done, err := l.register()
if err != nil {
return
}
go l.reconcileLoop(done)
go l.reconcileLoop(done, gen)
}
// reconcileLoop compares the chunks in the reconcile set with HEAD outside
@@ -1170,7 +1182,7 @@ func (l *chunkLayerImpl) startReconcile() {
// HEAD's becomes dirty. A write racing the comparison marks its chunk
// dirty anyway, so a chunk is never lost. When the set is empty the dirty
// set is exact: it is persisted with a header naming HEAD, and cuts resume.
func (l *chunkLayerImpl) reconcileLoop(done func()) {
func (l *chunkLayerImpl) reconcileLoop(done func(), gen uint64) {
defer done()
for {
if l.ctx.Err() != nil {
@@ -1183,7 +1195,14 @@ func (l *chunkLayerImpl) reconcileLoop(done func()) {
return
}
}
if hook := l.cfg.testReconcileHook; hook != nil {
hook("batch", gen)
}
l.stMu.Lock()
if l.reconcileGen != gen { // superseded
l.stMu.Unlock()
return
}
var batch []uint64
for _, idx := range sortedKeys(l.reconcile) {
if len(batch) == reconcileSlice {
@@ -1194,7 +1213,10 @@ func (l *chunkLayerImpl) reconcileLoop(done func()) {
head := copyHead(l.head)
l.stMu.Unlock()
if len(batch) == 0 {
if l.finishReconcile() {
if hook := l.cfg.testReconcileHook; hook != nil {
hook("finish", gen)
}
if l.finishReconcile(gen) {
return
}
if !l.sleep(100 * time.Millisecond) {
@@ -1212,7 +1234,14 @@ func (l *chunkLayerImpl) reconcileLoop(done func()) {
}
ref, had := head.Chunks[idx]
same := (!had && isAllZero(data)) || (had && sha256.Sum256(data) == ref.SHA256)
if hook := l.cfg.testReconcileHook; hook != nil {
hook("compared", gen)
}
l.stMu.Lock()
if l.reconcileGen != gen { // superseded: the replacement owns the set
l.stMu.Unlock()
return
}
if !same {
l.dirty[idx] = true
l.dirtyVer++
@@ -1223,12 +1252,19 @@ func (l *chunkLayerImpl) reconcileLoop(done func()) {
}
}
// finishReconcile persists the reconciled dirty set and leaves hash mode.
// It reports false when the bitmap could not be written (retried).
func (l *chunkLayerImpl) finishReconcile() bool {
// finishReconcile persists reconciliation gen's dirty set and leaves hash
// mode. It reports false when the bitmap could not be written (retried),
// and true when done or when gen is no longer current: a superseded run
// (replaced, or a BASE install began) writes nothing and certifies
// nothing. bmMu is held throughout, so no BASE state change interleaves.
func (l *chunkLayerImpl) finishReconcile(gen uint64) bool {
l.bmMu.Lock()
defer l.bmMu.Unlock()
l.stMu.Lock()
if l.reconcileGen != gen || len(l.reconcile) != 0 || l.hdr.Base == chunkBaseInstalling {
l.stMu.Unlock()
return true
}
still := map[uint64]bool{}
for idx := range l.dirty {
still[idx] = true
@@ -1264,24 +1300,26 @@ func (l *chunkLayerImpl) finishReconcile() bool {
}
// waitReconciled returns once the layer is not reconciling, or
// errChunkReconciling when ctx ends first.
// errChunkReconciling when ctx ends first. A replaced run wakes its
// waiters, which re-check against the current one.
func (l *chunkLayerImpl) waitReconciled(ctx context.Context) error {
l.stMu.Lock()
reconciling, ch := l.hashMode, l.reconciled
l.stMu.Unlock()
if !reconciling {
return nil
}
if ch == nil {
return errChunkReconciling
}
select {
case <-ch:
return nil
case <-ctx.Done():
return fmt.Errorf("%w: %w", errChunkReconciling, ctx.Err())
case <-l.ctx.Done():
return errors.New("storage: chunk layer closed")
for {
l.stMu.Lock()
reconciling, ch := l.hashMode, l.reconciled
l.stMu.Unlock()
if !reconciling {
return nil
}
if ch == nil {
return errChunkReconciling
}
select {
case <-ch:
case <-ctx.Done():
return fmt.Errorf("%w: %w", errChunkReconciling, ctx.Err())
case <-l.ctx.Done():
return errors.New("storage: chunk layer closed")
}
}
}
@@ -7,6 +7,8 @@ package storage
import (
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
)
@@ -30,6 +32,12 @@ func newReconcileFixture(t *testing.T, hold bool) *reconcileFixture {
// newReconcileFixtureWith reattaches after mutate damaged the bitmap.
func newReconcileFixtureWith(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore)) *reconcileFixture {
t.Helper()
return newReconcileFixtureOpts(t, hold, mutate, nil)
}
// newReconcileFixtureOpts also lets mutateCfg adjust the reattach config.
func newReconcileFixtureOpts(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore), mutateCfg func(cfg *chunkLayerConfig)) *reconcileFixture {
t.Helper()
s, path, crash := crashableStore(t)
f := newFakeChunkRemote()
@@ -58,6 +66,9 @@ func newReconcileFixtureWith(t *testing.T, hold bool, mutate func(bm *fakeBitmap
fx.hold = make(chan struct{})
fx.cfg.testReconcileHold = fx.hold
}
if mutateCfg != nil {
mutateCfg(&fx.cfg)
}
l, err := attachChunkLayer(s2, f, fx.cfg)
if err != nil {
t.Fatal(err)
@@ -240,3 +251,167 @@ func TestChunkReconcile_UnpersistedResultKeepsReconciling(t *testing.T) {
fx.bm.mu.Unlock()
waitReconciledForTest(t, fx.layer)
}
// refusedOver asserts check() holds at every poll for d: a negative
// invariant is checked over an interval, not once.
func refusedOver(t *testing.T, d time.Duration, what string, check func() error) {
t.Helper()
end := time.Now().Add(d)
for time.Now().Before(end) {
if err := check(); err != nil {
t.Fatalf("%s: %v", what, err)
}
time.Sleep(10 * time.Millisecond)
}
}
// A worker reconciling a lost bitmap when a BASE install begins must not
// finish over it: the install guard (Base=Installing) stays in force, in
// memory and on disk, until the install itself completes.
func TestChunkReconcile_BaseInstallSupersedesRunningReconciliation(t *testing.T) {
fx := newReconcileFixture(t, true) // the worker is held before its first slice
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
fx.release() // the old worker runs on
refusedOver(t, 300*time.Millisecond, "after BeginBaseInstall", func() error {
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
return fmt.Errorf("Cut admitted or refused for another cause during an incomplete BASE install: %v", err)
}
fx.bm.mu.Lock()
base := fx.bm.hdr.Base
fx.bm.mu.Unlock()
if base != chunkBaseInstalling {
return fmt.Errorf("persisted Base=%v, want the install guard (installing)", base)
}
return nil
})
// A restart still sees the incomplete install and refuses cuts.
if err := fx.s.Close(); err != nil { // closes the layer too
t.Fatal(err)
}
s3, _ := reopen(t, fx.path)
defer s3.Close()
cfg := fx.cfg
cfg.testReconcileHold = nil
l2, err := attachChunkLayer(s3, fx.f, cfg)
if err != nil {
t.Fatal(err)
}
defer l2.Close()
if _, err := l2.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
t.Fatalf("Cut after restart during an incomplete BASE install: %v", err)
}
}
// An old worker that saw its set empty and paused before certifying must
// not certify (or touch) the replacement reconciliation that a BASE
// install started meanwhile: cuts stay refused until the replacement is
// done.
func TestChunkReconcile_OldCompletionCannotCertifyReplacement(t *testing.T) {
var oldGen atomic.Uint64
atFinish, releaseFinish, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
hook := func(stage string, gen uint64) {
switch {
case stage == "finish" && oldGen.CompareAndSwap(0, gen):
close(atFinish)
<-releaseFinish
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
<-replHold
}
}
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
// Registered after the fixture: cleanups run last-in first-out, so the
// workers are released before the layer closes and waits for them.
t.Cleanup(func() {
for _, ch := range []chan struct{}{releaseFinish, replHold} {
select {
case <-ch:
default:
close(ch)
}
}
})
select {
case <-atFinish:
case <-time.After(ctLocalBound):
t.Fatal("the first reconciliation never reached certification")
}
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
t.Fatal(err)
}
total := fx.layer.Stats().ReconcileTotal
if total == 0 {
t.Fatal("the replacement reconciliation has nothing to compare; the schedule needs local chunks")
}
close(releaseFinish) // the old worker resumes into certification
refusedOver(t, 300*time.Millisecond, "after the old worker resumed", func() error {
st := fx.layer.Stats()
if !st.Reconciling || st.ReconcileTotal != total || st.ReconcileDone != 0 {
return fmt.Errorf("replacement certified or modified by the old worker: reconciling=%v done=%d/%d (total was %d)", st.Reconciling, st.ReconcileDone, st.ReconcileTotal, total)
}
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
return fmt.Errorf("Cut admitted while the replacement reconciles: %v", err)
}
return nil
})
close(replHold)
waitReconciledForTest(t, fx.layer)
if _, err := fx.layer.Cut(ctTimeout(t)); err != nil {
t.Fatalf("Cut after the replacement reconciled: %v", err)
}
}
// An old worker paused between comparing a chunk and recording it must not
// record into (or delete from) the replacement reconciliation's set.
func TestChunkReconcile_OldWorkerCannotModifyReplacementSet(t *testing.T) {
var oldGen atomic.Uint64
atCompared, releaseOld, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
hook := func(stage string, gen uint64) {
switch {
case stage == "compared" && oldGen.CompareAndSwap(0, gen):
close(atCompared)
<-releaseOld
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
<-replHold
}
}
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
// Registered after the fixture: cleanups run last-in first-out, so the
// workers are released before the layer closes and waits for them.
t.Cleanup(func() {
for _, ch := range []chan struct{}{releaseOld, replHold} {
select {
case <-ch:
default:
close(ch)
}
}
})
select {
case <-atCompared:
case <-time.After(ctLocalBound):
t.Fatal("the first reconciliation never compared a chunk")
}
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
t.Fatal(err)
}
total := fx.layer.Stats().ReconcileTotal
close(releaseOld)
refusedOver(t, 300*time.Millisecond, "after the paused old worker resumed", func() error {
if st := fx.layer.Stats(); st.ReconcileTotal != total || st.ReconcileDone != 0 {
return fmt.Errorf("old worker modified the replacement set: done=%d/%d (total was %d)", st.ReconcileDone, st.ReconcileTotal, total)
}
return nil
})
close(replHold)
waitReconciledForTest(t, fx.layer)
}
+5
View File
@@ -337,6 +337,11 @@ type chunkLayerConfig struct {
// reconciler before each slice until a token is received or the
// channel is closed.
testReconcileHold chan struct{}
// testReconcileHook, set only by this package's tests, is called by a
// reconciliation worker with its generation before each slice
// ("batch"), after comparing a chunk and before recording the result
// ("compared"), and before certifying the result ("finish").
testReconcileHook func(stage string, gen uint64)
}
// chunkCutStats describes one cut. The periodic-cut work fills it; a zero