diff --git a/seaweed-block/core/storage/chunk_record_runtime.go b/seaweed-block/core/storage/chunk_record_runtime.go new file mode 100644 index 0000000000..2d84ebbc7d --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_runtime.go @@ -0,0 +1,213 @@ +package storage + +import ( + "errors" + "fmt" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// Kernel states as page bytes. Zero is never a state: a zeroed page fails. +var chunkRecordStateCodes = map[chunkkernel.Kind]uint8{ + chunkkernel.Absent: 1, + chunkkernel.Partial: 2, + chunkkernel.Unknown: 3, + chunkkernel.HashUnpublished: 4, + chunkkernel.HashPublished: 5, +} + +func chunkRecordStateCode(k chunkkernel.Kind) (uint8, error) { + c, ok := chunkRecordStateCodes[k] + if !ok { + return 0, fmt.Errorf("storage: chunk record: no code for kernel state %q", k) + } + return c, nil +} + +func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { + for k, c := range chunkRecordStateCodes { + if c == code { + return k, nil + } + } + return "", fmt.Errorf("%w: state code %d", errChunkRecordCheck, code) +} + +// chunkRecordRuntime is the record while the volume serves: every chunk's +// state in memory, changed only through the kernel, and the pages written on +// their own schedule, never tied to the store's checkpoint. +// +// - Every applied or ignored event marks its chunk's page dirty: a write +// that leaves the state as it was still moves the chunk's store position, +// so the page must be written before the header's G passes it. +// - An event whose effect is "page before bytes" (an evict) writes that page +// before Apply returns; the caller drops the bytes after. +// - Flush writes every dirty page, then the header with G = the applied +// position read before the pages, and only when every page is clean +// after them (pages before the header). A clean page keeps its own valid +// position; it is valid through the larger of G and its own. +// - THE APPLIED POSITION. Pages and G are valid through appliedPos(): the +// store position through which the shell has applied every write to the +// record. The shell raises it only after the Apply of each write at or +// below it; a write synced but not yet applied is never claimed. +// - Due says when the schedule asks for a Flush: maxEntries changed entries, +// or maxAge since the first unwritten change. +// - WriteThrough(end) writes the dirty pages of the chunks below end (the +// upgrade pass persists its cursor after it). +type chunkRecordRuntime struct { + dir string + chunks uint64 + epoch uint64 + // appliedPos: see THE APPLIED POSITION. + appliedPos func() uint64 + + maxEntries int + maxAge time.Duration + + testBeforePageWrite func(seg uint64) // tests only: runs outside the lock before a page write + + mu sync.Mutex + kinds []chunkkernel.Kind + hashes [][32]byte + valid []uint64 // per segment: the position its page was last written valid through + dirtyVer []uint64 // per segment: moves on every change; zero is clean + writtenVer []uint64 // per segment: the version last written + changed int + firstDirty time.Time +} + +func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() uint64, kinds []chunkkernel.Kind, hashes [][32]byte, valid []uint64) (*chunkRecordRuntime, error) { + segs := chunkRecordSegments(chunks) + if uint64(len(kinds)) != chunks || uint64(len(hashes)) != chunks || uint64(len(valid)) != segs { + return nil, errors.New("storage: chunk record: runtime shape does not match the volume") + } + return &chunkRecordRuntime{dir: dir, chunks: chunks, epoch: epoch, appliedPos: appliedPos, + maxEntries: 1000, maxAge: time.Minute, + kinds: kinds, hashes: hashes, valid: valid, + dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs)}, nil +} + +// Kind is a chunk's state. +func (r *chunkRecordRuntime) Kind(chunk uint64) chunkkernel.Kind { + r.mu.Lock() + defer r.mu.Unlock() + return r.kinds[chunk] +} + +// Apply runs one kernel event on a chunk. hash is the chunk's hash when the +// event records one (a Hash or a Fill that leaves the hash known). A refused +// event changes nothing and returns the kernel's caller defect. +func (r *chunkRecordRuntime) Apply(chunk uint64, ev chunkkernel.Event, arg chunkkernel.Arg, hash *[32]byte) (chunkkernel.Effect, error) { + r.mu.Lock() + if chunk >= r.chunks { + r.mu.Unlock() + return chunkkernel.None, fmt.Errorf("storage: chunk record: chunk %d out of range", chunk) + } + res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: r.kinds[chunk]}, ev, arg) + if err != nil { + r.mu.Unlock() + return chunkkernel.None, err + } + r.kinds[chunk] = res.State.Kind + switch res.State.Kind { + case chunkkernel.HashUnpublished, chunkkernel.HashPublished: + if hash != nil { + r.hashes[chunk] = *hash + } + default: + r.hashes[chunk] = [32]byte{} + } + seg := chunk / chunkRecordSegment + r.dirtyVer[seg]++ + if r.changed == 0 { + r.firstDirty = time.Now() + } + r.changed++ + r.mu.Unlock() + if eff == chunkkernel.PageBeforeBytes { + if err := r.writeSegments(seg, seg+1); err != nil { + return eff, err + } + } + return eff, nil +} + +// Due reports whether the schedule asks for a Flush now. +func (r *chunkRecordRuntime) Due(now time.Time) bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.changed >= r.maxEntries || (r.changed > 0 && now.Sub(r.firstDirty) >= r.maxAge) +} + +// WriteThrough writes the dirty pages that hold a chunk below end. +func (r *chunkRecordRuntime) WriteThrough(end uint64) error { + if end == 0 { + return nil + } + last := (min(end, r.chunks) + chunkRecordSegment - 1) / chunkRecordSegment + return r.writeSegments(0, last) +} + +// Flush writes every dirty page, then, if no page was dirtied meanwhile, the +// header with G = the applied position read before the pages. +func (r *chunkRecordRuntime) Flush() error { + g := r.appliedPos() + if err := r.writeSegments(0, chunkRecordSegments(r.chunks)); err != nil { + return err + } + r.mu.Lock() + clean := true + for seg := range r.dirtyVer { + if r.dirtyVer[seg] != r.writtenVer[seg] { + clean = false + } + } + if clean { + r.changed = 0 + } + r.mu.Unlock() + if !clean { + return nil // a page changed meanwhile: G stays until a Flush finds all clean + } + return writeChunkRecordFile(r.dir, chunkRecordHeaderName, encodeChunkRecordHeader(chunkRecordHeader{Epoch: r.epoch, Chunks: r.chunks, G: g})) +} + +// writeSegments writes the dirty pages of segments [from, to). Each page is +// snapshotted under the lock and written outside it; a change while it is +// written leaves the page dirty. +func (r *chunkRecordRuntime) writeSegments(from, to uint64) error { + for seg := from; seg < to; seg++ { + r.mu.Lock() + ver := r.dirtyVer[seg] + if ver == r.writtenVer[seg] { + r.mu.Unlock() + continue + } + pos := r.appliedPos() + p := &chunkRecordPage{Segment: seg, ValidThrough: pos, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(r.chunks, seg))} + for i := range p.Entries { + c := seg*chunkRecordSegment + uint64(i) + code, err := chunkRecordStateCode(r.kinds[c]) + if err != nil { + r.mu.Unlock() + return err + } + p.Entries[i] = chunkRecordEntry{State: code, Hash: r.hashes[c]} + } + r.mu.Unlock() + if h := r.testBeforePageWrite; h != nil { + h(seg) + } + if err := writeChunkRecordPage(r.dir, p); err != nil { + return err + } + r.mu.Lock() + if r.writtenVer[seg] < ver { + r.writtenVer[seg], r.valid[seg] = ver, pos + } + r.mu.Unlock() + } + return nil +} diff --git a/seaweed-block/core/storage/chunk_record_runtime_test.go b/seaweed-block/core/storage/chunk_record_runtime_test.go new file mode 100644 index 0000000000..9fe711bc7f --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_runtime_test.go @@ -0,0 +1,207 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +func newTestRuntime(t *testing.T, chunks uint64, pos *uint64) *chunkRecordRuntime { + t.Helper() + kinds := make([]chunkkernel.Kind, chunks) + for i := range kinds { + kinds[i] = chunkkernel.Absent + } + r, err := newChunkRecordRuntime(filepath.Join(t.TempDir(), "rec"), chunks, 7, func() uint64 { return *pos }, + kinds, make([][32]byte, chunks), make([]uint64, chunkRecordSegments(chunks))) + if err != nil { + t.Fatal(err) + } + return r +} + +// A chunk's state changes only through the kernel: the runtime's result is +// the kernel's, and a refused edge changes nothing. +func TestRecordRuntimeAppliesTheKernel(t *testing.T) { + pos := uint64(5) + r := newTestRuntime(t, 4, &pos) + steps := []struct { + ev chunkkernel.Event + arg string + }{{chunkkernel.Write, "some"}, {chunkkernel.Write, "all"}, {chunkkernel.Hash, "-"}, {chunkkernel.Commit, "-"}} + for _, st := range steps { + before := r.Kind(0) + want, _, kerr := chunkkernel.Step(chunkkernel.State{Kind: before}, st.ev, chunkkernel.Arg{Value: st.arg}) + _, err := r.Apply(0, st.ev, chunkkernel.Arg{Value: st.arg}, &[32]byte{9}) + if (err == nil) != (kerr == nil) { + t.Fatalf("%s %s on %s: runtime %v, kernel %v", st.ev, st.arg, before, err, kerr) + } + if kerr != nil { + t.Fatalf("%s %s on %s: the control steps must be legal: %v", st.ev, st.arg, before, kerr) + } + if r.Kind(0) != want.State.Kind { + t.Fatalf("%s %s on %s: runtime %s, kernel %s", st.ev, st.arg, before, r.Kind(0), want.State.Kind) + } + } + r.Apply(1, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + var defect *chunkkernel.CallerDefect + if _, err := r.Apply(1, chunkkernel.Hash, chunkkernel.Arg{Value: "-"}, nil); !errors.As(err, &defect) { + t.Fatalf("hash on a partial chunk answered %v, want the kernel's refusal", err) + } + if r.Kind(1) != chunkkernel.Partial { + t.Fatalf("a refused event changed the state to %s", r.Kind(1)) + } +} + +// An evict writes its chunk's page before Apply returns. +func TestRecordRuntimeEvictWritesThePageFirst(t *testing.T) { + pos := uint64(3) + r := newTestRuntime(t, 4, &pos) + if _, err := r.Apply(2, chunkkernel.Fill, chunkkernel.Arg{Value: "-"}, &[32]byte{1}); err != nil { + t.Fatal(err) + } + if r.Kind(2) != chunkkernel.HashPublished { + t.Skipf("fill gives %s; the evict control needs a published hash", r.Kind(2)) + } + eff, err := r.Apply(2, chunkkernel.Evict, chunkkernel.Arg{Value: "-"}, nil) + if err != nil || eff != chunkkernel.PageBeforeBytes { + t.Fatalf("evict: %s %v", eff, err) + } + b, err := os.ReadFile(filepath.Join(r.dir, chunkRecordPageName(0))) + if err != nil { + t.Fatalf("the evict returned before its page was written: %v", err) + } + p, err := decodeChunkRecordPage(b, 0) + if err != nil { + t.Fatal(err) + } + if k, _ := chunkRecordKind(p.Entries[2].State); k != chunkkernel.Absent { + t.Fatalf("page says %s after the evict, want A", k) + } +} + +// The schedule: due after maxEntries changes, or maxAge after the first. +func TestRecordRuntimeSchedule(t *testing.T) { + pos := uint64(1) + r := newTestRuntime(t, 8, &pos) + r.maxEntries, r.maxAge = 3, time.Hour + for c := uint64(0); c < 2; c++ { + r.Apply(c, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + } + if r.Due(time.Now()) { + t.Fatal("due before maxEntries") + } + r.Apply(2, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + if !r.Due(time.Now()) { + t.Fatal("not due at maxEntries") + } + if err := r.Flush(); err != nil { + t.Fatal(err) + } + if r.Due(time.Now()) { + t.Fatal("due after a clean flush") + } + r.Apply(3, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + if !r.Due(time.Now().Add(2 * time.Hour)) { + t.Fatal("not due after maxAge") + } +} + +// Flush writes the dirty pages, then the header at the applied position; a +// restart loads the same states and hashes. +func TestRecordRuntimeFlushIsLoadedBack(t *testing.T) { + pos := uint64(40) + r := newTestRuntime(t, 25000, &pos) + r.Apply(5, chunkkernel.Write, chunkkernel.Arg{Value: "all"}, nil) + r.Apply(5, chunkkernel.Hash, chunkkernel.Arg{Value: "-"}, &[32]byte{7}) + r.Apply(15000, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + if err := r.Flush(); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(r.dir, 25000, true, 7, pos) + if err != nil || !got.Complete || got.Header.G != pos { + t.Fatalf("flushed record: %+v %v", got, err) + } + if _, ok := got.Pages[2]; ok { + t.Fatal("a clean page was written") + } + k5, _ := chunkRecordKind(got.Pages[0].Entries[5].State) + k15, _ := chunkRecordKind(got.Pages[1].Entries[5000].State) + if k5 != r.Kind(5) || k15 != chunkkernel.Partial || got.Pages[0].Entries[5].Hash != [32]byte{7} { + t.Fatalf("loaded %s/%s hash %x", k5, k15, got.Pages[0].Entries[5].Hash[:1]) + } +} + +// WriteThrough writes only the dirty pages below end. +func TestRecordRuntimeWriteThrough(t *testing.T) { + pos := uint64(2) + r := newTestRuntime(t, 25000, &pos) + r.Apply(5, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + r.Apply(15000, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + if err := r.WriteThrough(10); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(r.dir, chunkRecordPageName(0))); err != nil { + t.Fatalf("page 0 not written: %v", err) + } + if _, err := os.Stat(filepath.Join(r.dir, chunkRecordPageName(1))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("page 1 written by a write-through below chunk 10: %v", err) + } + if _, err := os.Stat(filepath.Join(r.dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatal("a write-through wrote the header") + } +} + +// A write that leaves the state as it was still moves the chunk's store +// position: its page is written again, valid through the new position. +func TestRecordRuntimeAnUnchangedStateStillDirtiesThePage(t *testing.T) { + pos := uint64(10) + r := newTestRuntime(t, 4, &pos) + r.Apply(1, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + if err := r.Flush(); err != nil { + t.Fatal(err) + } + pos = 20 + r.Apply(1, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) // P stays P + if err := r.Flush(); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(r.dir, 4, true, 7, pos) + if err != nil || !got.Complete { + t.Fatalf("%+v %v", got, err) + } + if v := got.Pages[0].ValidThrough; v != 20 { + t.Fatalf("page valid through %d after a write at 20 that kept the state", v) + } +} + +// A page dirtied while Flush writes the pages: no header is written over it. +func TestRecordRuntimeNoHeaderOverAPageDirtiedDuringFlush(t *testing.T) { + pos := uint64(10) + r := newTestRuntime(t, 4, &pos) + r.Apply(1, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + once := true + r.testBeforePageWrite = func(uint64) { + if once { + once = false + r.Apply(2, chunkkernel.Write, chunkkernel.Arg{Value: "some"}, nil) + } + } + if err := r.Flush(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(r.dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a header was written over a page dirtied during the flush: %v", err) + } + r.testBeforePageWrite = nil + if err := r.Flush(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(r.dir, chunkRecordHeaderName)); err != nil { + t.Fatalf("no header after a clean flush: %v", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c2bb5b480e..9f26deee5b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -616,6 +616,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | +| `INV-CHUNK-RECORD-RUNTIME-001` | While serving, a chunk's state changes only through the kernel; every event dirties its page; an evict writes its page before the bytes go; pages and the header are valid through the applied position, and the header is written only when every page is clean. | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Flush`, `WriteThrough` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedule`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateStillDirtiesThePage`, `TestRecordRuntimeNoHeaderOverAPageDirtiedDuringFlush` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE |