fix(storage): bind flush checkpoint and retirement to original recovery lifetime

This commit is contained in:
pingqiu committed 2026-11-17 08:34:59 -08:00
1 parent 99deddb4d6
commit 8af7760fbd
5 files changed
+160 -7

No files matched your search

+34 -3
View File
@@ -56,6 +56,8 @@ type flusher struct {
// taken and the publication lock released: the window in which a
// concurrent append is not in this cycle's checkpoint. Tests only.
afterSnapshotForTest func()
// Pauses after materialization/fsync, before map proof preparation. Tests only.
afterExtentSyncForTest func()
}
type flusherConfig struct {
@@ -167,6 +169,12 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// Hold the publication lock across all shards: a later shard must not
// include a write whose predecessor was omitted from an earlier shard.
// Release before WAL reads, extent writes or fsync.
// Bind materialization to the same Recover lifetime as this snapshot.
// Recover holds store.mu at both generation boundaries.
var recoveryGen uint64
if store.v3 != nil {
recoveryGen = store.v3.recoverGen.Load()
}
entries := store.dm.snapshot()
store.mu.RUnlock()
if len(entries) == 0 {
@@ -228,6 +236,10 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
return fmt.Errorf("flusher: fsync after extent writes: %w", syncErr)
}
if f.afterExtentSyncForTest != nil {
f.afterExtentSyncForTest()
}
// Step 3: advance the on-disk checkpoint to the highest LSN
// that was successfully flushed in this cycle. Because we
// processed the entire consistent snapshot, every entry
@@ -236,10 +248,16 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
if maxLSN > 0 {
// The released tail is persisted with the checkpoint, before the
// writer may reuse those bytes.
if err := store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize); err != nil {
var publishErr error
if store.v3 != nil {
publishErr = store.persistCheckpointV3(maxLSN, recoveryGen)
} else {
publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize)
}
if err := publishErr; err != nil {
return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err)
}
if store.CheckpointLSN() >= maxLSN {
if store.v3 == nil && store.CheckpointLSN() >= maxLSN {
store.mu.Lock()
if maxLSN+1 > store.walTail {
store.walTail = maxLSN + 1
@@ -257,7 +275,17 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// AND coverage, rather than merely refreshing W on an empty dirty map.
checkpoint := maxLSN // legacy behavior: remove the whole flushed snapshot
if store.v3 != nil {
checkpoint = store.CheckpointLSN()
// Serialize validation and LSN-only retirement with Recover. A new
// lifetime can reuse the same LBA, physical offset and LSN.
store.mu.Lock()
if !store.v3.flushLifetimeValidV3(recoveryGen) {
store.mu.Unlock()
return ErrMapCoverageStale
}
checkpoint = store.checkpointLSN
if checkpoint >= maxLSN && maxLSN+1 > store.walTail {
store.walTail = maxLSN + 1
}
}
for _, e := range entries {
if e.LSN > checkpoint {
@@ -265,6 +293,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
}
store.dm.compareAndDelete(e.LBA, e.LSN)
}
if store.v3 != nil {
store.mu.Unlock()
}
f.flushes.Add(1)
if store.v3 != nil {
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
+1 -1
View File
@@ -433,7 +433,7 @@ func (s *WALStore) persistCheckpointAndRelease(highestLSN, entryPhys, entryLen u
func (s *WALStore) persistCheckpointReleasing(highestLSN, entryPhys, entryLen uint64, release bool) error {
if s.v3 != nil {
return s.persistCheckpointV3(highestLSN)
return s.persistCheckpointV3(highestLSN, s.v3.recoverGen.Load())
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -49,7 +49,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati
return &preparedMapPublicationV3{candidate: c, proof: proof}, nil
}
func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN uint64) error {
func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) error {
v := s.v3
if err := s.stickyIOFault(); err != nil {
return err
@@ -87,6 +87,11 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN uint64) error {
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
// The candidate proof alone is insufficient: it was prepared after extent
// I/O and could belong to a newer Recover lifetime than those bytes.
if !v.flushLifetimeValidV3(recoveryGen) {
return ErrMapCoverageStale
}
wack := v.wack.Load()
if wack < cp {
return ErrMapCoverageStale
@@ -0,0 +1,108 @@
package storage
import (
"bytes"
"errors"
"sync"
"testing"
"time"
)
func TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
writeSynced(t, s, 1, 1) // W1, still in the WAL.
if lsn, err := s.Write(5, blk(0xA7)); err != nil || lsn != 2 {
t.Fatalf("write A: %d %v", lsn, err)
}
oldOff, _, _, _, ok := s.dm.get(5)
if !ok {
t.Fatal("missing A")
}
entered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{})
done := make(chan error, 1)
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
s.flusher.afterExtentSyncForTest = func() { close(entered); <-resume }
t.Cleanup(func() {
release()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("old flusher not joined")
}
})
go func() { defer close(joined); done <- s.flusher.flushOnce() }()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("old extent materialization not reached")
}
// Damage only the unacknowledged A record after its bytes reached extent.
// Recover keeps W1, drops/fences A, and reuses its LSN and physical offset.
pos := int64(s.sb.WALOffset + oldOff + walEntryPrefixSizeV3)
if _, err := s.fd.WriteAt([]byte{0xA6}, pos); err != nil {
t.Fatal(err)
}
if r, err := s.Recover(); err != nil || r != 1 {
t.Fatalf("recover drop: %d %v", r, err)
}
if lsn, err := s.Write(5, blk(0xB8)); err != nil || lsn != 2 {
t.Fatalf("write B: %d %v", lsn, err)
}
off, _, _, _, ok := s.dm.get(5)
if !ok || off != oldOff {
t.Fatal("control did not reuse A offset")
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
before := s.v3.pub.current()
release()
select {
case err := <-done:
if !errors.Is(err, ErrMapCoverageStale) {
t.Errorf("cross-Recover cycle accepted: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("old cycle did not finish")
}
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Fatal("old flusher result without join")
}
s.flusher.afterExtentSyncForTest = nil
if s.v3.pub.current() != before {
t.Error("old materialization published a new checkpoint/map")
}
if _, _, lsn, _, ok := s.dm.get(5); !ok || lsn != 2 {
t.Error("old cycle retired reused acknowledged B")
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
d := s.v3.pub.current()
if d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 {
t.Fatalf("fresh retry cp/C=%d/%d", d.CheckpointLSN, d.MapCoveredCheckpoint)
}
extent := make([]byte, 4096)
if _, err := s.fd.ReadAt(extent, int64(s.extentBase+5*4096)); err != nil || !bytes.Equal(extent, blk(0xB8)) {
t.Fatalf("fresh retry did not materialize B: %v", err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
r, err := openWALStoreV3ForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err = r.Recover(); err != nil {
t.Fatal(err)
}
got, err := r.Read(5)
if err != nil || !bytes.Equal(got, blk(0xB8)) {
t.Fatalf("reopen lost acknowledged B: %v", err)
}
}
+11 -2
View File
@@ -700,10 +700,16 @@ func (f *flusher) readDirtyRecordV3(e snapshotEntry) ([]byte, uint64, error) {
// leader role (syncMu), like Sync, refreshW and SetWMode, and cannot
// straddle a recovery. If a recovery lowered the acknowledged W below the
// prepared candidate meanwhile, this cycle publishes nothing.
func (s *WALStore) persistCheckpointV3(highestLSN uint64) error {
// flushLifetimeValidV3 is checked under syncMu at publication and store.mu
// at retirement. Recover/reset advance the same start/end generation.
func (v *walStoreV3State) flushLifetimeValidV3(gen uint64) bool {
return gen%2 == 0 && v.recoverGen.Load() == gen
}
func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error {
v := s.v3
if v.ownedMap != nil {
return s.persistOwnedMapCheckpointV3(highestLSN)
return s.persistOwnedMapCheckpointV3(highestLSN, recoveryGen)
}
if v.mapCandidate == nil {
return nil
@@ -718,6 +724,9 @@ func (s *WALStore) persistCheckpointV3(highestLSN uint64) error {
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
if !v.flushLifetimeValidV3(recoveryGen) {
return ErrMapCoverageStale
}
wack := v.wack.Load()
if wack < checkpoint {
return nil // a recovery lowered the frontier; retry next cycle