storage: every HEAD install goes through setHeadLocked; the ref table mirrors it under test

The nine places that installed the layer's HEAD (attach, settlement,
adoption, a fence, a cut's finish) go through setHeadLocked, and a cut's
finish through setHeadChangedLocked, which updates only its changed
chunks. On the v1.1 format they keep the ref table HEAD's when
refTableMirror is on; it stays off until the flat map goes (both at once
only add memory). TestRefTableMirrorsHeadThroughTheLayer runs the cut,
settle, hydration and fill suites on v1.1 with the table on and every
table read checked against the map (a mutant that drops a cut's changes
fails it). Tests that wrote the layer's HEAD directly now install it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 09:41:21 -08:00
1 parent 5e97bae96f
commit 7e5f1fce7d
7 files changed
+139 -15

No files matched your search

@@ -229,7 +229,7 @@ func TestACleanFillRecordEndsWithItsHeadRef(t *testing.T) {
ref.Key += "-replaced"
ref.SHA256[0] ^= 0xFF
h.Chunks[idx] = ref
l.head = h
l.setHeadLocked(h)
l.stMu.Unlock()
if !l.captureCandidates()[idx] {
t.Fatal("a chunk whose HEAD ref changed after its fill is not a candidate")
@@ -196,7 +196,7 @@ func (l *chunkLayerImpl) fencePublication(cur chunkHead) {
if cur.Gen != 0 {
// Preserve the existing hydration identity invalidation. This is not
// settlement of our cut: remoteLSN and captured-map dirt stay unchanged.
l.head = copyHead(cur)
l.setHeadLocked(copyHead(cur))
}
l.stMu.Unlock()
log.Printf("ALARM: chunk publisher fenced: local epoch=%d holder=%q, observed gen=%d epoch=%d holder=%q; keeping local data and intents", l.cfg.Epoch, l.cfg.Holder, cur.Gen, cur.Epoch, cur.Holder)
@@ -327,7 +327,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) {
t.Fatal("old Get not entered")
}
layer.stMu.Lock()
layer.head.Chunks[2] = newRef
setHeadChunkForTest(layer, 2, newRef)
layer.absentGen[2]++
layer.stMu.Unlock()
newer := startHydrationRead(t, s, ctx, 8)
@@ -368,7 +368,7 @@ func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) {
t.Fatal("old Get not entered")
}
layer.stMu.Lock()
layer.head.Chunks[2] = newRef
setHeadChunkForTest(layer, 2, newRef)
layer.absentGen[2]++
layer.stMu.Unlock()
newer := startHydrationRead(t, s, ctx, 8)
+68 -11
View File
@@ -140,9 +140,12 @@ type chunkLayerImpl struct {
stMu sync.Mutex
closed bool
head chunkHead
pending *chunkHead // a proposal whose CAS outcome is unresolved
fenced bool
detached *chunkCutResult // set by a successful Detach
// refs is the ref table of head on the v1.1 format (nil on v1.0): headRef
// reads it; setHeadLocked and setHeadChangedLocked keep it head's.
refs *refTable
pending *chunkHead // a proposal whose CAS outcome is unresolved
fenced bool
detached *chunkCutResult // set by a successful Detach
// pendingDetach says the unresolved proposal in pending is a Detach;
// pendingCut is its cut result, installed as the detach result if the
// re-read shows it applied.
@@ -333,7 +336,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.cancel()
return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err)
}
l.head = copyHeadEach(head, l.attachProgress.add) // reports as it copies
l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies
l.remoteLSN = head.RemoteLSN
// A HEAD that already belongs to a newer epoch or a competing holder is
// never used as this holder's publication guard.
@@ -445,10 +448,61 @@ func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks
// every single-chunk reader of HEAD goes through it (and headChunk), so the
// flat map behind it can be replaced (V4-B PR 4). Caller holds stMu.
func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) {
if l.refs != nil {
r, ok := l.refs.Get(idx)
if check := refTableCheck; check != nil {
if m, mok := l.head.Chunks[idx]; mok != ok || m != r {
check(fmt.Sprintf("chunk %d: the ref table names %+v (%v), the flat map %+v (%v)", idx, r, ok, m, mok))
}
}
return r, ok
}
r, ok := l.head.Chunks[idx]
return r, ok
}
// refTableCheck, set by tests only, compares every ref-table read with the
// flat map while both exist (a finding fails the package's tests).
var refTableCheck func(string)
// refTableMirror keeps the ref table beside the flat map on the v1.1 format.
// Off until the flat map goes (V4-B PR 4 commit 4): both at once only add
// memory. Tests turn it on to check the table against the map through the
// layer's every HEAD install (TestRefTableMirrorsHeadThroughTheLayer).
var refTableMirror = false
// setHeadLocked installs h as the layer's HEAD and, on the v1.1 format,
// refills the ref table from it whole (attach, settlement, adoption: the
// rare paths). Caller holds stMu or owns the layer.
func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
l.head = h
if !chunkV11Format || !refTableMirror {
l.refs = nil
return
}
if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks {
l.refs = newRefTable(l.numChunks)
}
l.refs.fillAll(h.Chunks)
}
// setHeadChangedLocked installs h after a commit whose changed chunks are
// changed: the ref table takes only those (O(C)), the rest is unchanged.
func (l *chunkLayerImpl) setHeadChangedLocked(h chunkHead, changed []uint64) {
if l.refs == nil {
l.setHeadLocked(h)
return
}
l.head = h
for _, idx := range changed {
if r, ok := h.Chunks[idx]; ok {
_ = l.refs.Set(idx, r)
} else {
l.refs.Delete(idx)
}
}
}
// headChunk is headRef's reference alone: the zero reference when HEAD names
// none (a comparison with a named reference then fails, as a map read's
// zero value did). Caller holds stMu.
@@ -1548,7 +1602,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if l.supersededBy(cur) {
l.stMu.Lock()
l.fenced = true
l.head = copyHead(cur)
l.setHeadLocked(copyHead(cur))
l.stMu.Unlock()
l.abortCOW(errChunkLayerFenced)
return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr)
@@ -1651,7 +1705,8 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
switch {
case sameProposal(cur, *pending):
l.noteSettled(l.head, cur)
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
l.setHeadLocked(copyHead(cur))
l.remoteLSN = cur.RemoteLSN
l.shadowCommitCaptured(landed, true)
cut.Head = copyHead(cur)
l.detached = &cut
@@ -1660,7 +1715,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
return detachApplied, r, nil
case l.supersededBy(cur):
l.fenced = true
l.head = copyHead(cur)
l.setHeadLocked(copyHead(cur))
return detachFenced, chunkCutResult{}, nil
default:
if l.adoptHeadLocked(cur) != nil {
@@ -1887,7 +1942,8 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
switch {
case sameProposal(cur, *pending):
l.noteSettled(l.head, cur)
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
l.setHeadLocked(copyHead(cur))
l.remoteLSN = cur.RemoteLSN
l.shadowCommitCaptured(landed, true)
if wasDetach {
cut.Head = copyHead(cur)
@@ -1896,7 +1952,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
}
case l.supersededBy(cur):
l.fenced = true
l.head = copyHead(cur)
l.setHeadLocked(copyHead(cur))
return errChunkLayerFenced
default:
// HEAD moved past the unresolved CAS's base without it: that CAS
@@ -1921,7 +1977,7 @@ var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder
// (errChunkForeignRoot). Caller holds stMu.
func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error {
same := sameChunkRoot(l.head.Chunks, cur.Chunks)
l.head = copyHead(cur)
l.setHeadLocked(copyHead(cur))
if !same {
l.fenced = true
log.Printf("level=WARN storage: chunk layer fenced: HEAD gen %d moved the chunk root without superseding holder %q epoch %d", cur.Gen, l.cfg.Holder, l.cfg.Epoch)
@@ -2226,7 +2282,8 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n
l.stMu.Lock()
defer l.stMu.Unlock()
l.noteSettled(l.head, head)
l.head, l.remoteLSN, l.pending = copyHead(head), h, nil
l.setHeadChangedLocked(copyHead(head), changed)
l.remoteLSN, l.pending = h, nil
l.pendingCaptured, l.pendingChanges = nil, nil
l.reusable = nil
l.inflight = map[uint64]bool{}
@@ -18,6 +18,16 @@ func TestMain(m *testing.M) {
found = append(found, msg)
mu.Unlock()
}
// While the flat map and the ref table both exist (V4-B PR 4), every
// ref-table read is checked against the map: a difference is a finding.
if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" {
refTableMirror = true
}
refTableCheck = func(msg string) {
mu.Lock()
found = append(found, "ref table: "+msg)
mu.Unlock()
}
// CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store
// format (the lab build's mode); it selects a format, it turns no check
// off.
@@ -155,6 +155,20 @@ func (t *refTable) FillSegment(first, end uint64, refs map[uint64]chunkRef) erro
return nil
}
// fillAll makes the table exactly m (a whole HEAD's references): O(S).
// References beyond the volume are dropped here; the attach refuses them
// before (a malformed HEAD).
func (t *refTable) fillAll(m map[uint64]chunkRef) {
for i := range t.prefix {
if t.prefix[i] != 0 {
t.Delete(uint64(i))
}
}
for i, r := range m {
_ = t.Set(i, r)
}
}
// each calls f for every named chunk, in index order: O(S), the whole
// volume (for the paths that need the whole set, never for a lookup).
func (t *refTable) each(f func(i uint64, ref chunkRef)) {
@@ -0,0 +1,43 @@
package storage
import (
"os"
"os/exec"
"strings"
"testing"
)
// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as
// a HEAD install would (the ref table follows when it is kept).
func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) {
l.head.Chunks[idx] = ref
if l.refs != nil {
_ = l.refs.Set(idx, ref)
}
}
// The ref table, kept beside the flat map, names exactly what the map names
// through every HEAD install the layer makes: attach, cuts (the changed
// chunks only), settlement, adoption, a fence. The package's cut, settle,
// hydration and fill suites run on the v1.1 format with the table kept and
// every table read checked against the map (refTableCheck: a difference is
// a finding, which fails the run). A child run, so the table's switch and
// the format are this test's alone.
func TestRefTableMirrorsHeadThroughTheLayer(t *testing.T) {
if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" {
t.Skip("the child run itself")
}
if testing.Short() {
t.Skip("runs the cut suites in a child process")
}
cmd := exec.Command(os.Args[0], "-test.run", "Cut|Settle|Pending|Hydrat|Fill|Evict|Adopt|Detach|Fresh|Clean|V11|Shadow|RefTable", "-test.count=1")
cmd.Env = append(os.Environ(), "REF_TABLE_MIRROR_CHILD=1", "CHUNK_RECORD_V11=1")
out, _ := cmd.CombinedOutput()
if strings.Contains(string(out), "ref table: ") {
i := strings.Index(string(out), "ref table: ")
t.Fatalf("the ref table and the flat map differ: %s", string(out)[i:min(len(out), i+400)])
}
if !strings.Contains(string(out), "ok") && !strings.Contains(string(out), "FAIL") {
t.Fatalf("the child run reported nothing: %s", out)
}
}