diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 6cdd7dce6a..997a5cf97a 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -1,7 +1,7 @@ package volume // /chunk/*: the walstore-chunk control routes on the status listener -// (B9 W2 spec §2.1-§2.2, §3.1-§3.4, §3.6). They are off by default +// (B9 W2 spec §2.1-§2.2, §3.1-§3.4, §3.6). They are off by default // (EnableChunkControlEndpoint, flag --chunk-control-endpoint), share the // listener's loopback rule, take JSON request bodies (POST) or a // ?volume= query (GET), and answer failures with a typed JSON body @@ -36,7 +36,7 @@ type ChunkControl interface { Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) } -// ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). +// ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). type ChunkCutResponse struct { VolumeID string `json:"volumeID"` CutLSN uint64 `json:"cutLSN"` @@ -46,7 +46,7 @@ type ChunkCutResponse struct { Noop bool `json:"noop"` FullHash bool `json:"fullHash"` // Stats are the statistics the chunk layer measured for this cut - // (§3.1). A zero field is "not measured" or "none" (a Noop cut + // (§3.1). A zero field is "not measured" or "none" (a Noop cut // uploads nothing). Stats ChunkCutStatsBody `json:"stats"` } @@ -108,7 +108,7 @@ func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { } } -// ChunkSnapshotRequest is POST /chunk/snapshot's request (§3.2), without +// ChunkSnapshotRequest is POST /chunk/snapshot's request (§3.2), without // the volume and the timeout. type ChunkSnapshotRequest struct { Name string @@ -119,7 +119,7 @@ type ChunkSnapshotRequest struct { Class string // retention class: "semantic" or "pinned" } -// ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6). +// ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6). type ChunkDetachResponse struct { VolumeID string `json:"volumeID"` CutLSN uint64 `json:"cutLSN"` @@ -128,7 +128,7 @@ type ChunkDetachResponse struct { LastWrittenLSN uint64 `json:"lastWrittenLSN"` } -// snapshotBody is POST /chunk/snapshot's success body, exactly §3.2's fields. +// snapshotBody is POST /chunk/snapshot's success body, exactly §3.2's fields. type snapshotBody struct { VolumeID string `json:"volumeID"` Name string `json:"name"` @@ -149,7 +149,7 @@ type chunkErrorBody struct { Retryable bool `json:"retryable"` } -// The codes the routes add to the catalog's (B9 §2.2 plus the 2026-11-15 +// The codes the routes add to the catalog's (B9 §2.2 plus the 2026-11-15 // rulings: awaiting_assignment, reconciling, internal, lsn_behind, and the // transport errors bad_request, method_not_allowed, forbidden; not_found // for an unknown /chunk path). @@ -274,6 +274,8 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, chunkstore.CodeNotChunkVolume, false case errors.Is(err, context.DeadlineExceeded): return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true + case errors.Is(err, storage.ErrChunkCaptureRefused): + return http.StatusServiceUnavailable, "capture_refused", true case errors.Is(err, storage.ErrCutCOWAborted): return http.StatusServiceUnavailable, "cut_aborted", true default: @@ -527,7 +529,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) Noop: r.Noop, FullHash: r.FullHash, Stats: cutStatsBody(r.Stats)}, nil } -// Snapshot resolves the request against the catalog first (§3.2 step 1): +// Snapshot resolves the request against the catalog first (§3.2 step 1): // a retry of a recorded request returns that snapshot and another request // for the name gets snapshot_exists, both without cutting. Only a free name // is cut, and the HEAD that cut installed is stored. diff --git a/seaweed-block/core/host/volume/chunk_review271_test.go b/seaweed-block/core/host/volume/chunk_review271_test.go new file mode 100644 index 0000000000..82498ab8a5 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_review271_test.go @@ -0,0 +1,20 @@ +package volume + +import ( + "errors" + "github.com/seaweedfs/seaweed-block/core/storage" + "net/http" + "testing" +) + +func TestChunkBudgetAdmissionRefusalIsRetryable(t *testing.T) { + status, code, retry := chunkErrorCode(errors.Join(storage.ErrChunkCaptureRefused, errors.New("host full"))) + if status != http.StatusServiceUnavailable || code != "capture_refused" || !retry { + t.Fatalf("%d %s retry=%v", status, code, retry) + } + // Ownership always wins over a resource refusal. + status, _, retry = chunkErrorCode(errors.Join(storage.ErrChunkCaptureRefused, storage.ErrChunkLayerFenced)) + if status != http.StatusConflict || retry { + t.Fatalf("fenced: %d retry=%v", status, retry) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index cdd4774d98..81d22fe1ad 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -31,6 +31,13 @@ const ( var errCutCOWAborted = errors.New("storage: cut copy window aborted; retry cut") +var ( + errCutSaverCapacity = errors.New("storage: saver capacity") + errCutCOWCapacity = errors.New("storage: COW capacity") + errCutBudgetRevoked = errors.New("storage: cut budget revoked") + errCutUpload = errors.New("storage: cut upload failed") +) + type cutCOWEntry struct { mu sync.Mutex state uint8 @@ -289,7 +296,7 @@ func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) { case w.saverSlots <- struct{}{}: acquired = true default: - w.abort(fmt.Errorf("%w: saver memory capacity", errCutCOWAborted)) + w.abort(errors.Join(errCutCOWAborted, errCutSaverCapacity)) w.refs.Done() } if !acquired { @@ -344,7 +351,7 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error // The side file is sparse but its saved chunks are real bytes on the // volume's filesystem: abort the cut (retried) instead of filling it. w.mu.Unlock() - return fmt.Errorf("%w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, w.spillLimit) + return fmt.Errorf("%w: %w: limit %d bytes", errCutCOWAborted, errCutCOWCapacity, w.spillLimit) } else { w.spillBytes += w.chunkBytes } diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index b746e4fec6..2a44b50ecc 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -3,6 +3,7 @@ package storage import ( "context" "crypto/sha256" + "errors" "fmt" "sort" ) @@ -35,13 +36,31 @@ func hotChunkKeys(indices map[uint64]bool, recent map[uint64]uint64) []uint64 { return keys } -// Each wave owns at most one image per uploader. Classify that bounded set, -// durably name only its changed keys, then upload and discard its buffers. +// Preallocate immutable keys and durably root the candidate set once per round. +// Each wave owns at most one image per uploader; unused intent keys are harmless. +// Classify that bounded set, then upload and discard its buffers. // Later waves remain protected by COW; no whole-round payload is retained. func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) { workers, _, _ := l.cutPayloadWorkers() out := make([]capturedChunk, 0, len(batch)) var intents []string + keys := make([]string, len(batch)) + for i, idx := range batch { + keys[i] = l.newKey(idx) + } + intent := "" + ensureIntent := func() error { + if intent != "" { + return nil + } + id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) + if err != nil { + return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) + } + intent = id + intents = append(intents, id) + return nil + } for start := 0; start < len(batch); start += workers { order := batch[start:min(len(batch), start+workers)] wave := make([]capturedChunk, len(order)) @@ -52,7 +71,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } ref, had := head.Chunks[c.idx] if !c.zero && !(had && ref.SHA256 == c.sum) { - c.key = l.newKey(c.idx) + c.key = keys[start+i] c.size = len(c.data) } wave[i] = c @@ -61,22 +80,18 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, if err != nil { return nil, intents, err } - var keys []string var changed []int for i, c := range wave { if c.key != "" { - keys = append(keys, c.key) changed = append(changed, i) } } - if len(keys) > 0 { - id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) - if err != nil { - return nil, intents, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) + if len(changed) > 0 { + if err := ensureIntent(); err != nil { + return nil, intents, err } - intents = append(intents, id) for _, i := range changed { - wave[i].intent = id + wave[i].intent = intent } if err = l.uploadBatch(ctx, len(changed), func(ctx context.Context, i int) error { c := wave[changed[i]] @@ -86,7 +101,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, l.rememberPayload(c, head.Gen) return nil }); err != nil { - return nil, intents, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) + return nil, intents, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } } for i := range wave { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 43b9cad9a7..2825efd6d8 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -492,7 +492,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { return l.persistPresence() } -// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in +// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in // the dirty map (all chunks when a BASE block landed or the set is unknown). func (l *chunkLayerImpl) saveDirty() error { // Impl3's actual checkpoint caller persists its owned map after this @@ -843,7 +843,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if cause == nil { cause = errChunkCaptureRefused } - abort(fmt.Errorf("%w: budget revoked: %w", errCutCOWAborted, cause)) + abort(errors.Join(errCutCOWAborted, errCutBudgetRevoked, cause)) }) if admitErr != nil { abort(nil) @@ -1078,7 +1078,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch }); err != nil { l.abortCut(all) l.dropIntents(ctx, intents) - return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) + return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } for _, u := range uploads { next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} @@ -1431,6 +1431,23 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error l.stats.CASUnknown++ } } + abortReason := "" + switch { + case errors.Is(err, errCutSaverCapacity): + abortReason = "saver_capacity" + case errors.Is(err, errCutCOWCapacity): + abortReason = "cow_capacity" + case errors.Is(err, errCutBudgetRevoked): + abortReason = "budget_revoked" + case errors.Is(err, errCutUpload): + abortReason = "upload" + } + if abortReason != "" { + if l.stats.CutsAborted == nil { + l.stats.CutsAborted = map[string]uint64{} + } + l.stats.CutsAborted[abortReason]++ + } reason := "" switch { case err == nil && r.Noop: @@ -1476,6 +1493,10 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { for k, v := range l.stats.CutsRefused { out.CutsRefused[k] = v } + out.CutsAborted = make(map[string]uint64, len(l.stats.CutsAborted)) + for k, v := range l.stats.CutsAborted { + out.CutsAborted[k] = v + } out.PendingUnresolved = l.pending != nil out.DirtyChunks = len(l.dirty) out.Reconciling = l.hashMode @@ -2102,6 +2123,32 @@ func (l *chunkLayerImpl) Close() error { w.join() } l.wg.Wait() + l.stMu.Lock() + protected := make(map[string]bool, len(l.pendingIntents)) + if l.pending != nil { + for _, id := range l.pendingIntents { + protected[id] = true + } + } + var settled []string + for _, sc := range l.reusable { + if !protected[sc.intent] { + settled = append(settled, sc.intent) + } + } + for _, id := range l.leftoverIntents { + if !protected[id] { + settled = append(settled, id) + } + } + l.reusable = nil + l.leftoverIntents = nil + l.stMu.Unlock() + // Layer cancellation has joined all owners. Cleanup has a separate bounded + // context; an unknown CAS retains its roots for later epoch fencing. + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 3*time.Second) + l.dropIntents(cleanupCtx, settled) + cleanupCancel() close(l.closeDone) return nil } diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go index 49e61cea71..c5d04f0b35 100644 --- a/seaweed-block/core/storage/chunk_layer_intent_test.go +++ b/seaweed-block/core/storage/chunk_layer_intent_test.go @@ -1,7 +1,7 @@ package storage // The capture path's intents (W5): a cut that uploads chunks durably writes -// an intent naming exactly those keys before the first upload, and deletes +// an intent naming at least those keys before the first upload, and deletes // only its own intent once the outcome is settled: after a confirmed HEAD // CAS, or a clean abort. An uncertain CAS keeps the intent until a later // HEAD read settles it. @@ -84,8 +84,11 @@ func TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS(t *testing.T) { } keys := append([]string(nil), in.Keys...) sort.Strings(keys) - if got := uploadedKeys(ops); strings.Join(keys, ",") != strings.Join(got, ",") { - t.Fatalf("intent keys %q, uploaded keys %q", keys, got) + for _, key := range uploadedKeys(ops) { + i := sort.SearchStrings(keys, key) + if i == len(keys) || keys[i] != key { + t.Fatalf("uploaded key %q absent from intent %q", key, keys) + } } if in.Gen != 0 || in.Epoch != 1 || in.Holder != "host-a" { t.Fatalf("intent gen %d epoch %d holder %q, want the cut's base gen 0, epoch 1, host-a", in.Gen, in.Epoch, in.Holder) diff --git a/seaweed-block/core/storage/chunk_review271_test.go b/seaweed-block/core/storage/chunk_review271_test.go index 8f004511f3..a5af9dac39 100644 --- a/seaweed-block/core/storage/chunk_review271_test.go +++ b/seaweed-block/core/storage/chunk_review271_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "encoding/json" "errors" "path/filepath" "runtime" @@ -15,6 +16,7 @@ func TestCutPayloadIntentCountIndependentOfCandidates(t *testing.T) { _, f, l, _ := precopyLayer(t, 0, n) l.cfg.UploadConcurrency = 1 before := len(f.putIntents) + mark := len(f.stats().ops) r, err := l.Cut(ctTimeout(t)) if err != nil { t.Fatal(err) @@ -120,3 +122,22 @@ func TestV3ReadLargeBatchScratchIsBlockBounded(t *testing.T) { t.Fatalf("unrequested payload corruption: io=%v validation=%v", ioErr, verr) } } + +func TestCutAbortReasonsAreCountedAndCopied(t *testing.T) { + _, _, l, _ := precopyLayer(t, 0, 1) + for reason, cause := range map[string]error{"saver_capacity": errCutSaverCapacity, "cow_capacity": errCutCOWCapacity, "budget_revoked": errCutBudgetRevoked, "upload": errCutUpload} { + l.recordCut(chunkCutResult{}, chunkCutStats{}, errors.Join(errCutCOWAborted, cause)) + st := l.Stats() + if st.CutsAborted[reason] != 1 { + t.Fatalf("%s: %+v", reason, st.CutsAborted) + } + st.CutsAborted[reason] = 100 + if l.Stats().CutsAborted[reason] != 1 { + t.Fatal("Stats exposed mutable counter map") + } + } + raw, err := json.Marshal(l.Stats()) + if err != nil || !bytes.Contains(raw, []byte(`"CutsAborted"`)) { + t.Fatalf("status: %s %v", raw, err) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 7ac29cd9f5..656b01abec 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -78,7 +78,7 @@ import ( // fetch began); a local version always wins. // // The dirty bitmap stays off the write hot path. WAL entries carry their -// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL +// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL // entries above the checkpoint. The persisted bitmap may over-report, never // under-report. type chunkSink interface { @@ -137,7 +137,7 @@ type chunkDelta struct { // clears post-cut dirt. // // Restart or failover: a header equal to HEAD {RemoteLSN, Gen, Epoch} with -// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪ +// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪ // chunks of WAL entries above the checkpoint. A lost bitmap or any header // mismatch falls back to a per-chunk SHA-256 compare against HEAD's chunk // refs; only differing chunks are uploaded (Base == chunkBaseInstalling @@ -452,6 +452,7 @@ type chunkLayerStats struct { CutsNoop uint64 CutsFailed uint64 CutsRefused map[string]uint64 + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload CASConflicts uint64 CASUnknown uint64 PendingUnresolved bool @@ -548,7 +549,7 @@ var ( errChunkKeyInvalid = errors.New("storage: chunk key is not non-empty valid UTF-8") errChunkLayerDetached = errors.New("storage: chunk layer detached") errChunkCASOutcomeUnknown = errors.New("storage: chunk HEAD CAS outcome unknown") - // The causes a control plane reports as typed codes (B9 W2 §2.2). + // The causes a control plane reports as typed codes (B9 W2 §2.2). errChunkLayerClosed = errors.New("storage: chunk layer closed") errChunkBaseInstalling = errors.New("storage: chunk BASE install in progress") errChunkRemoteUnavailable = errors.New("storage: chunk remote unavailable") diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index e80146acc4..8f9fdf658b 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -11,12 +11,16 @@ import ( // putCaptured retries one immutable object, never a whole batch or HEAD CAS. // A lost binding reply can turn the next attempt into KeyExists: only exact // bytes read from that binding prove completion; a collision is terminal. -// Bound attempts per object, without imposing a deadline on legitimate work -// across the whole cut. All attempts still obey the caller's context. +// Keep the point and frozen buffer through transient failures until the cut +// context ends (deadline, Close or window abort), never a fresh point. func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { + // The per-object retry deadline also bounds a contextless cut. It retains + // the same point and buffer through a remote outage, never re-reads live data. + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() backoff := 100 * time.Millisecond var lastErr error - for attempt := 1; ; attempt++ { + for { if err := ctx.Err(); err != nil { return errors.Join(lastErr, err) } @@ -33,9 +37,6 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt } return errChunkKeyExists } - if attempt == 3 { - return lastErr - } timer := time.NewTimer(backoff) select { case <-ctx.Done(): diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index d8d2419af6..5061201bca 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -164,14 +164,14 @@ func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { assertEveryHeadIsPrefixImage(t, f, w) } -func TestChunkCutUploadAttemptBoundRetainsDirt(t *testing.T) { +func TestChunkCutUploadDeadlineBoundRetainsDirt(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}} layer := mustAttach(t, s, r, ctConfig(1)) w := newWriteLog() w.write(t, s, 0, 0x51) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 1700*time.Millisecond) defer cancel() if _, err := layer.Cut(ctx); err == nil { t.Fatal("persistent upload outage published") @@ -181,8 +181,8 @@ func TestChunkCutUploadAttemptBoundRetainsDirt(t *testing.T) { t.Fatalf("retry changed object keys: %v", r.calls) } for _, n := range r.calls { - if n != 3 { - t.Errorf("single object attempted %d times, want bounded 3", n) + if n <= 3 { + t.Errorf("single object attempted %d times, want >3 before deadline", n) } } r.mode = "ok" diff --git a/seaweed-block/core/storage/wal_entry_v3.go b/seaweed-block/core/storage/wal_entry_v3.go index b0f4a70aa9..8741289c30 100644 --- a/seaweed-block/core/storage/wal_entry_v3.go +++ b/seaweed-block/core/storage/wal_entry_v3.go @@ -152,8 +152,7 @@ func decodeWALEntryV3(buf []byte, blockSize uint32, numBlocks uint64) (walEntryV return walEntryV3{}, errEntryTruncated } le := binary.LittleEndian - e := walEntryV3{LSN: le.Uint64(buf[0:8]), BatchCount: le.Uint64(buf[8:16]), Type: buf[16], Flags: buf[17], LBA: le.Uint64(buf[18:26]), Length: le.Uint32(buf[26:30]), DurableLSN: le.Uint64(buf[30:38]), LogicalStart: le.Uint64(buf[38:46])} - copy(e.Nonce[:], buf[46:62]) + e := entryPrefixV3(buf) n, err := e.payloadSizeV3(blockSize, numBlocks) if err != nil { return walEntryV3{}, err @@ -182,3 +181,12 @@ func decodeWALEntryV3(buf []byte, blockSize uint32, numBlocks uint64) (walEntryV } return e, nil } + +// entryPrefixV3 decodes only the fixed prefix; payloadSizeV3 validates all +// geometry before either a whole-record allocation or a bounded block scan. +func entryPrefixV3(buf []byte) walEntryV3 { + le := binary.LittleEndian + e := walEntryV3{LSN: le.Uint64(buf[0:8]), BatchCount: le.Uint64(buf[8:16]), Type: buf[16], Flags: buf[17], LBA: le.Uint64(buf[18:26]), Length: le.Uint32(buf[26:30]), DurableLSN: le.Uint64(buf[30:38]), LogicalStart: le.Uint64(buf[38:46])} + copy(e.Nonce[:], buf[46:62]) + return e +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 78c4524ba5..912bdf63ce 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "fmt" + "hash/crc32" "io" "os" "sync" @@ -991,13 +992,56 @@ func (s *WALStore) readDirtyV3Observed(lba uint32, recordAttempt func()) (data [ // io.EOF (a file shorter than its geometry) is substrate I/O too. verr is a // record that was read but does not validate as the resolved write. func (s *WALStore) readRecordV3(lba uint32, walRelOff uint64, dataOff uint32, lsn uint64) (data []byte, ioErr, verr error) { - e, _, ioErr, verr := readWholeRecordV3(s.fd, recordGeometryV3{s.sb.WALOffset, s.sb.WALSize, s.sb.BlockSize, s.sb.VolumeSize}, walRelOff) - if ioErr != nil || verr != nil { - return nil, ioErr, verr + // Validate the entire record while retaining only one block of scratch. + // A legal batch can be much larger than the capturing chunk and its budget. + if walRelOff+walEntryHeaderSizeV3 > s.sb.WALSize { + return nil, nil, errEntryTruncated } - data, err := blockOfRecordV3(e, uint64(lba), dataOff, lsn, s.sb.BlockSize) + var prefix [walEntryPrefixSizeV3]byte + base := int64(s.sb.WALOffset + walRelOff) + if _, err := s.fd.ReadAt(prefix[:], base); err != nil { + return nil, err, nil + } + e := entryPrefixV3(prefix[:]) + n, err := e.payloadSizeV3(s.sb.BlockSize, s.sb.VolumeSize/uint64(s.sb.BlockSize)) if err != nil { - return nil, nil, fmt.Errorf("storage: v3 WAL read at %d: %w", walRelOff, err) + return nil, nil, err + } + if walRelOff+walEntryHeaderSizeV3+n > s.sb.WALSize { + return nil, nil, errEntryTruncated + } + count := uint64(1) + if e.Type == walEntryWriteBatch { + count = e.BatchCount + } else if e.Type != walEntryWrite { + return nil, nil, errInvalidEntry + } + idx := uint64(dataOff) / uint64(s.sb.BlockSize) + if dataOff%s.sb.BlockSize != 0 || idx >= count || e.LBA+idx != uint64(lba) || e.LSN+idx != lsn { + return nil, nil, fmt.Errorf("%w: v3 dirty record identity", errInvalidEntry) + } + scratch := make([]byte, s.sb.BlockSize) + data = make([]byte, s.sb.BlockSize) + crc := crc32.Update(0, walEntryCRC32CV3, prefix[:]) + for off := uint64(0); off < n; off += uint64(len(scratch)) { + part := scratch[:min(uint64(len(scratch)), n-off)] + if _, err := s.fd.ReadAt(part, base+walEntryPrefixSizeV3+int64(off)); err != nil { + return nil, err, nil + } + crc = crc32.Update(crc, walEntryCRC32CV3, part) + if off == uint64(dataOff) { + copy(data, part) + } + } + var footer [8]byte + if _, err := s.fd.ReadAt(footer[:], base+walEntryPrefixSizeV3+int64(n)); err != nil { + return nil, err, nil + } + if binary.LittleEndian.Uint32(footer[4:]) != uint32(walEntryHeaderSizeV3+n) { + return nil, nil, fmt.Errorf("%w: v3 EntrySize", errInvalidEntry) + } + if binary.LittleEndian.Uint32(footer[:4]) != crc { + return nil, nil, errCRCMismatch } return data, nil, nil }