diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index f243ee2769..63281469e6 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -331,7 +331,7 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error // No window lock spans the host callback: it may revoke this or another cut. if w.budget != nil { if err := w.budget.reserve(w.chunkBytes); err != nil { - return fmt.Errorf("%w: COW budget reservation: %w", errCutCOWAborted, err) + return fmt.Errorf("%w: COW budget reservation: %w", errors.Join(errCutCOWAborted, errCutBudgetRevoked), err) } } if hook := w.layer.testCOWSave; hook != nil { @@ -396,7 +396,7 @@ func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []ui if lba >= uint64(l.s.NumBlocks()) { break } - b, local, err := l.readLocalBlock(lba, w) + b, local, err := l.readLocalBlock(lba, w, buf[int(i)*l.blockSize:int(i+1)*l.blockSize]) if err != nil { return nil, nil, err } @@ -415,10 +415,10 @@ func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []ui // ZERO. It never calls the miss hook. The order is safe against a concurrent // flush (dirty map before presence) and fill (HEAD's bytes either way); a new // write of the block waits for the caller's COW entry. -func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow) ([]byte, bool, error) { +func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte) ([]byte, bool, error) { s := l.s if s.v3 != nil { - if data, handled, err := s.readDirtyV3Observed(uint32(lba), func() { w.walReads.Add(1) }); handled { + if data, handled, err := s.readDirtyV3Into(uint32(lba), dst, func() { w.walReads.Add(1) }); handled { return data, err == nil, err } } else if walRelOff, dataOffset, _, _, ok := s.dm.get(lba); ok { diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 912bdf63ce..99d911141e 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -953,6 +953,10 @@ func (s *WALStore) readDirtyV3(lba uint32) (data []byte, handled bool, err error // Optional per-operation accounting; the validation/re-resolution contract is // identical for guest readers and local COW owners. func (s *WALStore) readDirtyV3Observed(lba uint32, recordAttempt func()) (data []byte, handled bool, err error) { + return s.readDirtyV3Into(lba, nil, recordAttempt) +} + +func (s *WALStore) readDirtyV3Into(lba uint32, dst []byte, recordAttempt func()) (data []byte, handled bool, err error) { const attempts = 8 for i := 0; i < attempts; i++ { if h := s.v3.testReadAdmitted; h != nil { @@ -969,7 +973,7 @@ func (s *WALStore) readDirtyV3Observed(lba uint32, recordAttempt func()) (data [ if recordAttempt != nil { recordAttempt() } - data, ioErr, verr := s.readRecordV3(lba, off, dataOff, lsn) + data, ioErr, verr := s.readRecordIntoV3(lba, off, dataOff, lsn, dst) if ioErr != nil { return nil, true, NewSubstrateIOFailure(ioErr, "v3 WAL read") } @@ -992,6 +996,10 @@ 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) { + return s.readRecordIntoV3(lba, walRelOff, dataOff, lsn, nil) +} + +func (s *WALStore) readRecordIntoV3(lba uint32, walRelOff uint64, dataOff uint32, lsn uint64, dst []byte) (data []byte, ioErr, verr error) { // 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 { @@ -1021,7 +1029,13 @@ func (s *WALStore) readRecordV3(lba uint32, walRelOff uint64, dataOff uint32, ls return nil, nil, fmt.Errorf("%w: v3 dirty record identity", errInvalidEntry) } scratch := make([]byte, s.sb.BlockSize) - data = make([]byte, s.sb.BlockSize) + data = dst + if data == nil { + data = make([]byte, s.sb.BlockSize) + } + if len(data) != int(s.sb.BlockSize) { + return nil, nil, errInvalidEntry + } crc := crc32.Update(0, walEntryCRC32CV3, prefix[:]) for off := uint64(0); off < n; off += uint64(len(scratch)) { part := scratch[:min(uint64(len(scratch)), n-off)] diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 7d219ee726..97e3a0a084 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -153,7 +153,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto - `pending`: become the owner (`saving`), read the chunk (still its content at H), put it in the side store, mark `saved`, wake waiters, proceed; - `copying` or `saving`: wait (step 2), then re-check. - **Batches across chunks** (`WriteBatch`; public `ApplyEntry` accepts one block): visit the batch's chunks in ascending chunk index and finish each chunk's step (wait, or save) before the next; no chunk is held while waiting on another, so batches cannot deadlock with each other or with the copier, which owns one chunk at a time. The batch publishes only after all its chunks are `saved`, `done` or outside D. -4. **Upload workers**, outside the barrier: read each candidate at H when an upload slot is available, preferring recent writes. A worker owns one immutable image through upload. The local entry is released after its read, so guest writes never wait for remote I/O; the window protects not-yet-read candidates until all workers settle. Only concurrent overwrites consume the bounded COW cache/side file. Pre-copy streams through the same bounded uploader pool. Intent, manifest, CAS and unknown-outcome rules are unchanged. +4. **Upload workers**, outside the barrier: read each candidate at H when an upload slot is available, preferring recent writes. A worker owns one immutable image through upload. The local entry is released after its read, so guest writes never wait for remote I/O; the window protects not-yet-read candidates until all workers settle. Only concurrent overwrites consume the bounded COW cache/side file. Pre-copy streams through the same bounded uploader pool. One intent per cut or staging round roots all preallocated candidate keys before the first PUT; unused keys need no payload. An open-window PUT retries its frozen buffer until cancellation or its 30-second object deadline. Window abort fails a named request; it never substitutes another point. Manifest, CAS and unknown-outcome rules are unchanged. 5. **Terminal states: closed, or aborted.** The window ends exactly once, either closed (step 4) or aborted. Abort is taken on a save error (side store full or an I/O error), cut cancellation, fencing, and before `Recover`, a reset or `Close` in the same open. Abort happens **before** the mutation that hit the error proceeds: the cut is marked failed (retryable, `finishCut` does not run, so the dirty set keeps every candidate and the next cut takes them again), all waiters are woken and proceed without saving, and the copier stops. A guest write is never refused because of a cut problem. `Recover`, a reset and `Close` wait for the abort to finish and join every outstanding owner and reader (step 6) before they take their own locks. 6. **Side store and drain.** Local and per cut: memory up to a bound, then a file in the volume's local root; at most |D| × 4 MiB, in practice the chunks written during the window. Every saving or copying owner holds a window reference from its state claim until all of its live-chunk reads and side-store I/O finish; every additional saved-buffer or side-store reader holds a reference too. Abort atomically invalidates the cut and wakes waiters without waiting for its caller's own reference. Owners release their references on every success and error path; an owner that initiates an abort releases its own reference before any join. `Recover`, a reset and `Close` join all outstanding owners and readers before their destructive transition. The side store is deleted exactly once, after the window is closed or aborted **and** no reference is outstanding; no later state claim or I/O may acquire a reference to that terminal window. Recovery never reads it: after a crash the cut is gone, HEAD is unchanged, and the dirty set is rebuilt from the owned map and the WAL. A locked RW open discards only regular files with this volume's reserved `.cut-cow-` prefix; it never reads their contents. 7. **Reads go through the store's read path as the format-v3 work defines it** (the stable, validated reader), both for the save and for the copier; COW adds no flusher hook and no raw extent read. The flusher moves WAL content to the extent without changing what a read returns, so saving at the flusher would miss writes still in the WAL. @@ -163,7 +163,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto **Alternatives.** Holding the flusher for candidate chunks (reading the at-H content back from the extent and WAL entries up to H) needs no side store, but the WAL cannot be released for those chunks during the window, and a long upload fills it. Raising `BarrierBound` staging does not bound the stall when writes keep re-dirtying staged chunks. Redirect-on-write at the extent changes the on-disk layout and is out of scope for the current format work. -**Implementation and lifetime.** `chunk_cut_cow.go` owns window claims and drain; `chunk_cut_payload.go` streams stage images with bounded workers. Four chunk buffers per upload worker plus two per active saver are reserved before cached saves are admitted; the configurable per-volume payload budget defaults to 64 MiB. Explicit budgets must hold at least six chunks; the default grows to that geometry-dependent minimum. An optional Budget admits before staging/barrier, accounts COW reservations without a window lock, and can revoke selected cuts; its ticket is released after worker joins. Host-wide policy belongs to the separate host limiter module. No whole-round payload copy is retained in memory or on disk. The configured side-file cap covers only overwritten-before-read chunks; exhaustion aborts the cut before publication and the guest proceeds. Uploads join before cut cleanup. Locked RW open discards regular files under the reserved `.cut-cow-` prefix; recovery never imports their contents. +**Implementation and lifetime.** `chunk_cut_cow.go` owns window claims and drain; `chunk_cut_payload.go` streams stage images with bounded workers. Whole WAL records are CRC/footer validated with block-sized scratch, including bytes outside the requested block. Savers read into their existing image buffer. Four chunk buffers per upload worker plus two per active saver are reserved before cached saves are admitted; the configurable per-volume payload budget defaults to 64 MiB. Explicit budgets must hold at least six chunks; the default grows to that geometry-dependent minimum. An optional Budget admits before staging/barrier, accounts COW reservations without a window lock, and can revoke selected cuts; its ticket is released after worker joins. Host-wide policy belongs to the separate host limiter module. No whole-round payload copy is retained in memory or on disk. The configured side-file cap covers only overwritten-before-read chunks; exhaustion aborts the cut before publication and the guest proceeds. Uploads join before cut cleanup. Locked RW open discards regular files under the reserved `.cut-cow-` prefix; recovery never imports their contents. Store Close permanently closes attachment admission and captures hooks under captureMu, releases it, then aborts/joins the layer before closing storage. Every Close caller shares completion/result. Recover/reset acquire a window-admission lease and join owners before lower store locks; hook snapshot recheck includes racing first attachment. BASE begin/complete drain the whole cut through capMu. Resume is excluded by BaseInstalling state, not by capMu. A completed install handle's ApplyInstallEntry uses the same pre-publication hook as ordinary ApplyEntry. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9957efa91a..363bb070cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -222,7 +222,7 @@ stateDiagram-v2 | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | | CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | -| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it; a refused current-lineage point retains intent-rooted completed uploads until reuse or supersession | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | | Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | ### M6 Chunk lifecycle