Merge #801 7003168a into train/20261130-t2

This commit is contained in:
pingqiu committed 2026-11-29 17:49:23 -08:00
commit fe8cedde34
4 files changed
+223 -22

No files matched your search

@@ -0,0 +1,202 @@
package storage
import (
"bytes"
"context"
"errors"
"sync/atomic"
"testing"
)
func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) {
for _, mode := range []string{"spill_cap", "context_end", "write_after_capture", "different_staged"} {
t.Run(mode, func(t *testing.T) {
s, l, f := unknownFilledVolume(t)
l.cfg.UploadConcurrency = 1
l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + 2*ctChunkBytes), nil }
image := f.imageOf(t, f.stats().head)
if mode == "different_staged" {
if _, err := s.Write(2*ctChunkBlocks, makeBlock(ctBlockSize, 0xE9)); err != nil {
t.Fatal(err)
}
}
// Stage the image, then invalidate two staged copies before the barrier.
// The other six equal results are captured without another COW read.
l.testBeforeBarrierLockHook = func() {
for _, idx := range []uint64{0, 1} {
lba := uint32(idx * ctChunkBlocks)
if _, err := s.Write(lba, blockOf(image, lba)); err != nil {
t.Error(err)
}
}
}
ctx, cancel := context.WithCancel(ctTimeout(t))
defer cancel()
var triggered atomic.Bool
l.testCOWRead = func(idx uint64, _ bool) {
if triggered.Swap(true) {
return
}
w := l.cowActive.Load()
if mode == "write_after_capture" {
if _, err := s.Write(2*ctChunkBlocks, makeBlock(ctBlockSize, 0xE9)); err != nil {
t.Error(err)
}
}
if mode == "spill_cap" {
w.mu.Lock()
w.memory, w.spillLimit = w.memoryLimit, 0
w.mu.Unlock()
other := uint32((1 - idx) * ctChunkBlocks)
if _, err := s.Write(other, blockOf(image, other)); err != nil {
t.Error(err)
}
} else {
cancel()
w.abort(context.Canceled)
}
}
_, err := l.Cut(ctx)
wantErr := error(context.Canceled)
if mode == "spill_cap" {
wantErr = errCutCOWCapacity
}
if !triggered.Load() || !errors.Is(err, wantErr) {
t.Fatalf("copy did not abort as intended: %v", err)
}
l.stMu.Lock()
marked := make(map[uint64]bool)
for idx := range l.filledClean {
if l.knownEqualToHeadLocked(idx) {
marked[idx] = true
}
}
l.stMu.Unlock()
want := 6
if mode == "write_after_capture" || mode == "different_staged" {
want--
}
if len(marked) != want || ((mode == "write_after_capture" || mode == "different_staged") && marked[2]) {
t.Fatalf("kept equal marks %v, want %d captured versions (no later write)", marked, want)
}
l.testBeforeBarrierLockHook, l.testCOWRead = nil, nil
var compared, repeated atomic.Int64
l.testAfterCompareHook = func(idx uint64) {
compared.Add(1)
if marked[idx] {
repeated.Add(1)
}
}
result, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
wantCompared := int64(2)
if mode == "write_after_capture" {
wantCompared++
}
wantCandidates := int(wantCompared)
if result.Stats.CandidateChunks != wantCandidates || compared.Load() != wantCompared || repeated.Load() != 0 {
t.Fatalf("retry candidates=%d compared=%d repeated=%d; want %d,%d,0", result.Stats.CandidateChunks, compared.Load(), repeated.Load(), wantCandidates, wantCompared)
}
if (mode == "write_after_capture" || mode == "different_staged") && !bytes.Equal(blockOf(f.imageOf(t, result.Head), 2*ctChunkBlocks), makeBlock(ctBlockSize, 0xE9)) {
t.Fatal("retry lost the write made after capture")
}
})
}
}
// A deadline inside pre-copy must keep the completed comparisons, not only
// the results of an entire staging round that reached the capture barrier.
func TestInterruptedStagingKeepsEqualWork(t *testing.T) {
for _, mutate := range []bool{false, true} {
name := "context_end"
if mutate {
name = "write_after_read"
}
t.Run(name, func(t *testing.T) {
s, l, f := unknownFilledVolume(t)
l.cfg.UploadConcurrency = 1
l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + ctChunkBytes), nil }
ctx, cancel := context.WithCancel(ctTimeout(t))
defer cancel()
var reads atomic.Int64
var written uint64
l.testAfterStageReadHook = func(idx uint64) {
n := reads.Add(1)
if n == 1 && mutate {
written = idx
if _, err := s.Write(uint32(idx*ctChunkBlocks), makeBlock(ctBlockSize, 0xEC)); err != nil {
t.Error(err)
}
}
if n == 3 {
cancel()
}
}
if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) {
t.Fatalf("staging cancellation: %v", err)
}
l.stMu.Lock()
kept := make(map[uint64]bool)
for idx := range l.filledClean {
if l.knownEqualToHeadLocked(idx) {
kept[idx] = true
}
}
l.stMu.Unlock()
want := 3
if mutate {
want--
}
if len(kept) != want || (mutate && kept[written]) {
t.Fatalf("staging kept %v, want %d valid captured proofs", kept, want)
}
if !mutate {
written = 7 // not among the first three completed comparisons
if kept[written] {
t.Fatal("fixture wrote a retained chunk")
}
if _, err := s.Write(uint32(written*ctChunkBlocks), makeBlock(ctBlockSize, 0xEC)); err != nil {
t.Fatal(err)
}
}
var retryReads, repeated atomic.Int64
l.testAfterStageReadHook = func(idx uint64) {
retryReads.Add(1)
if kept[idx] {
repeated.Add(1)
}
}
result, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if result.Stats.CandidateChunks != 8-want || retryReads.Load() != int64(8-want) || repeated.Load() != 0 {
t.Fatalf("retry candidates=%d reads=%d repeated=%d, want %d,%d,0", result.Stats.CandidateChunks, retryReads.Load(), repeated.Load(), 8-want, 8-want)
}
if !bytes.Equal(blockOf(f.imageOf(t, result.Head), uint32(written*ctChunkBlocks)), makeBlock(ctBlockSize, 0xEC)) {
t.Fatal("retry lost the write after the staging read")
}
})
}
}
func TestStagingEqualChunksStillCountAsCandidates(t *testing.T) {
_, l, _ := unknownFilledVolume(t)
l.cfg.UploadConcurrency = 1
l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + ctChunkBytes), nil }
var reads atomic.Int64
l.testAfterStageReadHook = func(uint64) { reads.Add(1) }
result, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
const total = ctNumBlocks / ctChunkBlocks
if reads.Load() != total || result.Stats.StagedChunks != total {
t.Fatalf("fixture reads=%d staged=%d, want %d", reads.Load(), result.Stats.StagedChunks, total)
}
if result.Stats.CandidateChunks != total {
t.Fatalf("staging compared %d equal chunks, CandidateChunks=%d, want %d", total, result.Stats.CandidateChunks, total)
}
}
@@ -70,8 +70,9 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
}
}
l.rememberPayload(c, head.Gen, staging)
if !staging {
l.markEqualNow(c, head)
l.markEqualNow(c, head)
if hook := l.testAfterCompareHook; hook != nil {
hook(c.idx)
}
c.data = nil
out[i] = c
@@ -84,7 +85,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
}
// markEqualNow records a captured chunk that compared equal to HEAD as a
// clean mark as soon as it is compared, at the version the barrier captured
// clean mark as soon as it is compared, at the version its read captured
// and only while the chunk still has it, so a cut that runs out of time
// keeps every chunk it finished comparing and the next request continues
// from there (the same mark the cut records for all of them after the
@@ -98,9 +99,6 @@ func (l *chunkLayerImpl) markEqualNow(c capturedChunk, head chunkHead) {
}
l.stMu.Unlock()
}
if hook := l.testAfterCompareHook; hook != nil {
hook(c.idx)
}
}
func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, error) {
+16 -15
View File
@@ -784,6 +784,18 @@ func (l *chunkLayerImpl) latchIdentityMoved(err error) error {
// an identity-moved signal; it returns err unchanged.
func (l *chunkLayerImpl) ObserveRemoteError(err error) error { return l.latchIdentityMoved(err) }
// recordCapturedEqualMarks shares the success and copy-abort proof rule.
// A mark names the barrier-captured version and base HEAD ref, never bytes
// uploaded but not committed or a version written after that barrier.
func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, versions map[uint64]uint64, head chunkHead) {
for _, c := range captured {
if v, ok := versions[c.idx]; ok {
c.version = v
l.markEqualNow(c, head)
}
}
}
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) {
defer func() { err = l.latchIdentityMoved(err) }()
done, err := l.register()
@@ -1058,7 +1070,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN)
}
st.CandidateChunks = len(candidates)
st.CandidateChunks = max(st.CandidateChunks, len(candidates))
var copyErr error
copyStart := time.Now()
bytesBeforeCopy := st.UploadedBytes
@@ -1097,6 +1109,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
st.UploadNs = st.CopyNs
if copyErr != nil {
l.recordCapturedEqualMarks(captured, capturedVersions, baseHead)
l.requeueCut(all)
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr)
}
@@ -1120,16 +1133,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
key string
}
var uploads []upload
// equal: the chunks this cut compared equal to HEAD, at the version it
// captured; recorded as clean marks below, so a rerun after this cut
// fails does not compare them again.
var equal []uint64
for _, c := range captured {
ref, had := baseHead.Chunks[c.idx]
switch {
case c.zero && !had, unchangedFromHead(c, ref, had):
st.UnchangedChunks++
equal = append(equal, c.idx)
continue
case c.zero:
delete(next.Chunks, c.idx)
@@ -1151,15 +1159,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if hook := l.testBeforeRecordMarksHook; hook != nil {
hook()
}
if len(equal) > 0 {
l.stMu.Lock()
for _, idx := range equal {
if v, ok := capturedVersions[idx]; ok && l.chunkVersion(idx) == v {
l.filledClean[idx] = filledMark{version: v, ref: baseHead.Chunks[idx]}
}
}
l.stMu.Unlock()
}
l.recordCapturedEqualMarks(captured, capturedVersions, baseHead)
// The holder's session is begun before the first upload: every object
// the cut writes belongs to it until the commit (CASHead) or Abort.
l.cutPhase("upload")
@@ -1790,6 +1790,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap
head := copyHead(l.head)
l.stMu.Unlock()
st.StageRounds++
st.CandidateChunks = max(st.CandidateChunks, len(batch))
roundChunks, err := l.stagePayloadRound(ctx, batch, vers, head, st)
if err != nil {
return nil, err
+1 -1
View File
@@ -602,7 +602,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. A refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`) | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`) | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `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-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 |