mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Merge main into fsync latency breakdown; retain recovery and timing status
This commit is contained in:
commit
882f8aed6a
33 files changed
+2087
-76
No files matched your search
@@ -55,6 +55,7 @@ type flags struct {
|
||||
launcherCHAPUserKey string
|
||||
launcherCHAPSecretKey string
|
||||
failbackRuntimeRPC bool
|
||||
workspaceMaxClockSkew time.Duration
|
||||
workspaceRPC bool
|
||||
workspaceHEADBase string
|
||||
frontendPublicationRuntimeHTTP bool
|
||||
@@ -104,6 +105,7 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.launcherCHAPUserKey, "launcher-iscsi-chap-username-key", "chapUsername", "Kubernetes Secret key for generated blockvolume iSCSI CHAP username")
|
||||
fs.StringVar(&f.launcherCHAPSecretKey, "launcher-iscsi-chap-secret-key", "chapSecret", "Kubernetes Secret key for generated blockvolume iSCSI CHAP secret")
|
||||
fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence")
|
||||
fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound")
|
||||
fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs")
|
||||
fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc")
|
||||
fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only")
|
||||
@@ -123,6 +125,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
if err := nvme.ValidateMaxH2CDataLength(uint32(f.launcherNVMeMaxH2CDataLength)); err != nil {
|
||||
return flags{}, fmt.Errorf("--launcher-nvme-max-h2c-data-length=%d invalid: %w", f.launcherNVMeMaxH2CDataLength, err)
|
||||
}
|
||||
if f.workspaceMaxClockSkew <= 0 || f.workspaceMaxClockSkew >= 60*time.Second {
|
||||
return flags{}, fmt.Errorf("--workspace-max-clock-skew must be positive and less than 60s")
|
||||
}
|
||||
if f.authorityStore == "" {
|
||||
return flags{}, fmt.Errorf("--authority-store is required")
|
||||
}
|
||||
@@ -173,6 +178,7 @@ func run(f flags) int {
|
||||
Topology: topo,
|
||||
Freshness: authority.FreshnessConfig{FreshnessWindow: f.freshnessWindow, PendingGrace: f.pendingGrace},
|
||||
ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: f.expectedSlotsPerVol},
|
||||
WorkspaceMaxClockSkew: f.workspaceMaxClockSkew,
|
||||
FailbackRuntimeRPC: f.failbackRuntimeRPC,
|
||||
FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP,
|
||||
FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWorkspaceClockSkewFlag(t *testing.T) {
|
||||
for _, v := range []string{"0s", "-1s", "60s", "90s"} {
|
||||
if _, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v}); err == nil {
|
||||
t.Errorf("accepted %s", v)
|
||||
}
|
||||
}
|
||||
for _, v := range []string{"1s", "20s", "59s"} {
|
||||
f, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v})
|
||||
want, _ := time.ParseDuration(v)
|
||||
if err != nil || f.workspaceMaxClockSkew != want {
|
||||
t.Fatal(v, f.workspaceMaxClockSkew, err)
|
||||
}
|
||||
}
|
||||
f, err := parseFlags([]string{"--authority-store", "unused"})
|
||||
if err != nil || f.workspaceMaxClockSkew != 20*time.Second {
|
||||
t.Fatal("default", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
|
||||
)
|
||||
|
||||
// Issue #51: a real SmartWAL WAL-slot corruption (the issue's mutation:
|
||||
// the last byte of a committed record's 32-byte slot, i.e. its record CRC)
|
||||
// must not let the volume start Ready.
|
||||
|
||||
// writeSmartWAL writes the given LBAs in order through the real provider,
|
||||
// syncs and closes it, and returns the store's path.
|
||||
func writeSmartWAL(t *testing.T, cfg durable.ProviderConfig, lbas []uint32) string {
|
||||
t.Helper()
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := dp.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, lba := range lbas {
|
||||
data := make([]byte, 4096)
|
||||
data[0], data[1] = byte(0xA0+i), byte(lba)
|
||||
if _, err := st.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := st.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dp.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filepath.Join(cfg.StorageRoot, "v1.bin")
|
||||
}
|
||||
|
||||
// corruptSlotCRC flips the last byte (the record CRC) of the newest slot
|
||||
// recorded for lba, as the issue's QA mutation did (target_record_offset
|
||||
// +31).
|
||||
func corruptSlotCRC(t *testing.T, path string, lba uint32) {
|
||||
t.Helper()
|
||||
_, records, err := smartwal.InspectRecords(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var off int64 = -1
|
||||
var lsn uint64
|
||||
for _, r := range records {
|
||||
if r.LBA == lba && r.LSN >= lsn {
|
||||
off, lsn = r.Offset, r.LSN
|
||||
}
|
||||
}
|
||||
if off < 0 {
|
||||
t.Fatalf("no record for LBA %d", lba)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := make([]byte, 1)
|
||||
if _, err := f.ReadAt(b, off+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := f.WriteAt(b, off+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func startAfterCorruption(t *testing.T, cfg durable.ProviderConfig) (durableStartupOutcome, *spyHost) {
|
||||
t.Helper()
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dp.Close() })
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
t.Logf("outcome=%v reported=%v evidence=%q err=%v", outcome, h.reported, evidence, err)
|
||||
return outcome, h
|
||||
}
|
||||
|
||||
// The issue's schedule: LBA 0 was written twice; the newer record's slot
|
||||
// is corrupted, so recovery drops it as torn and falls back to the older
|
||||
// record, whose CRC no longer matches the extent. Current main fails
|
||||
// closed (85d93753): wal_corrupt, readiness blocked.
|
||||
func TestDurableStartup_Issue51_CorruptNewerSlotIsWALCorrupt(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 0})
|
||||
corruptSlotCRC(t, path, 0)
|
||||
outcome, h := startAfterCorruption(t, cfg)
|
||||
if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 {
|
||||
t.Fatalf("corrupt newer slot: outcome=%v reported=%v blocked=%v; want faulted, wal_corrupt, readiness blocked", outcome, h.reported, h.blocked)
|
||||
}
|
||||
}
|
||||
|
||||
// claude05's ruling (A), 06:47Z: detection only for smartwal too. A
|
||||
// corrupted committed slot with later valid records starts as before
|
||||
// (ready), and the durable status carries the counted warning.
|
||||
func TestDurableStartup_Issue51_SmartWALHoleIsAWarningNotAnOutage(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 3})
|
||||
corruptSlotCRC(t, path, 1) // LSN 2; LSN 3 and 4 stay valid
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dp.Close()
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("smartwal hole: outcome=%v reported=%v evidence=%q err=%v; want ready", outcome, h.reported, evidence, err)
|
||||
}
|
||||
warned := false
|
||||
for _, st := range dp.DurableStatuses() {
|
||||
for _, w := range st.Warnings {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") && st.HolesSuspected == 1 {
|
||||
warned = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !warned {
|
||||
t.Fatalf("durable statuses %+v; want the counted %s warning", dp.DurableStatuses(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
|
||||
// Control: a torn tail (the newest slot bad, nothing valid after it)
|
||||
// still recovers: a power loss is not an outage.
|
||||
func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2})
|
||||
corruptSlotCRC(t, path, 2) // LSN 3, the newest
|
||||
outcome, h := startAfterCorruption(t, cfg)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("torn tail: outcome=%v reported=%v; want ready", outcome, h.reported)
|
||||
}
|
||||
}
|
||||
|
||||
// walstore interim (claude05's ruling 06:14Z): the same mid-history
|
||||
// corruption on a walstore volume does not become an outage: startup is
|
||||
// ready, and the durable status carries the typed warning.
|
||||
func TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16}
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
// A crashed walstore: entries synced, nothing checkpointed (the file
|
||||
// as it is right after Sync; a clean close would checkpoint).
|
||||
s, err := storage.CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xD0 + i)
|
||||
if _, err := s.Write(i, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashed, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
// Corrupt a payload byte of the second entry (walstore's WAL starts at
|
||||
// 4096; a one-block entry is 38+4096 bytes).
|
||||
crashed[4096+(38+4096)+38+100] ^= 0xFF
|
||||
if err := os.WriteFile(path, crashed, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dp.Close()
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("walstore hole: outcome=%v reported=%v evidence=%q err=%v; want ready (no outage)", outcome, h.reported, evidence, err)
|
||||
}
|
||||
warned := false
|
||||
for _, st := range dp.DurableStatuses() {
|
||||
for _, w := range st.Warnings {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") {
|
||||
warned = st.HolesSuspected == 1
|
||||
}
|
||||
}
|
||||
}
|
||||
if !warned {
|
||||
t.Fatalf("durable statuses %+v; want the %s warning, counted once", dp.DurableStatuses(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,7 @@ type Publisher struct {
|
||||
workspaceUncertain map[string]bool
|
||||
workspaceNow func() time.Time
|
||||
workspaceTTL time.Duration
|
||||
workspaceMaxClockSkew time.Duration
|
||||
workspaceLeaseDeadline map[string]time.Time
|
||||
}
|
||||
|
||||
|
||||
@@ -15,10 +15,11 @@ type WorkspaceHead struct {
|
||||
}
|
||||
|
||||
type WorkspaceLease struct {
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
ExpiresAtNS int64
|
||||
Revoking bool
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
ExpiresAtNS int64
|
||||
MaxClockSkewNS int64 `json:",omitempty"`
|
||||
Revoking bool
|
||||
}
|
||||
|
||||
type WorkspaceRevokeAck struct {
|
||||
@@ -70,6 +71,27 @@ func WithWorkspaceLeaseConfig(ttl time.Duration, now func() time.Time) Publisher
|
||||
}
|
||||
}
|
||||
|
||||
// WithWorkspaceMaxClockSkew configures the bound between clocks. Zero keeps
|
||||
// the default: two nominal TTL/3 renewal intervals. Existing grants retain
|
||||
// their persisted bound when configuration is reduced after a restart.
|
||||
func WithWorkspaceMaxClockSkew(skew time.Duration) PublisherOption {
|
||||
return func(p *Publisher) {
|
||||
if skew > 0 {
|
||||
p.workspaceMaxClockSkew = skew
|
||||
}
|
||||
}
|
||||
}
|
||||
func (p *Publisher) workspaceSkew(lease *WorkspaceLease) time.Duration {
|
||||
skew := p.workspaceMaxClockSkew
|
||||
if skew <= 0 {
|
||||
skew = p.workspaceTTL / 3 * 2
|
||||
}
|
||||
if lease != nil && time.Duration(lease.MaxClockSkewNS) > skew {
|
||||
skew = time.Duration(lease.MaxClockSkewNS)
|
||||
}
|
||||
return skew
|
||||
}
|
||||
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
@@ -96,7 +118,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
|
||||
}
|
||||
}
|
||||
lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano()}
|
||||
lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(s.Lease))}
|
||||
s.Lease = &lease
|
||||
if err := p.persistWorkspaceLocked(volume, s); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
@@ -291,6 +313,13 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil {
|
||||
return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease")
|
||||
}
|
||||
if q.Kind == "forced" {
|
||||
now := p.workspaceNow()
|
||||
skew := p.workspaceSkew(s.Lease)
|
||||
if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.workspaceLeaseDeadline[q.VolumeID].Add(skew)) {
|
||||
return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
}
|
||||
// A restart may resume the identical durable reservation; it never grants
|
||||
// a different request the reserved epoch.
|
||||
for idx, r := range s.Moves {
|
||||
@@ -311,11 +340,6 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen {
|
||||
return nil, 0, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK")
|
||||
}
|
||||
} else {
|
||||
now := p.workspaceNow()
|
||||
if now.UnixNano() < s.Lease.ExpiresAtNS || now.Before(p.workspaceLeaseDeadline[q.VolumeID]) {
|
||||
return nil, 0, fmt.Errorf("workspace forced move lease has not expired")
|
||||
}
|
||||
}
|
||||
max := maxPublishedEpochForVolume(p.state, q.VolumeID)
|
||||
for _, r := range s.Moves {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) {
|
||||
for _, restart := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "live", true: "restart-smaller-config"}[restart], func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
now := time.Unix(1000, 0)
|
||||
start := now
|
||||
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lease.MaxClockSkewNS != int64(4*time.Second) {
|
||||
t.Fatal("configured margin not in durable grant", lease)
|
||||
}
|
||||
boundary := start.Add(10 * time.Second)
|
||||
if restart {
|
||||
now = start.Add(7 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second))
|
||||
boundary = now.Add(6*time.Second + 4*time.Second)
|
||||
}
|
||||
q := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r"}
|
||||
now = boundary.Add(-time.Nanosecond)
|
||||
if _, err := p.MoveWorkspace(context.Background(), q, head); err == nil {
|
||||
t.Fatal("forced before skew boundary")
|
||||
}
|
||||
if len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("early move wrote journal")
|
||||
}
|
||||
now = boundary
|
||||
if _, err := p.MoveWorkspace(context.Background(), q, head); err != nil {
|
||||
t.Fatal("margin elapsed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,10 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) {
|
||||
if len(state.Moves) != 1 || state.Moves[0].Issued || state.Moves[0].NewEpoch != 2 {
|
||||
t.Fatalf("grant not durable before epoch: %+v", state)
|
||||
}
|
||||
if _, err := loaded.MoveWorkspace(context.Background(), req, head); err == nil {
|
||||
t.Fatal("restart resumed forced reservation before conservative skew barrier")
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
r, err := loaded.MoveWorkspace(context.Background(), req, head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -228,6 +228,11 @@ type VolumeStatus struct {
|
||||
// Chunk is the chunk layer's state and cut counters; walstore-chunk
|
||||
// volumes only.
|
||||
Chunk *ChunkStatus
|
||||
// Warnings are the store's typed recovery warnings (e.g.
|
||||
// wal_hole_suspected, issue #51); they do not change readiness.
|
||||
// HolesSuspected counts the recoveries that found a WAL hole.
|
||||
Warnings []string `json:",omitempty"`
|
||||
HolesSuspected uint64 `json:",omitempty"`
|
||||
}
|
||||
|
||||
// ChunkStatus is one walstore-chunk volume's chunk layer (B9 7.2-7.3).
|
||||
|
||||
@@ -276,6 +276,14 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
b.mu.Unlock()
|
||||
durableLSN, retainedLSN, headLSN := b.storage.Boundaries()
|
||||
evidence, _ := b.opEvidence.Load().(string)
|
||||
var warnings []string
|
||||
var holes uint64
|
||||
if w, ok := b.storage.(storage.RecoveryWarner); ok {
|
||||
warnings = w.RecoveryWarnings()
|
||||
}
|
||||
if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok {
|
||||
holes = c.HolesSuspected()
|
||||
}
|
||||
writeProfile := b.WriteProfile()
|
||||
if instrumented, ok := b.storage.(storage.WriteInstrumented); ok {
|
||||
storageProfile := instrumented.WriteInstrumentation()
|
||||
@@ -304,6 +312,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos
|
||||
}
|
||||
return VolumeStatus{
|
||||
Warnings: warnings,
|
||||
HolesSuspected: holes,
|
||||
VolumeID: volumeID,
|
||||
Path: path,
|
||||
Impl: impl,
|
||||
|
||||
@@ -3,6 +3,7 @@ package bootstrap
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
)
|
||||
@@ -14,14 +15,14 @@ import (
|
||||
// reload capability existed only in unit tests.
|
||||
//
|
||||
// Startup order matches sketch §7:
|
||||
// 1. acquire the single-owner store lock (refuse to start if held)
|
||||
// 2. open the file-per-volume store under the same directory
|
||||
// 3. construct the Publisher with WithStore(store), which runs
|
||||
// reload synchronously — surviving records populate
|
||||
// Publisher state, corrupt records go to LoadErrors()
|
||||
// 4. log any LoadErrors() at startup so operators see
|
||||
// reload-corruption events rather than having them stranded
|
||||
// inside the Publisher
|
||||
// 1. acquire the single-owner store lock (refuse to start if held)
|
||||
// 2. open the file-per-volume store under the same directory
|
||||
// 3. construct the Publisher with WithStore(store), which runs
|
||||
// reload synchronously — surviving records populate
|
||||
// Publisher state, corrupt records go to LoadErrors()
|
||||
// 4. log any LoadErrors() at startup so operators see
|
||||
// reload-corruption events rather than having them stranded
|
||||
// inside the Publisher
|
||||
//
|
||||
// The caller owns lifecycle: invoke Close() on process exit (or
|
||||
// via defer) to release the lock and close the store cleanly.
|
||||
@@ -43,8 +44,9 @@ type DurableAuthorityBootstrap struct {
|
||||
|
||||
// Options customizes durable-authority bootstrap wiring.
|
||||
type Options struct {
|
||||
PublishObserver authority.PublishObserver
|
||||
PublicationAdmission authority.PublicationAdmission
|
||||
WorkspaceMaxClockSkew time.Duration
|
||||
PublishObserver authority.PublishObserver
|
||||
PublicationAdmission authority.PublicationAdmission
|
||||
}
|
||||
|
||||
// Bootstrap performs the durable-authority startup sequence and
|
||||
@@ -53,9 +55,10 @@ type Options struct {
|
||||
// acquired or the store directory cannot be enumerated.
|
||||
//
|
||||
// Startup logs:
|
||||
// "durable authority lock acquired"
|
||||
// "durable authority reload: N records"
|
||||
// "durable authority reload skip: %v" (one per skip)
|
||||
//
|
||||
// "durable authority lock acquired"
|
||||
// "durable authority reload: N records"
|
||||
// "durable authority reload skip: %v" (one per skip)
|
||||
//
|
||||
// The logs are the promised operator/startup visibility of
|
||||
// LoadErrors() — architect round-5 finding #3.
|
||||
@@ -117,7 +120,7 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store
|
||||
if opts.PublishObserver != nil {
|
||||
pubOpts = append(pubOpts, authority.WithPublishObserver(opts.PublishObserver))
|
||||
}
|
||||
pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission))
|
||||
pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission), authority.WithWorkspaceMaxClockSkew(opts.WorkspaceMaxClockSkew))
|
||||
pub := authority.NewPublisher(directive, pubOpts...)
|
||||
|
||||
// Publisher's LoadErrors is the canonical source; prefer it
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
|
||||
@@ -67,8 +68,9 @@ type Config struct {
|
||||
|
||||
// WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be
|
||||
// obtained from the configured remote source, never from operator flags.
|
||||
WorkspaceRPC bool
|
||||
WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error)
|
||||
WorkspaceMaxClockSkew time.Duration
|
||||
WorkspaceRPC bool
|
||||
WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error)
|
||||
|
||||
// FrontendPublicationRuntimeHTTP enables the frontend publication runtime
|
||||
// HTTP surface. It is disabled by default and only confirms a post-failback
|
||||
@@ -170,6 +172,9 @@ func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBa
|
||||
//
|
||||
// Live loops (publisher.Run, host.Start, grpc.Serve) run in Start.
|
||||
func New(cfg Config) (*Host, error) {
|
||||
if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second {
|
||||
return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)")
|
||||
}
|
||||
if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") {
|
||||
return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store")
|
||||
}
|
||||
@@ -208,8 +213,9 @@ func New(cfg Config) (*Host, error) {
|
||||
}
|
||||
|
||||
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
|
||||
PublishObserver: h.recordAuthorityPublishedEvent,
|
||||
PublicationAdmission: h.admitWorkspacePublication,
|
||||
WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew,
|
||||
PublishObserver: h.recordAuthorityPublishedEvent,
|
||||
PublicationAdmission: h.admitWorkspacePublication,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("master.New: Bootstrap: %w", err)
|
||||
|
||||
@@ -73,7 +73,7 @@ func TestWorkspaceBindingsForcedRetiresOnlyAfterIssue(t *testing.T) {
|
||||
}
|
||||
|
||||
func workspaceBindingsMove(t *testing.T, forced bool) {
|
||||
cfg := Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
|
||||
}}
|
||||
h, err := New(cfg)
|
||||
@@ -127,7 +127,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) {
|
||||
}
|
||||
if forced {
|
||||
select {
|
||||
case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 20*time.Millisecond):
|
||||
case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader})
|
||||
h, err := New(Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -169,7 +169,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
|
||||
}
|
||||
} else {
|
||||
// Actual master lease expiry, no test clock and no revocation ACK.
|
||||
timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 20*time.Millisecond)
|
||||
timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type heldSkewLeaseClient struct {
|
||||
skewLeaseClient
|
||||
calls atomic.Int32
|
||||
initial *control.WorkspaceLeaseFact
|
||||
entered chan *control.WorkspaceLeaseFact
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (c *heldSkewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, opts ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) {
|
||||
reply, err := c.skewLeaseClient.RenewWorkspaceLease(ctx, id, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.calls.Add(1) == 1 {
|
||||
c.initial = reply
|
||||
return reply, nil
|
||||
}
|
||||
select {
|
||||
case c.entered <- reply:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-c.release:
|
||||
return reply, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
|
||||
for _, late := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "before-old-expiry", true: "after-old-expiry"}[late], func(t *testing.T) {
|
||||
store, err := authority.NewFileAuthorityStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
// Current-time clocks keep the guard's real RPC deadline in the future.
|
||||
start := time.Now()
|
||||
var masterNS, hostNS atomic.Int64
|
||||
masterNS.Store(start.UnixNano())
|
||||
hostNS.Store(start.UnixNano())
|
||||
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
|
||||
p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, masterNS.Load()) }), authority.WithWorkspaceMaxClockSkew(4*time.Second))
|
||||
seedSkewPublisher(t, p, dir)
|
||||
client := &heldSkewLeaseClient{skewLeaseClient: skewLeaseClient{p}, entered: make(chan *control.WorkspaceLeaseFact, 1), release: make(chan struct{})}
|
||||
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := g.Refresh(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldLease := *p.WorkspaceState("v").Lease
|
||||
oldEarly := start.Add(time.Duration(client.initial.ValidForNs))
|
||||
requestStart := start.Add(time.Second)
|
||||
hostNS.Store(requestStart.UnixNano())
|
||||
masterNS.Store(requestStart.UnixNano())
|
||||
done := make(chan struct{})
|
||||
var refreshErr error
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(client.release) }) }
|
||||
go func() { defer close(done); refreshErr = g.Refresh(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("held renewal unsettled")
|
||||
}
|
||||
})
|
||||
var reply *control.WorkspaceLeaseFact
|
||||
select {
|
||||
case reply = <-client.entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("renewal did not enter", ctx.Err())
|
||||
}
|
||||
renewed := *p.WorkspaceState("v").Lease
|
||||
freshEarly := requestStart.Add(time.Duration(reply.ValidForNs))
|
||||
if freshEarly.Sub(oldEarly) < time.Second || renewed.ExpiresAtNS <= oldLease.ExpiresAtNS || renewed.MaxClockSkewNS != int64(4*time.Second) {
|
||||
t.Fatal("fixture did not extend the real persisted grant", oldLease, renewed)
|
||||
}
|
||||
arrival := oldEarly.Add(-time.Second)
|
||||
if late {
|
||||
arrival = oldEarly.Add(freshEarly.Sub(oldEarly) / 2)
|
||||
}
|
||||
if !arrival.Before(freshEarly) || ctx.Err() != nil {
|
||||
t.Fatal("new-grant or context expiry would mask old-boundary check")
|
||||
}
|
||||
// Do not call Projection here: it must not pre-latch the old expiry.
|
||||
hostNS.Store(arrival.UnixNano())
|
||||
masterNS.Store(arrival.UnixNano())
|
||||
release()
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("held response did not settle", ctx.Err())
|
||||
}
|
||||
if late {
|
||||
if refreshErr == nil || g.Projection().Healthy {
|
||||
t.Fatal("late renewal revived lease after OLD early expiry while NEW grant remained future")
|
||||
}
|
||||
} else {
|
||||
if refreshErr != nil || !g.Projection().Healthy {
|
||||
t.Fatal("timely renewal refused", refreshErr)
|
||||
}
|
||||
hostNS.Store(oldEarly.Add(freshEarly.Sub(oldEarly) / 2).UnixNano())
|
||||
if !g.Projection().Healthy {
|
||||
t.Fatal("timely grant failed to extend old early expiry")
|
||||
}
|
||||
}
|
||||
q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}
|
||||
boundary := time.Unix(0, renewed.ExpiresAtNS).Add(time.Duration(renewed.MaxClockSkewNS))
|
||||
for _, when := range []time.Time{time.Unix(0, oldLease.ExpiresAtNS).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} {
|
||||
masterNS.Store(when.UnixNano())
|
||||
if _, err := p.MoveWorkspace(ctx, q, head); err == nil {
|
||||
t.Fatal("forced move ignored renewed expiry plus persisted margin")
|
||||
}
|
||||
if len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("refusal wrote journal")
|
||||
}
|
||||
}
|
||||
masterNS.Store(boundary.UnixNano())
|
||||
hostNS.Store(boundary.Add(-time.Second).UnixNano())
|
||||
grant, err := p.MoveWorkspace(ctx, q, head)
|
||||
if err != nil || !grant.Issued || grant.NewEpoch <= 1 || g.Projection().Healthy {
|
||||
t.Fatal("renewed boundary grant overlaps old admission", grant, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,14 @@ func workspaceError(err error) error {
|
||||
|
||||
func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact {
|
||||
// Client anchors this duration to its request START, not response arrival.
|
||||
// The host fences half a skew bound before the stored master expiry.
|
||||
// Never grant more than the server's configured 30s TTL after a restart.
|
||||
remaining := time.Until(time.Unix(0, l.ExpiresAtNS))
|
||||
skew := time.Duration(l.MaxClockSkewNS)
|
||||
// Older persisted leases predate the bound; use the production default.
|
||||
if skew <= 0 {
|
||||
skew = 20 * time.Second
|
||||
}
|
||||
remaining := time.Until(time.Unix(0, l.ExpiresAtNS).Add(-skew / 2))
|
||||
if remaining > 30*time.Second {
|
||||
remaining = 30 * time.Second
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type skewLeaseClient struct{ p *authority.Publisher }
|
||||
|
||||
func (c skewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) {
|
||||
l, err := c.p.RenewWorkspaceLease(ctx, id.VolumeId, id.ReplicaId, id.Epoch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return leaseFact(id.VolumeId, l), nil
|
||||
}
|
||||
func (skewLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) {
|
||||
panic("expiry must not ACK clean")
|
||||
}
|
||||
|
||||
func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) {
|
||||
for _, check := range []string{"master-margin", "host-early-fence"} {
|
||||
t.Run(check, func(t *testing.T) {
|
||||
store, err := authority.NewFileAuthorityStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
|
||||
start := time.Now()
|
||||
masterNow, hostNow := start, start
|
||||
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
|
||||
p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(3*time.Second, func() time.Time { return masterNow }))
|
||||
seedSkewPublisher(t, p, dir)
|
||||
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, skewLeaseClient{p}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return hostNow })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := g.Refresh(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease := p.WorkspaceState("v").Lease
|
||||
q := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}
|
||||
if check == "host-early-fence" {
|
||||
// Default skew is two nominal TTL/3 renewal intervals; host stops half that early.
|
||||
hostNow = start.Add(2 * time.Second)
|
||||
if g.Projection().Healthy {
|
||||
t.Fatal("old host serves past expiry minus half-skew")
|
||||
}
|
||||
} else {
|
||||
// Master advanced one tick farther than the old host since renewal.
|
||||
masterNow = time.Unix(0, lease.ExpiresAtNS)
|
||||
hostNow = start.Add(2900 * time.Millisecond)
|
||||
if _, err := p.MoveWorkspace(context.Background(), q, head); err == nil {
|
||||
t.Fatalf("forced grant before skew margin; old serving=%v", g.Projection().Healthy)
|
||||
}
|
||||
line, _ := p.VolumeAuthorityLine("v")
|
||||
if line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("early refusal changed authority/journal")
|
||||
}
|
||||
}
|
||||
masterNow = time.Unix(0, lease.ExpiresAtNS).Add(2 * time.Second)
|
||||
hostNow = start.Add(4 * time.Second)
|
||||
grant, err := p.MoveWorkspace(context.Background(), q, head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !grant.Issued || grant.NewEpoch <= 1 || g.Projection().Healthy {
|
||||
t.Fatal("overlapping old serving at new grant", grant)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type skewDirective struct{ asks chan authority.AssignmentAsk }
|
||||
|
||||
func (d *skewDirective) Next(ctx context.Context) (authority.AssignmentAsk, error) {
|
||||
select {
|
||||
case a := <-d.asks:
|
||||
return a, nil
|
||||
case <-ctx.Done():
|
||||
return authority.AssignmentAsk{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
func seedSkewPublisher(t *testing.T, p *authority.Publisher, d *skewDirective) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- p.Run(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("publisher unsettled")
|
||||
}
|
||||
})
|
||||
ch, unsub := p.Subscribe("v", "r")
|
||||
defer unsub()
|
||||
d.asks <- authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: authority.IntentBind}
|
||||
select {
|
||||
case info := <-ch:
|
||||
if info.Epoch != 1 {
|
||||
t.Fatal(info)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("initial authority not published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) {
|
||||
h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
defer closeTestMaster(t, h)
|
||||
if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedVerifiedExistingReplicaPlacement(t, h)
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, h.Publisher(), "vol-a")
|
||||
reply, err := (&services{host: h}).RenewWorkspaceLease(context.Background(), &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease := h.Publisher().WorkspaceState("vol-a").Lease
|
||||
if lease.MaxClockSkewNS != int64(4*time.Second) || reply.ValidForNs <= 0 || reply.ValidForNs > int64(28*time.Second) {
|
||||
t.Fatal("configuration not applied to host validity", lease, reply)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,10 @@ type StatusProjection struct {
|
||||
// CatchUp shows a supporting replica's catch-up progress while it is
|
||||
// not yet replica_ready; it is visible without being an alert.
|
||||
CatchUp *CatchUpStatus `json:",omitempty"`
|
||||
// Warnings are the durable store's typed recovery warnings (e.g.
|
||||
// wal_hole_suspected, issue #51). Visible, not an alert: they do not
|
||||
// change Healthy or the frontend's readiness.
|
||||
Warnings []string `json:",omitempty"`
|
||||
}
|
||||
|
||||
// CatchUpStatus is a supporting replica's catch-up state.
|
||||
@@ -477,7 +481,15 @@ func (s *StatusServer) statusProjection() StatusProjection {
|
||||
s.mu.Lock()
|
||||
p.Healthy = p.Healthy && !s.nvmePending
|
||||
p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending
|
||||
src := s.durableSource
|
||||
s.mu.Unlock()
|
||||
if src != nil { // outside s.mu: the provider takes its own lock
|
||||
for _, st := range src.DurableStatuses() {
|
||||
if st.VolumeID == p.VolumeID {
|
||||
p.Warnings = append(p.Warnings, st.Warnings...)
|
||||
}
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
// Issue #51 (walstore interim): the durable store's typed recovery warning
|
||||
// is visible on /status and does not change Healthy or readiness.
|
||||
func TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth(t *testing.T) {
|
||||
t.Run("not-ready replica", func(t *testing.T) {
|
||||
statusWarningsCase(t, NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil), false)
|
||||
})
|
||||
t.Run("healthy primary", func(t *testing.T) {
|
||||
// codex01's advisory: a healthy primary stays healthy with a warning.
|
||||
p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}}
|
||||
statusWarningsCase(t, NewAdapterProjectionView(p, "v1", "r1", stubProbe{yes: false}), true)
|
||||
})
|
||||
}
|
||||
|
||||
func statusWarningsCase(t *testing.T, view *AdapterProjectionView, wantHealthy bool) {
|
||||
s := NewStatusServer(view)
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
get := func() StatusProjection {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://" + addr + "/status?volume=v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var p StatusProjection
|
||||
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
before := get()
|
||||
if before.Healthy != wantHealthy || before.FrontendPrimaryReady != wantHealthy {
|
||||
t.Fatalf("before the warning: healthy=%t ready=%t; want %t", before.Healthy, before.FrontendPrimaryReady, wantHealthy)
|
||||
}
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{
|
||||
VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1,
|
||||
}}})
|
||||
after := get()
|
||||
if len(after.Warnings) != 1 || after.Warnings[0][:18] != "wal_hole_suspected" {
|
||||
t.Fatalf("/status warnings %v; want the wal_hole_suspected warning", after.Warnings)
|
||||
}
|
||||
if after.Healthy != before.Healthy || after.FrontendPrimaryReady != before.FrontendPrimaryReady {
|
||||
t.Fatalf("a warning changed health: before healthy=%t ready=%t, after healthy=%t ready=%t",
|
||||
before.Healthy, before.FrontendPrimaryReady, after.Healthy, after.FrontendPrimaryReady)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,8 @@ func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool {
|
||||
|
||||
// Refresh anchors validity to the request START. Reply latency can only shorten
|
||||
// the client's usable lease, never extend it past the master's grant window.
|
||||
// ValidForNs already excludes half the master-configured clock-skew margin;
|
||||
// until is the early self-fence deadline, not the raw ExpiresAtNs wall clock.
|
||||
func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
|
||||
g.operation.Lock()
|
||||
defer g.operation.Unlock()
|
||||
|
||||
@@ -50,6 +50,28 @@ func (d *dirtyMap) put(lba, walOffset, lsn uint64, length uint32) {
|
||||
d.putAt(lba, walOffset, 0, lsn, length)
|
||||
}
|
||||
|
||||
// putAtIfNewer is putAt for recovery replay: last writer wins by LSN, so
|
||||
// an older version of an LBA scanned after a newer one (range scan order
|
||||
// is physical, not LSN order) never replaces it.
|
||||
func (d *dirtyMap) putAtIfNewer(
|
||||
lba, walOffset uint64,
|
||||
dataOffset uint32,
|
||||
lsn uint64,
|
||||
length uint32,
|
||||
) {
|
||||
s := d.shard(lba)
|
||||
s.mu.Lock()
|
||||
if cur, ok := s.m[lba]; !ok || cur.lsn < lsn {
|
||||
s.m[lba] = dirtyEntry{
|
||||
walOffset: walOffset,
|
||||
dataOffset: dataOffset,
|
||||
lsn: lsn,
|
||||
length: length,
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (d *dirtyMap) putAt(
|
||||
lba, walOffset uint64,
|
||||
dataOffset uint32,
|
||||
|
||||
@@ -51,6 +51,11 @@ type flusher struct {
|
||||
flushes atomic.Uint64 // diagnostic
|
||||
bytesOut atomic.Uint64 // diagnostic
|
||||
instr flusherInstrumentation
|
||||
|
||||
// afterSnapshotForTest, when set, runs after the dirty-map snapshot is
|
||||
// taken and the publication lock released: the window in which a
|
||||
// concurrent append is not in this cycle's checkpoint. Tests only.
|
||||
afterSnapshotForTest func()
|
||||
}
|
||||
|
||||
type flusherConfig struct {
|
||||
@@ -164,6 +169,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
if f.afterSnapshotForTest != nil {
|
||||
f.afterSnapshotForTest()
|
||||
}
|
||||
finishCycle := f.instr.recordCycle(
|
||||
cycleStart, time.Since(snapshotStart), entries, store.sb.BlockSize,
|
||||
)
|
||||
@@ -220,11 +228,12 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
// with LSN <= maxLSN is in extent or superseded by a retained newer
|
||||
// WAL record. Concurrent writes remain dirty for the next cycle.
|
||||
if maxLSN > 0 {
|
||||
if err := store.persistCheckpoint(maxLSN); err != nil {
|
||||
// The released tail is persisted with the checkpoint, before the
|
||||
// writer may reuse those bytes.
|
||||
if err := store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize); err != nil {
|
||||
return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err)
|
||||
}
|
||||
if store.CheckpointLSN() >= maxLSN {
|
||||
store.wal.advanceTailPastEntry(maxLSNPhys, maxLSNEntrySize)
|
||||
store.mu.Lock()
|
||||
if maxLSN+1 > store.walTail {
|
||||
store.walTail = maxLSN + 1
|
||||
|
||||
@@ -16,6 +16,11 @@ type recoveryResult struct {
|
||||
WALTail uint64 // reconstructed logical byte tail of retained WAL
|
||||
TornEntries int // entries discarded due to CRC failure or truncation
|
||||
DefensiveScan bool // true when the superblock was empty and we scanned the whole region
|
||||
// HoleSuspected: a bad entry was followed by a valid later entry
|
||||
// (issue #51). Detection only: it changes nothing about what is
|
||||
// replayed. HoleDetail says where.
|
||||
HoleSuspected bool
|
||||
HoleDetail string
|
||||
}
|
||||
|
||||
// recoverWAL scans the WAL region and replays any entries that have
|
||||
@@ -50,12 +55,23 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
walSize := sb.WALSize
|
||||
checkpointLSN := sb.WALCheckpointLSN
|
||||
|
||||
type scanRange struct {
|
||||
start, end uint64 // physical positions within WAL
|
||||
}
|
||||
type scanRange = recoveryScanRange
|
||||
var ranges []scanRange
|
||||
// lastLSN is the highest LSN decoded so far (detection only).
|
||||
var lastLSN uint64
|
||||
|
||||
if logicalHead == logicalTail {
|
||||
if logicalHead == logicalTail && logicalHead%walSize != 0 {
|
||||
// The superblock records an empty WAL at this position (a full
|
||||
// checkpoint persists head == tail). Sync does not persist the
|
||||
// head, so later appends continue contiguously from here: scan
|
||||
// from it. Scanning from offset 0 would let a torn record wrapped
|
||||
// there hide the synced run behind it.
|
||||
start := logicalHead % walSize
|
||||
ranges = append(ranges, scanRange{start, walSize}, scanRange{0, start})
|
||||
result.DefensiveScan = true
|
||||
log.Printf("storage: recovery from an empty superblock window (head==tail=%d checkpoint=%d)",
|
||||
logicalHead, checkpointLSN)
|
||||
} else if logicalHead == logicalTail {
|
||||
// A pre-boundary-persistence crash can leave a wrapped retained
|
||||
// window while the superblock still says empty. Find the high
|
||||
// physical run from record footers, then scan high and low as
|
||||
@@ -93,7 +109,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range ranges {
|
||||
for ri, r := range ranges {
|
||||
pos := r.start
|
||||
for pos < r.end {
|
||||
remaining := r.end - pos
|
||||
@@ -119,6 +135,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
entrySize := uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > remaining {
|
||||
result.TornEntries++
|
||||
if err := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, nil); err != nil {
|
||||
return result, err
|
||||
}
|
||||
break
|
||||
}
|
||||
fullBuf := make([]byte, entrySize)
|
||||
@@ -129,6 +148,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
if err != nil {
|
||||
// Torn write or trailing zeros — stop scanning this range.
|
||||
result.TornEntries++
|
||||
if herr := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, err); herr != nil {
|
||||
return result, herr
|
||||
}
|
||||
break
|
||||
}
|
||||
highestEntryLSN := entry.LSN
|
||||
@@ -148,6 +170,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
}
|
||||
highestEntryLSN = entry.LSN + entry.Reserved - 1
|
||||
}
|
||||
if highestEntryLSN > lastLSN {
|
||||
lastLSN = highestEntryLSN
|
||||
}
|
||||
if highestEntryLSN <= checkpointLSN {
|
||||
pos += entrySize
|
||||
continue
|
||||
@@ -165,7 +190,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
case walEntryWrite:
|
||||
blocks := entry.Length / sb.BlockSize
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
dm.putAt(
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
entry.LSN, sb.BlockSize,
|
||||
)
|
||||
@@ -178,7 +203,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
if lsn <= checkpointLSN {
|
||||
continue
|
||||
}
|
||||
dm.putAt(
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
lsn, sb.BlockSize,
|
||||
)
|
||||
@@ -190,7 +215,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
blocks = 1
|
||||
}
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
dm.putAt(
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
entry.LSN, sb.BlockSize,
|
||||
)
|
||||
@@ -323,3 +348,111 @@ func previousValidWALRecord(
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// recoveryScanRange is a physical [start, end) span of the WAL region.
|
||||
type recoveryScanRange struct {
|
||||
start, end uint64
|
||||
}
|
||||
|
||||
func allZeroBytes(b []byte) bool {
|
||||
for _, c := range b {
|
||||
if c != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// laterValidEntry looks, from pos in ranges[ri] through the later ranges,
|
||||
// for an offset holding a valid WAL entry (it decodes, CRC included) whose
|
||||
// LSN is above minLSN. It runs only after a bad entry, so a linear resync
|
||||
// over the remaining WAL is acceptable; a cheap header prefilter keeps the
|
||||
// full decodes to plausible candidates.
|
||||
func laterValidEntry(fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos, minLSN uint64, blockSize uint32) (bool, uint64, error) {
|
||||
const window = 1 << 20
|
||||
hdr := uint64(walEntryHeaderSize)
|
||||
for i := ri; i < len(ranges); i++ {
|
||||
start, end := ranges[i].start, ranges[i].end
|
||||
if i == ri {
|
||||
start = pos
|
||||
}
|
||||
for p := start; p+hdr <= end; p += window {
|
||||
n := min(window+hdr, end-p)
|
||||
buf := make([]byte, n)
|
||||
if _, err := fd.ReadAt(buf, int64(walOffset+p)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read at %d: %w", p, err)
|
||||
}
|
||||
for q := uint64(0); q+hdr <= n && q < window; q++ {
|
||||
size, ok := plausibleEntryHeader(buf[q:q+hdr], minLSN, end-(p+q), blockSize)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
full := make([]byte, size)
|
||||
if _, err := fd.ReadAt(full, int64(walOffset+p+q)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read entry at %d: %w", p+q, err)
|
||||
}
|
||||
if _, err := decodeWALEntry(full); err == nil {
|
||||
return true, p + q, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, 0, nil
|
||||
}
|
||||
|
||||
// plausibleEntryHeader is the resync prefilter: a known record type, an
|
||||
// LSN above minLSN, and a length that fits in what remains.
|
||||
func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) (uint64, bool) {
|
||||
lsn := binary.LittleEndian.Uint64(h[0:8])
|
||||
if lsn <= minLSN {
|
||||
return 0, false
|
||||
}
|
||||
length := uint64(parseLengthFromHeader(h))
|
||||
size := uint64(walEntryHeaderSize)
|
||||
switch h[16] {
|
||||
case walEntryWrite, walEntryWriteBatch:
|
||||
if length == 0 || blockSize == 0 || length%uint64(blockSize) != 0 {
|
||||
return 0, false
|
||||
}
|
||||
size += length
|
||||
case walEntryTrim, walEntryBarrier:
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
if size > remaining {
|
||||
return 0, false
|
||||
}
|
||||
return size, true
|
||||
}
|
||||
|
||||
// detectHole notes a suspected WAL hole at a bad entry (issue #51;
|
||||
// claude05's ruling 2026-11-16 06:47Z: detection only). An all-zero
|
||||
// header is just the end of what was written. Otherwise, if a valid entry
|
||||
// with an LSN above minLSN (the highest decoded so far, or the checkpoint)
|
||||
// follows it, the hole is recorded as the typed warning
|
||||
// WarningWALHoleSuspected and logged. Nothing about the replay changes:
|
||||
// the caller stops this range exactly as before. A torn tail and a
|
||||
// corrupted record cannot be told apart without a synced watermark, hence
|
||||
// "suspected".
|
||||
func detectHole(result *recoveryResult, fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos uint64, header []byte, minLSN uint64, blockSize uint32, cause error) error {
|
||||
if allZeroBytes(header) || result.HoleSuspected {
|
||||
return nil
|
||||
}
|
||||
found, at, err := laterValidEntry(fd, walOffset, ranges, ri, pos+1, minLSN, blockSize)
|
||||
if err != nil {
|
||||
// Detection never changes the outcome: a failed look-ahead read
|
||||
// is logged, and recovery goes on exactly as before.
|
||||
log.Printf("storage: recovery hole detection at offset=%d skipped: %v", pos, err)
|
||||
return nil
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
result.HoleSuspected = true
|
||||
result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and a valid later entry (LSN > %d) follows at offset=%d", pos, minLSN, at)
|
||||
if cause != nil {
|
||||
result.HoleDetail += " (" + cause.Error() + ")"
|
||||
}
|
||||
log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail)
|
||||
return nil
|
||||
}
|
||||
@@ -37,13 +37,21 @@ import (
|
||||
// - per-block CRC stored alongside extent (extent stays raw blocks)
|
||||
// - cross-checking against any external snapshot
|
||||
func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, error) {
|
||||
records, err := r.scanValid()
|
||||
frontier, _, err := runRecoveryCounting(r, fd, extentBase, blockSize)
|
||||
return frontier, err
|
||||
}
|
||||
|
||||
// runRecoveryCounting is runRecovery that also reports how many populated
|
||||
// slots fail their record CRC (issue #51, detection only: they are
|
||||
// skipped exactly as before; see Store.Recover's warning).
|
||||
func runRecoveryCounting(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, int, error) {
|
||||
records, bad, err := r.scanSlots()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery scan: %w", err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery scan: %w", err)
|
||||
}
|
||||
if len(records) == 0 {
|
||||
log.Printf("smartwal: recovery: ring empty; nothing to verify")
|
||||
return 0, nil
|
||||
return 0, len(bad), nil
|
||||
}
|
||||
|
||||
// Last-writer-wins map. Records arrive sorted by LSN ascending,
|
||||
@@ -65,12 +73,12 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
data := make([]byte, blockSize)
|
||||
off := extentBase + int64(rec.LBA)*int64(blockSize)
|
||||
if _, err := fd.ReadAt(data, off); err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err)
|
||||
}
|
||||
if crc32.ChecksumIEEE(data) != rec.DataCRC32 {
|
||||
detail := fmt.Sprintf("trim CRC mismatch LSN=%d LBA=%d", rec.LSN, rec.LBA)
|
||||
log.Printf("smartwal: recovery %s — failing closed", detail)
|
||||
return 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
return 0, 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
}
|
||||
recovered++
|
||||
if rec.LSN > highestVerifiedLSN {
|
||||
@@ -82,14 +90,14 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
data := make([]byte, blockSize)
|
||||
off := extentBase + int64(rec.LBA)*int64(blockSize)
|
||||
if _, err := fd.ReadAt(data, off); err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err)
|
||||
}
|
||||
actual := crc32.ChecksumIEEE(data)
|
||||
if actual != rec.DataCRC32 {
|
||||
detail := fmt.Sprintf("CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x",
|
||||
rec.LSN, rec.LBA, rec.DataCRC32, actual)
|
||||
log.Printf("smartwal: recovery %s — failing closed", detail)
|
||||
return 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
return 0, 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
}
|
||||
recovered++
|
||||
if rec.LSN > highestVerifiedLSN {
|
||||
@@ -99,5 +107,5 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
|
||||
log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d",
|
||||
recovered, highestVerifiedLSN)
|
||||
return highestVerifiedLSN, nil
|
||||
return highestVerifiedLSN, len(bad), nil
|
||||
}
|
||||
@@ -60,23 +60,34 @@ func (r *ring) appendAt(lsn uint64, rec record) error {
|
||||
//
|
||||
// Used during recovery to rebuild the in-memory view.
|
||||
func (r *ring) scanValid() ([]record, error) {
|
||||
records, _, err := r.scanSlots()
|
||||
return records, err
|
||||
}
|
||||
|
||||
// scanSlots is scanValid that also returns the indexes of populated slots
|
||||
// (magic present) whose record CRC fails: torn or corrupted.
|
||||
func (r *ring) scanSlots() ([]record, []uint64, error) {
|
||||
totalSize := r.capacity * recordSize
|
||||
buf := make([]byte, totalSize)
|
||||
r.mu.Lock()
|
||||
_, err := r.fd.ReadAt(buf, r.base)
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("smartwal: ring scan read: %w", err)
|
||||
return nil, nil, fmt.Errorf("smartwal: ring scan read: %w", err)
|
||||
}
|
||||
var out []record
|
||||
var bad []uint64
|
||||
for i := uint64(0); i < r.capacity; i++ {
|
||||
off := i * recordSize
|
||||
rec, ok := decode(buf[off : off+recordSize])
|
||||
if !ok {
|
||||
if buf[off] == recordMagic {
|
||||
bad = append(bad, i)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, rec)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].LSN < out[j].LSN })
|
||||
return out, nil
|
||||
return out, bad, nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package smartwal
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func flipSlotCRC(t *testing.T, path string, lsn uint64) {
|
||||
t.Helper()
|
||||
_, records, err := InspectRecords(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, r := range records {
|
||||
if r.LSN != lsn {
|
||||
continue
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := make([]byte, 1)
|
||||
if _, err := f.ReadAt(b, r.Offset+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := f.WriteAt(b, r.Offset+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no record LSN %d", lsn)
|
||||
}
|
||||
|
||||
func warnsHole(s *Store) bool {
|
||||
for _, w := range s.RecoveryWarnings() {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// codex01's r1 P1, under claude05's 06:47Z ruling (detection only): a torn
|
||||
// slot accepted by one recovery stays a recoverable warning after a
|
||||
// frontier jump and a new synced write; nothing infers its generation from
|
||||
// its position in the ring.
|
||||
func TestSmartWALTornSlotSurvivesAFrontierJump(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "s.sw")
|
||||
s, err := CreateStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, lba := range []uint32{0, 1} { // LSN 1, 2
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xE0 + i)
|
||||
if _, err := s.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flipSlotCRC(t, path, 2) // LSN 2 torn
|
||||
|
||||
s, err = OpenStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("first recovery: %v; want the torn tail accepted", err)
|
||||
}
|
||||
firstWarned, firstHoles := warnsHole(s), s.HolesSuspected()
|
||||
s.AdvanceFrontier(4)
|
||||
data := make([]byte, 4096)
|
||||
data[0] = 0xEF
|
||||
if _, err := s.Write(2, data); err != nil { // LSN 5
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s, err = OpenStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("second recovery after the frontier jump: %v; want recovered (the old torn slot is not corruption)", err)
|
||||
}
|
||||
if !firstWarned || firstHoles != 1 || !warnsHole(s) {
|
||||
t.Fatalf("warnings: first %t (%d), second %v; want the counted %s both times", firstWarned, firstHoles, s.RecoveryWarnings(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
@@ -52,6 +53,11 @@ const defaultWALSlots = 65536
|
||||
// the same LBA from different goroutines are NOT serialized at this
|
||||
// layer — callers must order their own per-LBA writes.
|
||||
type Store struct {
|
||||
// recoveryWarnings and holesSuspected: the last Recover's typed
|
||||
// warnings, and how many recoveries saw bad slots (issue #51).
|
||||
recoveryWarnings []string
|
||||
holesSuspected uint64
|
||||
|
||||
path string
|
||||
fd *os.File
|
||||
hdr *header
|
||||
@@ -176,16 +182,41 @@ func openInitialized(path string, f *os.File, hdr *header) (*Store, error) {
|
||||
// Recover rebuilds the in-memory LSN counter from the ring buffer.
|
||||
// Idempotent: calling twice on the same on-disk state yields the
|
||||
// same result.
|
||||
// RecoveryWarnings returns the last Recover's typed warnings.
|
||||
func (s *Store) RecoveryWarnings() []string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return append([]string(nil), s.recoveryWarnings...)
|
||||
}
|
||||
|
||||
// HolesSuspected counts the recoveries that saw populated slots failing
|
||||
// their record CRC.
|
||||
func (s *Store) HolesSuspected() uint64 {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.holesSuspected
|
||||
}
|
||||
|
||||
func (s *Store) Recover() (uint64, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return 0, errors.New("smartwal: Recover after Close")
|
||||
}
|
||||
frontier, err := runRecovery(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize))
|
||||
frontier, bad, err := runRecoveryCounting(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Detection only (issue #51): populated slots whose record CRC fails
|
||||
// were skipped as before. Without a synced watermark a torn tail and
|
||||
// a corrupted committed record cannot be told apart, so this is a
|
||||
// "suspected" warning that changes nothing else.
|
||||
s.recoveryWarnings = nil
|
||||
if bad > 0 {
|
||||
s.holesSuspected++
|
||||
s.recoveryWarnings = []string{fmt.Sprintf("%s: %d populated WAL slot(s) fail their record CRC (a torn tail or a corrupted record; not distinguishable without a synced watermark)", storage.WarningWALHoleSuspected, bad)}
|
||||
log.Printf("smartwal: recovery %s", s.recoveryWarnings[0])
|
||||
}
|
||||
if frontier >= s.nextLSN {
|
||||
s.nextLSN = frontier + 1
|
||||
}
|
||||
|
||||
@@ -31,7 +31,16 @@ type walWriter struct {
|
||||
walSize uint64 // size of the WAL region in bytes
|
||||
logicalHead uint64 // monotonic write position
|
||||
logicalTail uint64 // monotonic flush position
|
||||
instr *writeInstrumentation
|
||||
// durableTail is the tail in the last fsynced superblock. The writer
|
||||
// overwrites only bytes released by it (claude05's S3 ruling,
|
||||
// 2026-11-16): bytes the on-disk superblock still declares retained
|
||||
// are never reused, so a torn new record cannot land inside the
|
||||
// persisted [tail, head) and hide a record recovery needs.
|
||||
// durablePending: the bounds were rebuilt by recovery and are not yet
|
||||
// persisted; nothing is reusable until they are.
|
||||
durableTail uint64
|
||||
durablePending bool
|
||||
instr *writeInstrumentation
|
||||
|
||||
// Optional batch pwrite fault seam; nil uses the real file.
|
||||
batchWriteAt func([]byte, int64) (int, error)
|
||||
@@ -47,6 +56,7 @@ func newWALWriter(fd *os.File, walOffset, walSize, head, tail uint64, instr *wri
|
||||
walSize: walSize,
|
||||
logicalHead: head,
|
||||
logicalTail: tail,
|
||||
durableTail: tail,
|
||||
instr: instr,
|
||||
}
|
||||
}
|
||||
@@ -55,6 +65,15 @@ func (w *walWriter) physicalPos(logical uint64) uint64 { return logical % w.walS
|
||||
|
||||
func (w *walWriter) used() uint64 { return w.logicalHead - w.logicalTail }
|
||||
|
||||
// spaceUsed is what the space checks count: everything from the durable
|
||||
// tail on. Bytes released only in memory are not reusable yet.
|
||||
func (w *walWriter) spaceUsed() uint64 {
|
||||
if w.durablePending || w.durableTail > w.logicalHead {
|
||||
return w.walSize
|
||||
}
|
||||
return w.logicalHead - w.durableTail
|
||||
}
|
||||
|
||||
// append writes one entry and returns the WAL-relative offset where
|
||||
// it was placed. If the entry would straddle the end of the WAL
|
||||
// region, a padding entry is written first and the real entry starts
|
||||
@@ -83,7 +102,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) {
|
||||
remaining := w.walSize - physHead
|
||||
if remaining < entryLen {
|
||||
// Pad to end of region and wrap.
|
||||
if w.used()+remaining+entryLen > w.walSize {
|
||||
if w.spaceUsed()+remaining+entryLen > w.walSize {
|
||||
return 0, errWALFull
|
||||
}
|
||||
if err := w.writePadding(remaining, physHead); err != nil {
|
||||
@@ -95,7 +114,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) {
|
||||
w.logicalHead += remaining
|
||||
physHead = 0
|
||||
}
|
||||
if w.used()+entryLen > w.walSize {
|
||||
if w.spaceUsed()+entryLen > w.walSize {
|
||||
return 0, errWALFull
|
||||
}
|
||||
absOffset := int64(w.walOffset + physHead)
|
||||
@@ -253,7 +272,12 @@ func boundedPendingCapacity(lengths []uint64) int {
|
||||
func (w *walWriter) planAppendBatchLengths(lengths []uint64) ([]uint64, uint64, error) {
|
||||
localHead := w.logicalHead
|
||||
offsets := make([]uint64, 0, len(lengths))
|
||||
used := func() uint64 { return localHead - w.logicalTail }
|
||||
used := func() uint64 {
|
||||
if w.durablePending || w.durableTail > localHead {
|
||||
return w.walSize
|
||||
}
|
||||
return localHead - w.durableTail
|
||||
}
|
||||
for _, entryLen := range lengths {
|
||||
physHead := w.physicalPos(localHead)
|
||||
remaining := w.walSize - physHead
|
||||
@@ -368,6 +392,8 @@ func (w *walWriter) reset() {
|
||||
defer w.mu.Unlock()
|
||||
w.logicalHead = 0
|
||||
w.logicalTail = 0
|
||||
w.durableTail = 0
|
||||
w.durablePending = false
|
||||
}
|
||||
|
||||
func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error {
|
||||
@@ -381,9 +407,49 @@ func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error {
|
||||
}
|
||||
w.logicalHead = head
|
||||
w.logicalTail = tail
|
||||
w.durablePending = true // until the caller persists these bounds
|
||||
return nil
|
||||
}
|
||||
|
||||
// bounds returns head and tail from one snapshot.
|
||||
func (w *walWriter) bounds() (head, tail uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.logicalHead, w.logicalTail
|
||||
}
|
||||
|
||||
// tailPastEntry is the tail that advanceTailPastEntry would set, without
|
||||
// moving it (the caller persists it first).
|
||||
func (w *walWriter) tailPastEntry(entryPhys, entryLen uint64) uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
physTail := w.physicalPos(w.logicalTail)
|
||||
var distanceToEntry uint64
|
||||
if entryPhys >= physTail {
|
||||
distanceToEntry = entryPhys - physTail
|
||||
} else {
|
||||
distanceToEntry = w.walSize - physTail + entryPhys
|
||||
}
|
||||
advance := distanceToEntry + entryLen
|
||||
if advance > w.used() {
|
||||
return w.logicalTail
|
||||
}
|
||||
return w.logicalTail + advance
|
||||
}
|
||||
|
||||
// tailPersisted records that a superblock with WAL tail = tail is fsynced:
|
||||
// the writer's tail moves there (never backward) and the bytes before it
|
||||
// become reusable.
|
||||
func (w *walWriter) tailPersisted(tail uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if tail > w.logicalTail {
|
||||
w.logicalTail = tail
|
||||
}
|
||||
w.durableTail = tail
|
||||
w.durablePending = false
|
||||
}
|
||||
|
||||
func (w *walWriter) head() uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
@@ -420,5 +486,5 @@ func (w *walWriter) usedFraction() float64 {
|
||||
if w.walSize == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(w.used()) / float64(w.walSize)
|
||||
return float64(w.spaceUsed()) / float64(w.walSize)
|
||||
}
|
||||
@@ -45,6 +45,11 @@ import (
|
||||
// - Online resize
|
||||
// - Compaction (the WAL is bounded but periodic checkpoints free space)
|
||||
type WALStore struct {
|
||||
// recoveryWarnings and holesSuspected: the last Recover's typed
|
||||
// warnings, and how many recoveries found a WAL hole (issue #51).
|
||||
recoveryWarnings []string
|
||||
holesSuspected uint64
|
||||
|
||||
fileSyncLatency iolatency.Histogram
|
||||
metadata BlockMetadata // immutable before publication
|
||||
|
||||
@@ -371,8 +376,21 @@ func (s *WALStore) writeExtentUnlocked(lba uint32, data []byte) error {
|
||||
// the in-memory checkpoint advances, because the caller may recycle
|
||||
// the corresponding WAL bytes immediately after this method returns.
|
||||
func (s *WALStore) persistCheckpoint(highestLSN uint64) error {
|
||||
return s.persistCheckpointReleasing(highestLSN, 0, 0, false)
|
||||
}
|
||||
|
||||
// persistCheckpointAndRelease is persistCheckpoint that also releases the
|
||||
// WAL bytes through the entry at entryPhys (entryLen bytes long) when the
|
||||
// checkpoint reaches highestLSN. The released tail is persisted in the
|
||||
// same superblock before the writer may reuse those bytes.
|
||||
func (s *WALStore) persistCheckpointAndRelease(highestLSN, entryPhys, entryLen uint64) error {
|
||||
return s.persistCheckpointReleasing(highestLSN, entryPhys, entryLen, true)
|
||||
}
|
||||
|
||||
func (s *WALStore) persistCheckpointReleasing(highestLSN, entryPhys, entryLen uint64, release bool) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
requested := highestLSN
|
||||
// Clamp the proposed checkpoint to the recycle floor reported
|
||||
// by an external coordinator (e.g., the recovery package's
|
||||
// PeerShipCoordinator). When a replica is in an active rebuild
|
||||
@@ -386,26 +404,39 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if highestLSN <= s.checkpointLSN {
|
||||
advance := highestLSN > s.checkpointLSN
|
||||
checkpoint := s.checkpointLSN
|
||||
if advance {
|
||||
checkpoint = highestLSN
|
||||
}
|
||||
// One snapshot of head and tail; the tail this flush releases is
|
||||
// persisted here, before the writer may reuse its bytes.
|
||||
head, tail := s.wal.bounds()
|
||||
if release && checkpoint >= requested {
|
||||
tail = s.wal.tailPastEntry(entryPhys, entryLen)
|
||||
}
|
||||
if !advance && tail == s.sb.WALTail {
|
||||
return nil
|
||||
}
|
||||
if s.metadata != nil {
|
||||
if err := s.metadata.BeforeCheckpointAdvance(highestLSN); err != nil {
|
||||
return fmt.Errorf("storage: block metadata before checkpoint %d: %w", highestLSN, err)
|
||||
if advance {
|
||||
if s.metadata != nil {
|
||||
if err := s.metadata.BeforeCheckpointAdvance(highestLSN); err != nil {
|
||||
return fmt.Errorf("storage: block metadata before checkpoint %d: %w", highestLSN, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The chunk layer's dirty bitmap must be durable before the checkpoint
|
||||
// (and so the WAL tail) can pass the entries it covers.
|
||||
if h := s.chunk.Load(); h != nil {
|
||||
if err := h.sink.BeforeCheckpointAdvance(highestLSN); err != nil {
|
||||
return fmt.Errorf("storage: chunk bitmap before checkpoint %d: %w", highestLSN, err)
|
||||
// The chunk layer's dirty bitmap must be durable before the checkpoint
|
||||
// (and so the WAL tail) can pass the entries it covers.
|
||||
if h := s.chunk.Load(); h != nil {
|
||||
if err := h.sink.BeforeCheckpointAdvance(highestLSN); err != nil {
|
||||
return fmt.Errorf("storage: chunk bitmap before checkpoint %d: %w", highestLSN, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sbCopy := *s.sb
|
||||
sbCopy.WALCheckpointLSN = highestLSN
|
||||
sbCopy.WALHead = s.wal.logicalHeadValue()
|
||||
sbCopy.WALTail = s.wal.logicalTailValue()
|
||||
sbCopy.WALCheckpointLSN = checkpoint
|
||||
sbCopy.WALHead = head
|
||||
sbCopy.WALTail = tail
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sbCopy.writeTo(buf); err != nil {
|
||||
return fmt.Errorf("storage: encode superblock: %w", err)
|
||||
@@ -426,10 +457,11 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("storage: fsync checkpoint superblock: %w", err)
|
||||
}
|
||||
s.checkpointLSN = highestLSN
|
||||
s.sb.WALCheckpointLSN = highestLSN
|
||||
s.checkpointLSN = checkpoint
|
||||
s.sb.WALCheckpointLSN = checkpoint
|
||||
s.sb.WALHead = sbCopy.WALHead
|
||||
s.sb.WALTail = sbCopy.WALTail
|
||||
s.wal.tailPersisted(sbCopy.WALTail)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -459,6 +491,32 @@ func (s *WALStore) FlusherInstrumentation() FlusherInstrumentationStatus {
|
||||
return s.flusher.instr.snapshot()
|
||||
}
|
||||
|
||||
// WarningWALHoleSuspected is the typed recovery warning for a WAL hole
|
||||
// followed by valid records (issue #51): reported on /status, it does not
|
||||
// change readiness.
|
||||
const WarningWALHoleSuspected = "wal_hole_suspected"
|
||||
|
||||
// RecoveryWarner is a store that reports warnings from its last Recover.
|
||||
type RecoveryWarner interface {
|
||||
RecoveryWarnings() []string
|
||||
}
|
||||
|
||||
// RecoveryWarnings returns the warnings of the last Recover (nil when it
|
||||
// found nothing to warn about).
|
||||
func (s *WALStore) RecoveryWarnings() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.recoveryWarnings...)
|
||||
}
|
||||
|
||||
// HolesSuspected counts the recoveries of this store that found a WAL hole
|
||||
// followed by valid records.
|
||||
func (s *WALStore) HolesSuspected() uint64 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.holesSuspected
|
||||
}
|
||||
|
||||
// Recover replays WAL entries past the last checkpoint into the dirty
|
||||
// map. After Recover, the in-memory state matches what an aborted
|
||||
// process would have left durably on disk.
|
||||
@@ -498,8 +556,33 @@ func (s *WALStore) Recover() (uint64, error) {
|
||||
s.dm.clear()
|
||||
return 0, NewWALIntegrityFailure(err, "restore walstore recovery bounds")
|
||||
}
|
||||
if res.WALHead != s.sb.WALHead || res.WALTail != s.sb.WALTail {
|
||||
// Persist the rebuilt bounds before any append: the writer never
|
||||
// reuses bytes the on-disk superblock still declares retained.
|
||||
sbCopy := *s.sb
|
||||
sbCopy.WALHead, sbCopy.WALTail = res.WALHead, res.WALTail
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sbCopy.writeTo(buf); err != nil {
|
||||
s.dm.clear()
|
||||
return 0, fmt.Errorf("storage: encode recovered superblock: %w", err)
|
||||
}
|
||||
if err := s.writeSuperblockMetadata(buf.bytes()); err != nil {
|
||||
s.dm.clear()
|
||||
return 0, fmt.Errorf("storage: pwrite recovered superblock: %w", err)
|
||||
}
|
||||
if err := s.syncSuperblockMetadata(); err != nil {
|
||||
s.dm.clear()
|
||||
return 0, fmt.Errorf("storage: fsync recovered superblock: %w", err)
|
||||
}
|
||||
}
|
||||
s.wal.tailPersisted(res.WALTail)
|
||||
s.sb.WALHead = res.WALHead
|
||||
s.sb.WALTail = res.WALTail
|
||||
s.recoveryWarnings = nil
|
||||
if res.HoleSuspected {
|
||||
s.holesSuspected++
|
||||
s.recoveryWarnings = []string{WarningWALHoleSuspected + ": " + res.HoleDetail}
|
||||
}
|
||||
recoveredHead := s.checkpointLSN
|
||||
if res.HighestLSN > recoveredHead {
|
||||
recoveredHead = res.HighestLSN
|
||||
@@ -1254,8 +1337,7 @@ func (s *WALStore) Close() error {
|
||||
// Persist current head/tail back into the superblock so a
|
||||
// subsequent OpenWALStore can find the WAL bounds without
|
||||
// relying solely on the defensive scan.
|
||||
s.sb.WALHead = s.wal.logicalHeadValue()
|
||||
s.sb.WALTail = s.wal.logicalTailValue()
|
||||
s.sb.WALHead, s.sb.WALTail = s.wal.bounds()
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := s.sb.writeTo(buf); err != nil {
|
||||
closeErrors = append(closeErrors, fmt.Errorf("storage: encode final superblock: %w", err))
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Issue #51, walstore (claude05's ruling 2026-11-16 06:47Z): pure
|
||||
// detection. A WAL hole followed by valid records is logged, counted and
|
||||
// reported as the typed warning wal_hole_suspected; nothing about what is
|
||||
// replayed, where replay stops, or whether the volume opens changes.
|
||||
|
||||
// writeSyncedEntries writes one block to each of lbas (in order), syncs,
|
||||
// and returns the store with auto-flush off (nothing checkpointed) and
|
||||
// each LBA's WAL offset.
|
||||
func writeSyncedEntries(t *testing.T, lbas []uint32) (*WALStore, string, map[uint64]uint64) {
|
||||
t.Helper()
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := CreateWALStore(path, 16, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i, lba := range lbas {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0xB0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, path, walOffsetsByLBA(s)
|
||||
}
|
||||
|
||||
func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
|
||||
offs := map[uint64]uint64{}
|
||||
for _, e := range s.dm.snapshot() {
|
||||
offs[e.LBA] = e.WALOffset
|
||||
}
|
||||
return offs
|
||||
}
|
||||
|
||||
// flipDataByte corrupts one payload byte of the entry at walOffset without
|
||||
// fixing its CRC.
|
||||
func flipDataByte(t *testing.T, s *WALStore, walOffset uint64) {
|
||||
t.Helper()
|
||||
off := int64(s.sb.WALOffset+walOffset) + int64(walEntryHeaderSize) + 100
|
||||
b := make([]byte, 1)
|
||||
if _, err := s.fd.ReadAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := s.fd.WriteAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func reopenAfterCrash(t *testing.T, s *WALStore, path string) (*WALStore, uint64, error) {
|
||||
t.Helper()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
lsn, rerr := r.Recover()
|
||||
return r, lsn, rerr
|
||||
}
|
||||
|
||||
func holeWarning(s *WALStore) bool {
|
||||
for _, w := range s.RecoveryWarnings() {
|
||||
if strings.HasPrefix(w, WarningWALHoleSuspected+":") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// (a) A corrupted mid-history synced record: recovery opens as before
|
||||
// (this range stops at it), and warns (typed, counted).
|
||||
func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[1])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 1 {
|
||||
t.Fatalf("Recover after a mid-history hole = %d, %v; want 1, nil (no outage)", lsn, err)
|
||||
}
|
||||
if !holeWarning(r) || r.HolesSuspected() != 1 {
|
||||
t.Fatalf("warnings %v holes %d; want %s, counted once", r.RecoveryWarnings(), r.HolesSuspected(), WarningWALHoleSuspected)
|
||||
}
|
||||
if got := r.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries replayed = %d; want 1 (nothing after the hole)", got)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0xB0))
|
||||
}
|
||||
|
||||
// (b) A power loss with an unsynced, out-of-order tail: an earlier
|
||||
// unsynced record torn, a later one written back. No outage: recovery
|
||||
// succeeds with the synced prefix intact.
|
||||
func TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail(t *testing.T) {
|
||||
s, path, _ := writeSyncedEntries(t, []uint32{0, 1}) // synced
|
||||
for i, lba := range []uint32{2, 3} { // unsynced
|
||||
if _, err := s.Write(lba, makeBlock(4096, byte(0xC0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[2]) // LBA 2 torn, LBA 3 reached the disk
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 2 {
|
||||
t.Fatalf("Recover after an out-of-order unsynced tail = %d, %v; want 2, nil", lsn, err)
|
||||
}
|
||||
for i, lba := range []uint32{0, 1} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// A torn tail (nothing valid after it) recovers without a warning.
|
||||
func TestWALStoreRecoverKeepsATornTail(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[3])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 3 || holeWarning(r) {
|
||||
t.Fatalf("Recover with a torn tail = %d, %v, warnings %v; want 3, nil, none", lsn, err, r.RecoveryWarnings())
|
||||
}
|
||||
for i, lba := range []uint32{0, 1, 2} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// (c) A hole across wrapped ranges (the older record at the high end
|
||||
// corrupted, the newer batch wrapped to offset 0) is no outage. Detection
|
||||
// here is per range: when the newer entries were scanned first there is
|
||||
// nothing "later" left to find, and telling generations apart across
|
||||
// ranges (like not replaying past such a hole) is the post-M4 watermark
|
||||
// work.
|
||||
func TestWALStoreRecoverWrappedHoleIsNoOutage(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+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)
|
||||
}
|
||||
if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[20])
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover = %v; want no outage", err)
|
||||
}
|
||||
_ = r
|
||||
}
|
||||
|
||||
// codex01's r1 P1: a damaged STALE record in a released range (below the
|
||||
// checkpoint, outside the retained window) must not cost retained data.
|
||||
// Layout: checkpoint 2, persisted tail at S, head at 3S; LSN 1 (released)
|
||||
// at 0 damaged, LSN 2 checkpointed at S, LSN 3 synced and unflushed at 2S.
|
||||
// LSN 3 must be replayed with its exact bytes.
|
||||
func TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2})
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
if offs[0] != 0 || offs[1] != S || offs[2] != 2*S {
|
||||
t.Fatalf("offsets %v; want 0, S, 2S", offs)
|
||||
}
|
||||
sb := *s.sb
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 2, S, 3*S
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flipDataByte(t, s, offs[0]) // the released LSN 1
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 2, makeBlock(blockSize, 0xB2)) // LSN 3, exact bytes
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The WAL writer may only overwrite bytes that the PERSISTED superblock tail
|
||||
// has released (claude05's ruling on the S3 torn-wrap finding, 2026-11-16
|
||||
// 07:33Z). Otherwise a torn new record can land inside the persisted
|
||||
// [tail, head) and stop recovery's scan before a synced record behind it.
|
||||
|
||||
func diskSuperblockForTest(t *testing.T, path string) superblock {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sb
|
||||
}
|
||||
|
||||
// The S3 trace, deterministic: LSN 2 is appended (and synced) while the
|
||||
// flush of LSN 1 runs, so the checkpoint covers LSN 1 and the persisted head
|
||||
// covers LSN 2. Synced LSN 3..5 follow; an unsynced LSN 6 wraps to offset 0
|
||||
// over the released LSN 1. The crash leaves LSN 6 torn and its end padding
|
||||
// not on disk (both unsynced pages: a plain crash, no corruption). Synced
|
||||
// LSN 2..5 must all be recovered.
|
||||
func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.afterSnapshotForTest = func() {
|
||||
s.flusher.afterSnapshotForTest = nil
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x11)); err != nil { // LSN 2, not in this flush
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sb := diskSuperblockForTest(t, path); sb.WALCheckpointLSN != 1 || sb.WALHead != 2*S {
|
||||
t.Fatalf("persisted ckpt=%d head=%d; want the flush of LSN 1 to cover LSN 2 in its head (2S=%d)", sb.WALCheckpointLSN, sb.WALHead, 2*S)
|
||||
}
|
||||
for lba := uint32(2); lba <= 4; lba++ { // LSN 3..5, synced
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
|
||||
t.Fatal(err)
|
||||
}
|
||||
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
|
||||
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
|
||||
}
|
||||
walOff := s.sb.WALOffset
|
||||
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
|
||||
}
|
||||
}
|
||||
|
||||
// A flush persists the tail it releases: the on-disk tail equals the
|
||||
// writer's tail after every checkpoint, and head/tail come from one snapshot.
|
||||
func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
for round := 0; round < 3; round++ {
|
||||
for lba := uint32(0); lba < 2; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x20+round))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb := diskSuperblockForTest(t, path)
|
||||
if tail, head := s.wal.logicalTailValue(), s.wal.logicalHeadValue(); sb.WALTail != tail || sb.WALHead != head {
|
||||
t.Fatalf("round %d: persisted tail=%d head=%d, writer tail=%d head=%d; the writer may reuse bytes the persisted tail still retains", round, sb.WALTail, sb.WALHead, tail, head)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery that moves the writer's bounds persists them before any append,
|
||||
// so the writer never reuses bytes the on-disk superblock still declares
|
||||
// retained.
|
||||
func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the superblock as an older flush left it: ckpt 1, tail before LSN 1
|
||||
sb := *s.sb
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, uint64(walEntryHeaderSize+blockSize)
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := diskSuperblockForTest(t, path)
|
||||
if tail, head := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != head {
|
||||
t.Fatalf("after Recover: persisted tail=%d head=%d, writer tail=%d head=%d; want the recovered bounds persisted", disk.WALTail, disk.WALHead, tail, head)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 1, makeBlock(blockSize, 0x31))
|
||||
}
|
||||
|
||||
// The writer's space check uses the durable tail: an in-memory release that
|
||||
// is not yet persisted does not make its bytes reusable.
|
||||
func TestWALWriterReuseIsBoundedByTheDurableTail(t *testing.T) {
|
||||
f, err := os.CreateTemp(t.TempDir(), "wal")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
const walSize = 4096
|
||||
entry := func() *walEntry {
|
||||
return &walEntry{LSN: 1, Type: walEntryWrite, LBA: 0, Length: 64, Data: make([]byte, 64)}
|
||||
}
|
||||
size, err := entry().encodedSize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := uint64(walSize) / uint64(size)
|
||||
w := newWALWriter(f, 0, walSize, 0, 0, nil)
|
||||
for i := uint64(0); i < n; i++ {
|
||||
if _, err := w.append(entry()); err != nil {
|
||||
t.Fatalf("append %d of %d: %v", i, n, err)
|
||||
}
|
||||
}
|
||||
w.advanceTailPastEntry(0, uint64(size)) // released in memory only
|
||||
if _, err := w.append(entry()); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("append into bytes released only in memory: err=%v; want errWALFull until the tail is persisted", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A full flush persists head == tail (an empty WAL at that position). Sync
|
||||
// does not persist the head, so synced appends follow it there; recovery must
|
||||
// scan from the persisted position, not from offset 0 (claude05's S3 trace:
|
||||
// a torn unsynced record wrapped to 0 must not hide the synced run).
|
||||
func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ { // LSN 2..5, synced
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
|
||||
t.Fatal(err)
|
||||
}
|
||||
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
|
||||
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
|
||||
}
|
||||
walOff := s.sb.WALOffset
|
||||
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 #159 P2-S2: the batch planner (with a padding wrap) counts from the
|
||||
// durable tail too: refused while the release is only in memory or the
|
||||
// bounds are recovery-pending, accepted once the tail is persisted.
|
||||
func TestWALWriterBatchReuseIsBoundedByTheDurableTail(t *testing.T) {
|
||||
const walSize = 4096
|
||||
mk := func(lsn uint64) walEntry {
|
||||
return walEntry{LSN: lsn, Type: walEntryWrite, LBA: lsn, Length: 64, Data: make([]byte, 64)}
|
||||
}
|
||||
e0 := mk(0)
|
||||
size, err := e0.encodedSize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sz := uint64(size)
|
||||
n := uint64(walSize) / sz // the last walSize%sz bytes force a padding wrap
|
||||
fill := func(t *testing.T) (*walWriter, *os.File) {
|
||||
f, err := os.CreateTemp(t.TempDir(), "wal")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = f.Close() })
|
||||
if err := f.Truncate(walSize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := newWALWriter(f, 0, walSize, 0, 0, nil)
|
||||
for i := uint64(0); i < n; i++ {
|
||||
e := mk(i + 1)
|
||||
if _, err := w.append(&e); err != nil {
|
||||
t.Fatalf("fill %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
return w, f
|
||||
}
|
||||
batch := func() []walEntry { return []walEntry{mk(n + 1), mk(n + 2)} }
|
||||
refused := func(t *testing.T, w *walWriter, f *os.File, why string) {
|
||||
t.Helper()
|
||||
head := w.logicalHeadValue()
|
||||
tailBytes := make([]byte, walSize-n*sz)
|
||||
if _, err := f.ReadAt(tailBytes, int64(n*sz)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.appendBatch(batch()); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("%s: appendBatch err=%v; want errWALFull", why, err)
|
||||
}
|
||||
after := make([]byte, len(tailBytes))
|
||||
if _, err := f.ReadAt(after, int64(n*sz)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.logicalHeadValue() != head || !bytes.Equal(after, tailBytes) {
|
||||
t.Fatalf("%s: a refused batch moved the head or wrote padding", why)
|
||||
}
|
||||
}
|
||||
accepted := func(t *testing.T, w *walWriter) {
|
||||
t.Helper()
|
||||
offs, err := w.appendBatch(batch())
|
||||
if err != nil {
|
||||
t.Fatalf("after the tail is persisted: appendBatch: %v", err)
|
||||
}
|
||||
if len(offs) != 2 || offs[0] != 0 || offs[1] != sz {
|
||||
t.Fatalf("offsets %v; want the batch wrapped to [0 %d]", offs, sz)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("released in memory only", func(t *testing.T) {
|
||||
w, f := fill(t)
|
||||
w.advanceTailPastEntry(0, 2*sz)
|
||||
refused(t, w, f, "in-memory release")
|
||||
w.tailPersisted(2 * sz)
|
||||
accepted(t, w)
|
||||
})
|
||||
t.Run("recovered bounds pending", func(t *testing.T) {
|
||||
w, f := fill(t)
|
||||
w.tailPersisted(2 * sz) // the space is free on disk; only the pending flag refuses it
|
||||
if err := w.restoreRecoveredBounds(n*sz, 2*sz); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refused(t, w, f, "durablePending")
|
||||
single := mk(n + 1)
|
||||
if _, err := w.append(&single); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("durablePending: append err=%v; want errWALFull", err)
|
||||
}
|
||||
w.tailPersisted(2 * sz)
|
||||
accepted(t, w)
|
||||
})
|
||||
}
|
||||
|
||||
// codex01 #159 P2-S3: when Recover cannot persist the rebuilt bounds (the
|
||||
// superblock write or its fsync fails), it fails, admits no append, and a
|
||||
// same-instance retry persists them; later writes survive a reopen exactly.
|
||||
func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
errInjected := errors.New("injected superblock failure")
|
||||
for _, seam := range []string{"write", "sync"} {
|
||||
t.Run(seam, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb := *s.sb // an older flush's superblock: the bounds Recover must rebuild and persist
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, S
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
crashed = true
|
||||
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
rClosed := false
|
||||
t.Cleanup(func() {
|
||||
if !rClosed {
|
||||
_ = r.Close()
|
||||
}
|
||||
})
|
||||
realWrite, realSync := r.writeSuperblockMetadata, r.syncSuperblockMetadata
|
||||
if seam == "write" {
|
||||
r.writeSuperblockMetadata = func([]byte) error { return errInjected }
|
||||
} else {
|
||||
r.syncSuperblockMetadata = func() error { return errInjected }
|
||||
}
|
||||
if _, err := r.Recover(); !errors.Is(err, errInjected) {
|
||||
t.Fatalf("Recover with a failing superblock %s: err=%v; want the injected failure", seam, err)
|
||||
}
|
||||
head := r.wal.logicalHeadValue()
|
||||
r.admissionTimeout = 200 * time.Millisecond
|
||||
if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err == nil {
|
||||
t.Fatal("Write after a failed Recover succeeded; want it refused until the bounds are persisted")
|
||||
}
|
||||
if r.wal.logicalHeadValue() != head {
|
||||
t.Fatalf("refused Write moved the WAL head %d -> %d", head, r.wal.logicalHeadValue())
|
||||
}
|
||||
|
||||
r.writeSuperblockMetadata, r.syncSuperblockMetadata = realWrite, realSync
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("same-instance Recover retry: %v", err)
|
||||
}
|
||||
disk := diskSuperblockForTest(t, path)
|
||||
if tail, h := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != h {
|
||||
t.Fatalf("after the retry: persisted tail=%d head=%d, writer tail=%d head=%d", disk.WALTail, disk.WALHead, tail, h)
|
||||
}
|
||||
r.admissionTimeout = 30 * time.Second
|
||||
if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
rClosed = true
|
||||
|
||||
q, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = q.Close() })
|
||||
if _, err := q.Recover(); err != nil {
|
||||
t.Fatalf("reopen Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, q, 1, makeBlock(blockSize, 0x31))
|
||||
assertRecoveryHardeningBlock(t, q, 5, makeBlock(blockSize, 0x55))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// claude05's condition (1) for any prefix-cut recovery rule (2026-11-16
|
||||
// 07:33Z): an intentional LSN gap must not drop synced entries above it. A
|
||||
// rebuild installs BASE through WriteExtentDirect (no LSN) and applies
|
||||
// WAL-lane entries with their real LSNs through ApplyEntry; the frontier
|
||||
// jump (AdvanceFrontier at MarkBaseComplete) is not persisted before them.
|
||||
// So a replica can hold a synced LSN 101 with a persisted checkpoint of 0 and
|
||||
// no LSN 1..100 anywhere. Recovery must keep it (a rule that replays only the
|
||||
// contiguous LSN prefix above the checkpoint keeps nothing here).
|
||||
func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
if err := s.WriteExtentDirect(0, makeBlock(blockSize, 0xBA)); err != nil { // BASE, no LSN
|
||||
t.Fatal(err)
|
||||
}
|
||||
live := makeBlock(blockSize, 0x65)
|
||||
if err := s.ApplyEntry(3, live, 101); err != nil { // session-live entry above the BASE hint
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ApplyEntry(4, makeBlock(blockSize, 0x66), 102); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
synced, err := s.Sync()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if synced < 102 {
|
||||
t.Fatalf("Sync frontier %d; want 102 (the applied entries are synced)", synced)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
crashed = true
|
||||
if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 {
|
||||
t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN)
|
||||
}
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 3, live)
|
||||
assertRecoveryHardeningBlock(t, r, 4, makeBlock(blockSize, 0x66))
|
||||
}
|
||||
|
||||
// diskSuperblockForGapTest reads the on-disk superblock with a plain file
|
||||
// read: no store, no flusher or committer.
|
||||
func diskSuperblockForGapTest(t *testing.T, path string) superblock {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sb
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Recovery is last-writer-wins by LSN (claude05's ruling (B), 2026-11-16
|
||||
// 06:47Z). Two valid versions of one LBA survive in the WAL; the persisted
|
||||
// head/tail predate the wrap, so the range scanned first holds the newer
|
||||
// version (wrapped to offset 0) and the range scanned later the older one.
|
||||
// Recovery must still serve the newer bytes.
|
||||
func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil { // checkpoint 3: head/tail persisted here
|
||||
t.Fatal(err)
|
||||
}
|
||||
older := makeBlock(blockSize, 0xA4)
|
||||
if _, err := s.Write(20, older); err != nil { // LSN 4, at the high end
|
||||
t.Fatal(err)
|
||||
}
|
||||
newer := makeBlock(blockSize, 0xB5)
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(20, [][]byte{newer, makeBlock(blockSize, 0xB6)}); err != nil { // LSN 5-6, wraps to 0
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e := recoverySnapshotEntriesByLBA(s.dm.snapshot())[20]; e.WALOffset != 0 || e.LSN != 5 {
|
||||
t.Fatalf("newest LBA 20 entry at offset %d LSN %d; want the wrapped batch at 0, LSN 5", e.WALOffset, e.LSN)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(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(20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != newer[0] {
|
||||
t.Fatalf("LBA 20 after recovery = %02x; want the newer version %02x (LSN 5), not the older %02x (LSN 4)", got[0], newer[0], older[0])
|
||||
}
|
||||
}
|
||||
@@ -28,3 +28,16 @@ for its result before ACK. Host shutdown fences admission synchronously.
|
||||
The host installation mutex latches this terminal fence even before a guard
|
||||
exists; a later-installed guard is born fenced. Its lock order is installation
|
||||
mutex then guard state mutex. Canceled renewal replies cannot publish a grant.
|
||||
|
||||
## Clock skew
|
||||
|
||||
`blockmaster --workspace-max-clock-skew` defaults to 20s (two nominal 10s
|
||||
renewal intervals for the 30s lease). Set a positive bound below 60s that
|
||||
covers the deployment's clock drift. The bound is persisted with each lease;
|
||||
a restart or smaller setting cannot shorten an outstanding grant's bound.
|
||||
The master grants a FORCED move only after both the stored expiry and its
|
||||
conservative restart deadline plus the full bound. `ValidForNs` in lease
|
||||
replies excludes half the bound. Hosts anchor that shortened duration to
|
||||
request start, self-fencing early without comparing remote wall-clock times.
|
||||
Delayed replies cannot extend admission. The bound is an operational clock
|
||||
assumption; arbitrarily stopped or unbounded clocks are not covered.
|
||||
Reference in new issue
Block a user