From 5e1f9d11e4f9e6e23545da331eee725d4ebfc819 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:11:40 -0800 Subject: [PATCH] storage: no flat map on v1.1: HEAD's chunks live in the ref table On the v1.1 format the layer keeps HEAD's identity and its chunks in the ref table only: the attach reads HEAD one segment at a time from a segment reader (ChunkSegmentReader; the layout remote is one), every install fills the table from a HEAD read whole, and the paths that need the whole image (adoption, owning, the detach cancel, the publication report) build it from the table. A cut's result reports HEAD's identity only; no production code reads its chunks (a scan test guards it), and tests read the remote's installed HEAD. The held heap at 1 TiB's chunk count is 174 B/chunk (442 before) and is asserted at most 200. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 3 +- .../chunkstore/layout_head_read_root_test.go | 16 +- .../core/frontend/chunkstore/layout_remote.go | 3 + .../durable/commit_check_budget_test.go | 5 +- .../core/frontend/durable/provider_chunk.go | 23 ++ .../storage/chunk_attach_progress_test.go | 6 +- .../storage/chunk_attach_segments_test.go | 103 +++++++++ .../storage/chunk_cut_cow_spillcap_test.go | 5 +- .../core/storage/chunk_cut_image_test.go | 5 +- .../storage/chunk_cut_result_head_test.go | 64 ++++++ .../core/storage/chunk_fake_remote_test.go | 30 +++ .../core/storage/chunk_fresh_known_zero.go | 4 +- .../storage/chunk_head_test_helpers_test.go | 11 + .../chunk_hydration_concurrency_test.go | 4 +- seaweed-block/core/storage/chunk_layer.go | 205 +++++++++++------- .../core/storage/chunk_layer_cut_test.go | 6 + .../core/storage/chunk_layer_races_test.go | 2 +- seaweed-block/core/storage/chunk_own.go | 6 +- .../storage/chunk_proposal_by_change_test.go | 25 ++- .../core/storage/chunk_record_open.go | 2 +- .../storage/chunk_record_shadow_main_test.go | 10 - .../core/storage/chunk_record_shadow_test.go | 2 +- .../core/storage/chunk_record_upgrade.go | 12 +- .../storage/chunk_ref_table_mirror_test.go | 43 ---- .../core/storage/chunk_space_baseline_test.go | 18 +- 25 files changed, 449 insertions(+), 164 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_attach_segments_test.go create mode 100644 seaweed-block/core/storage/chunk_cut_result_head_test.go create mode 100644 seaweed-block/core/storage/chunk_head_test_helpers_test.go delete mode 100644 seaweed-block/core/storage/chunk_ref_table_mirror_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 92280b3bba..0de1e71b95 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -64,12 +64,13 @@ var headReaders = map[string]string{ "cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)", "cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)", "core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/frontend/durable/provider_chunk.go EachSegment -> GetHead": "a remote without a segment read: ErrHeadAbsent from its GetHead, as GetHead (probe LayoutRemote)", "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/storage/chunk_head_belt.go readChunkHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", - "core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/storage/chunk_layer.go readAttachHead -> GetHead": "ErrHeadAbsent from the layout remote; its segment read (EachSegment) reads HEAD as GetHead does (headIdentityLocked) (probe LayoutRemote)", } // TestHeadReaders_Enumeration lists every HEAD reader in core/ and cmd/ from diff --git a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go index 3f79bbbedc..007e9ce6df 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go @@ -89,7 +89,7 @@ func TestTheConfirmationAfterAHeadWriteReadsNoManifest(t *testing.T) { // already holds, it reads HEAD only and keeps its chunk list: no root and no // segment. func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { - _, _, l, counting, reads := manifestReads(t) + _, remote, l, counting, reads := manifestReads(t) if _, err := l.Cut(context.Background()); err != nil { // publish the written chunks t.Fatal(err) } @@ -104,7 +104,19 @@ func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { if n := reads.Load(); n != 0 { t.Fatalf("a no-op cut over an unchanged HEAD read %d roots or segments; want 0", n) } - if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks { + if res.Head.Chunks == nil { + // The v1.1 format: a cut's result reports HEAD's identity only. HEAD + // itself, read once the cut's reads are counted, still names every + // chunk at the result's generation. + counting.Store(false) + h, err := remote.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.Gen != res.Head.Gen || len(h.Chunks) != lrBlocks/lrChunkBlocks { + t.Fatalf("after the no-op cut HEAD is gen %d with %d chunks; want the result's gen %d with the %d it already held", h.Gen, len(h.Chunks), res.Head.Gen, lrBlocks/lrChunkBlocks) + } + } else if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks { t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks) } } diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 70fa4906d6..e66ec45fbc 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -476,6 +476,9 @@ func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, return m, err } +// The layer's v1.1 attach reads HEAD through it segment by segment. +var _ storage.ChunkSegmentReader = (*LayoutRemote)(nil) + // EachSegment is GetHead one segment at a time (storage.ChunkSegmentReader): // HEAD's identity as GetHead returns it (no chunk listed), and fn called for // each segment HEAD's root names with its chunk range [first, end) (a diff --git a/seaweed-block/core/frontend/durable/commit_check_budget_test.go b/seaweed-block/core/frontend/durable/commit_check_budget_test.go index 0cb93d2c58..1d9962a918 100644 --- a/seaweed-block/core/frontend/durable/commit_check_budget_test.go +++ b/seaweed-block/core/frontend/durable/commit_check_budget_test.go @@ -111,8 +111,9 @@ func TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces(t *testing b, ok := r.(storage.ChunkHeadStepBounder) return ok && b.BoundsHeadStep() }, - "ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok }, - "ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok }, + "ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok }, + "ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok }, + "ChunkSegmentReader": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkSegmentReader); return ok }, } for name, has := range checks { if has(lr) && !has(wrapped) { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a47cf57d84..43b1743e1d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "log" + "math" "math/rand/v2" "strings" "sync" @@ -728,6 +729,28 @@ func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, erro return r.ChunkRemote.GetHead(c) } +// EachSegment forwards HEAD's read one segment at a time +// (storage.ChunkSegmentReader) with GetHead's binding. A remote without it +// is read whole and handed over as one segment. +func (r *closeBoundRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]storage.ChunkRef) error) (storage.ChunkHead, error) { + c, end := r.bindManifest(ctx) + defer end() + if sr, ok := r.ChunkRemote.(storage.ChunkSegmentReader); ok { + return sr.EachSegment(c, fn) + } + h, err := r.ChunkRemote.GetHead(c) + if err != nil { + return storage.ChunkHead{}, err + } + if len(h.Chunks) > 0 { + if err := fn(0, math.MaxUint64, h.Chunks); err != nil { + return storage.ChunkHead{}, err + } + } + h.Chunks = nil + return h, nil +} + func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { c, end := r.bindManifest(ctx) defer end() diff --git a/seaweed-block/core/storage/chunk_attach_progress_test.go b/seaweed-block/core/storage/chunk_attach_progress_test.go index 6c8cece6a9..b6f833182b 100644 --- a/seaweed-block/core/storage/chunk_attach_progress_test.go +++ b/seaweed-block/core/storage/chunk_attach_progress_test.go @@ -56,9 +56,13 @@ func TestAttachReportsItsVolumeSizedLocalWork(t *testing.T) { // On the v1.1 format the presence save feeds the store's upgrade, // then the record's pages (one entry per chunk of the volume) are // written by the upgrade and judged at the open. + // The ref table holds the volume's chunks only: this HEAD names more + // than the store's, which the absent marking and the presence save + // then count per volume chunk. want := uint64(4 * n) if chunkV11Format { - want = 4*n + 2*uint64(s.NumBlocks()) + vol := uint64(s.NumBlocks()) + want = n + 3*min(n, vol) + 2*vol } if c.total != want { t.Fatalf("reported %d entries, want %d (the HEAD copy, the absent marking, then the presence save's keys and lines, or the record's pages written and judged)", c.total, want) diff --git a/seaweed-block/core/storage/chunk_attach_segments_test.go b/seaweed-block/core/storage/chunk_attach_segments_test.go new file mode 100644 index 0000000000..15afc5c156 --- /dev/null +++ b/seaweed-block/core/storage/chunk_attach_segments_test.go @@ -0,0 +1,103 @@ +package storage + +import ( + "context" + "fmt" + "reflect" + "sort" + "testing" +) + +// segmentRemote reads HEAD one segment at a time (ChunkSegmentReader), in +// segments of seg chunks, counting the segments it hands out and every +// whole read (GetHead) made through it. +type segmentRemote struct { + *fakeChunkRemote + seg uint64 + segments, wholeReads int +} + +func (r *segmentRemote) GetHead(ctx context.Context) (chunkHead, error) { + r.wholeReads++ + return r.fakeChunkRemote.GetHead(ctx) +} + +func (r *segmentRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error) { + h, err := r.fakeChunkRemote.GetHead(ctx) // the remote's own read: the layer sees segments + if err != nil { + return chunkHead{}, err + } + shards := map[uint64]map[uint64]chunkRef{} + for idx, ref := range h.Chunks { + sh := idx / r.seg + if shards[sh] == nil { + shards[sh] = map[uint64]chunkRef{} + } + shards[sh][idx] = ref + } + order := make([]uint64, 0, len(shards)) + for sh := range shards { + order = append(order, sh) + } + sort.Slice(order, func(i, j int) bool { return order[i] < order[j] }) + for _, sh := range order { + r.segments++ + if err := fn(sh*r.seg, (sh+1)*r.seg, shards[sh]); err != nil { + return chunkHead{}, err + } + } + h.Chunks = nil + return h, nil +} + +// On the v1.1 format a layer attaches to a remote that reads HEAD by segment +// one segment at a time: no whole read of HEAD, no flat map kept, and the +// ref table names exactly HEAD's chunks. A segment naming a chunk beyond +// the volume is refused (a malformed HEAD), as the whole read's install +// cannot tell. +func TestV11AttachReadsHeadOneSegmentAtATime(t *testing.T) { + withV11Format(t) + head := func(extra bool) chunkHead { + h := chunkHead{Gen: 3, Epoch: 1, Holder: "old", RemoteLSN: 0, Chunks: map[uint64]chunkRef{}} + for i := uint64(0); i < 16; i += 2 { // every other chunk of the 16-chunk store + h.Chunks[i] = chunkRef{Key: fmt.Sprintf("c%d", i), Encoding: "full"} + } + if extra { + h.Chunks[17] = chunkRef{Key: "beyond", Encoding: "full"} + } + return h + } + attach := func(t *testing.T, h chunkHead) (*segmentRemote, *chunkLayerImpl, error) { + s, _ := v11Store(t) + f := newFakeChunkRemote() + f.head = h + r := &segmentRemote{fakeChunkRemote: f, seg: 4} + cfg := ctConfig(1) + cfg.Bitmap, cfg.Epoch, cfg.FreshFromHead = nil, 2, true + l, err := attachChunkLayer(s, r, cfg) + if err != nil { + return r, nil, err + } + t.Cleanup(func() { _ = l.Close() }) + return r, l.(*chunkLayerImpl), nil + } + r, l, err := attach(t, head(false)) + if err != nil { + t.Fatal(err) + } + l.stMu.Lock() + flat, whole := l.head.Chunks, l.wholeHeadLocked() + l.stMu.Unlock() + if r.wholeReads != 0 || r.segments != 4 { + t.Fatalf("attach read HEAD whole %d times and %d segments, want none and 4", r.wholeReads, r.segments) + } + if flat != nil { + t.Fatalf("the attached layer keeps a flat map of %d chunks", len(flat)) + } + if want := head(false).Chunks; !reflect.DeepEqual(whole.Chunks, want) { + t.Fatalf("the ref table names %d chunks, HEAD %d", len(whole.Chunks), len(want)) + } + if _, _, err := attach(t, head(true)); err == nil { + t.Fatal("a segment naming a chunk beyond the volume was attached") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go index 3adf5057c0..92b7e0800d 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -356,9 +356,10 @@ func TestCutCOWV3_RecentChunkUploadsFirst(t *testing.T) { if len(puts) != len(want) { t.Fatalf("PUTs=%v, want three uploads", puts) } + installed := f.headOf(t, result.Head) for i, idx := range want { - if puts[i] != result.Head.Chunks[idx].Key { - t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, result.Head.Chunks[idx].Key) + if puts[i] != installed.Chunks[idx].Key { + t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, installed.Chunks[idx].Key) } } } diff --git a/seaweed-block/core/storage/chunk_cut_image_test.go b/seaweed-block/core/storage/chunk_cut_image_test.go index 2e181ac838..aed92ec97d 100644 --- a/seaweed-block/core/storage/chunk_cut_image_test.go +++ b/seaweed-block/core/storage/chunk_cut_image_test.go @@ -89,7 +89,7 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) { if err != nil { t.Fatal(err) } - if first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + if f.headOf(t, first.Head).Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { t.Fatalf("first cut: %+v, want position %d", first.Head, y) } _, err = s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) @@ -100,7 +100,8 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) { if err != nil { t.Fatal(err) } - if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1] == first.Head.Chunks[1] { + h1, h2 := f.headOf(t, first.Head), f.headOf(t, second.Head) + if h2.Chunks[0] != h1.Chunks[0] || h2.Chunks[1] == h1.Chunks[1] { t.Fatal("rewrite changed a cold chunk or did not publish the changed one") } for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { diff --git a/seaweed-block/core/storage/chunk_cut_result_head_test.go b/seaweed-block/core/storage/chunk_cut_result_head_test.go new file mode 100644 index 0000000000..7455c397e4 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_result_head_test.go @@ -0,0 +1,64 @@ +package storage + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// On the v1.1 format a cut's result reports HEAD's identity only (its Chunks +// nil): no production code may read a cut or detach result's chunks. Every +// non-test Go file of the module is scanned for a read of .Head.Chunks or +// .Head.Segments; a reader added later fails here. The control: the pattern +// finds such a read. +func TestNoProductionReaderOfACutResultsChunks(t *testing.T) { + re := regexp.MustCompile(`\.Head\.(Chunks|Segments)\b`) + if !re.MatchString("ref := res.Head.Chunks[3]") || re.MatchString("gen := res.Head.Gen") { + t.Fatal("control: the scan's pattern does not tell a chunk read from an identity read") + } + root := filepath.Join("..", "..") + if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil { + t.Fatalf("module root not found from the package: %v", err) + } + var found []string + files := 0 + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case ".git", "vendor", "testdata", "node_modules": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + files++ + for i, line := range strings.Split(string(b), "\n") { + if re.MatchString(line) { + found = append(found, fmt.Sprintf("%s:%d", p, i+1)) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if files < 100 { + t.Fatalf("scanned only %d Go files: the walk did not cover the module", files) + } + if len(found) > 0 { + t.Fatalf("production code reads a cut result's chunks, which the v1.1 format does not report: %v", found) + } +} diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 882f098ad6..063fa98807 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -389,6 +389,9 @@ func (f *fakeChunkRemote) imageOf(t *testing.T, h chunkHead) []byte { t.Helper() f.mu.Lock() defer f.mu.Unlock() + if h.Chunks == nil && h.Gen != 0 { + h = f.installedLocked(t, h) + } img := make([]byte, ctNumBlocks*ctBlockSize) for idx, ref := range h.Chunks { b, ok := f.objs[ref.Key] @@ -1178,3 +1181,30 @@ func deltaMatchesNext(h chunkHead, next chunkHead, changes map[uint64]*chunkRef) } return applied, nil } + +// headOf is h whole: h itself, or the HEAD this remote installed with h's +// identity when h reports identity only (a v1.1 cut's result). +func (f *fakeChunkRemote) headOf(t *testing.T, h chunkHead) chunkHead { + t.Helper() + if h.Chunks != nil || h.Gen == 0 { + return h + } + f.mu.Lock() + defer f.mu.Unlock() + return f.installedLocked(t, h) +} + +// installedLocked is the HEAD this remote installed with id's generation, +// epoch and holder: what a cut's result names when it reports identity only +// (the v1.1 format), read from the remote, the source of truth. Caller +// holds mu. +func (f *fakeChunkRemote) installedLocked(t *testing.T, id chunkHead) chunkHead { + t.Helper() + for i := len(f.heads) - 1; i >= 0; i-- { + if h := f.heads[i]; h.Gen == id.Gen && h.Epoch == id.Epoch && h.Holder == id.Holder { + return h + } + } + t.Fatalf("no installed HEAD has gen %d epoch %d holder %q", id.Gen, id.Epoch, id.Holder) + return chunkHead{} +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index 9f57e2b4f6..ba8783a0ae 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -22,7 +22,7 @@ import "log" // THEN the marking is made durable, THEN the volume serves. A crash between // the first two leaves no marker and every chunk UNKNOWN (one scan); a // failed map publication leaves them UNKNOWN on disk (conservative). -func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 { +func (l *chunkLayerImpl) freshKnownZeroCandidates() map[uint64]uint64 { s := l.s if s.v3 == nil || s.v3.ownedMap == nil { return nil @@ -32,7 +32,7 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin out := map[uint64]uint64{} for idx := uint64(0); idx < l.numChunks && idx < uint64(s.v3.mapEntries.len()); idx++ { l.attachProgress.add(1) // attach only (its one caller): every inspected entry, candidate or not - if _, named := head.Chunks[idx]; named { + if _, named := l.headRef(idx); named { continue } if e := s.v3.mapEntries.at(int(idx)); e.LSN != 0 || !e.Unknown { diff --git a/seaweed-block/core/storage/chunk_head_test_helpers_test.go b/seaweed-block/core/storage/chunk_head_test_helpers_test.go new file mode 100644 index 0000000000..3f43c5a594 --- /dev/null +++ b/seaweed-block/core/storage/chunk_head_test_helpers_test.go @@ -0,0 +1,11 @@ +package storage + +// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as +// a HEAD install would: in the ref table on the v1.1 format, else the map. +func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) { + if l.refs != nil { + _ = l.refs.Set(idx, ref) + return + } + l.head.Chunks[idx] = ref +} diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 71caa18817..a11cf11273 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -310,7 +310,7 @@ func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, err func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { s, layer, remote, registered := hydrationFixture(t, 2, 64) layer.stMu.Lock() - oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + oldRef, newRef := layer.headChunk(2), layer.headChunk(3) layer.stMu.Unlock() r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})} layer.remote = r @@ -350,7 +350,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) { s, layer, remote, registered := hydrationFixture(t, 2, 64) layer.stMu.Lock() - oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + oldRef, newRef := layer.headChunk(2), layer.headChunk(3) layer.stMu.Unlock() r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})} layer.remote = r diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index c53ca663a9..d8b08b7cab 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -334,12 +334,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.nonce = hex.EncodeToString(nb8[:]) l.ctx, l.cancel = context.WithCancel(context.Background()) - head, err := remote.GetHead(l.ctx) + head, err := l.readAttachHead(remote) if err != nil { l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } - 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. @@ -363,14 +362,14 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch} l.dirty = map[uint64]bool{} - for idx := range head.Chunks { + l.eachHeadChunkLocked(func(idx uint64) { l.absent[idx] = true l.absentGen[idx]++ l.attachProgress.add(1) - } + }) l.presenceVer++ if cfg.CreatedThisStart { - l.freshKnownZero = l.freshKnownZeroCandidates(head) + l.freshKnownZero = l.freshKnownZeroCandidates() } } else if marked, _ := s.ChunkStateMarker(); chunkV11Format && marked { // The v1.1 record and the store's bits hold presence: a leftover @@ -452,60 +451,104 @@ func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks // 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 + return l.refs.Get(idx) } 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. +// setHeadLocked installs h as the layer's HEAD. On the v1.1 format HEAD's +// chunks live in the ref table only: it is refilled from h whole (a HEAD +// read whole: settlement, adoption, a fence) and the layer keeps h's +// identity, no flat map (V4-B PR 4). Caller holds stMu or owns the layer. func (l *chunkLayerImpl) setHeadLocked(h chunkHead) { - l.head = h - if !chunkV11Format || !refTableMirror { - l.refs = nil + if !chunkV11Format { + l.head, l.refs = h, nil return } if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks { l.refs = newRefTable(l.numChunks) } l.refs.fillAll(h.Chunks) + h.Chunks = nil + l.head = h } -// 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) +// readAttachHead reads HEAD at attach and installs it. On the v1.1 format, +// from a remote that reads HEAD one segment at a time (ChunkSegmentReader), +// each segment's references go to the ref table as it is read: no flat map +// is built, here or in the remote. Otherwise HEAD is read whole and +// installed (setHeadLocked). Every reference is reported as attach progress. +// It returns HEAD as installed (identity only on the v1.1 format). +func (l *chunkLayerImpl) readAttachHead(remote chunkRemote) (chunkHead, error) { + sr, segmented := remote.(ChunkSegmentReader) + if !chunkV11Format || !segmented { + head, err := remote.GetHead(l.ctx) + if err != nil { + return chunkHead{}, err + } + l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies + return l.head, nil + } + refs := newRefTable(l.numChunks) + head, err := sr.EachSegment(l.ctx, func(first, end uint64, seg map[uint64]ChunkRef) error { + if first >= l.numChunks && len(seg) == 0 { + return nil + } + if err := refs.FillSegment(first, min(end, l.numChunks), seg); err != nil { + return err + } + l.attachProgress.add(uint64(len(seg))) + return nil + }) + if err != nil { + return chunkHead{}, err + } + head.Chunks = nil + l.head, l.refs = head, refs + return head, nil +} + +// ChunkSegmentReader is a remote that reads HEAD one segment at a time: +// HEAD's identity (no chunk listed), and fn called for each segment its +// root names with the segment's chunk range [first, end) and its +// references. A HEAD with no image calls fn never. +type ChunkSegmentReader interface { + EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error) +} + +// eachHeadChunkLocked calls f for every chunk HEAD names (O(S): whole-volume +// paths only). Caller holds stMu or owns the layer. +func (l *chunkLayerImpl) eachHeadChunkLocked(f func(idx uint64)) { + if l.refs != nil { + l.refs.each(func(i uint64, _ chunkRef) { f(i) }) 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) - } + for idx := range l.head.Chunks { + f(idx) } } +// wholeHeadLocked is a copy of HEAD with every chunk listed: from the ref +// table on the v1.1 format (O(S): for the rare paths that need the whole +// image), else the flat map. Caller holds stMu. +func (l *chunkLayerImpl) wholeHeadLocked() chunkHead { + h := copyHead(l.head) + if l.refs != nil { + l.refs.each(func(i uint64, r chunkRef) { h.Chunks[i] = r }) + } + return h +} + +// headChunksLocked is HEAD's chunks as a map: the flat map itself, or on +// the v1.1 format a map built from the ref table (O(S)). Caller holds stMu. +func (l *chunkLayerImpl) headChunksLocked() map[uint64]chunkRef { + if l.refs == nil { + return l.head.Chunks + } + return l.wholeHeadLocked().Chunks +} + // 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. @@ -1514,7 +1557,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch inPlace := byChange && fromBase // cur is the cut's base: its candidates only finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS persistCapturedMap(capturedVersions) - return chunkCutResult{H: h, Head: l.cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} // On the v1.1 format the commit goes by change: one owned change set, @@ -1562,7 +1605,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch finishCapturedCut(next, h, changed, newKeys, changes != nil) l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: l.cutResultHead(next, changes != nil), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: cutResultHead(next, changes != nil), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -1666,7 +1709,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.stMu.Lock() fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase changes, marked := l.pendingChanges, l.pendingMarked - baseHead := copyHead(l.head) + baseHead := l.wholeHeadLocked() l.stMu.Unlock() if fenced { return detachFenced, chunkCutResult{}, nil @@ -1762,7 +1805,7 @@ func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { defer l.stMu.Unlock() if d := l.detached; d != nil { r := *d - r.Head = copyHead(d.Head) + r.Head = copyResultHead(d.Head) return r, true } return chunkCutResult{}, false @@ -1773,7 +1816,7 @@ func (l *chunkLayerImpl) cutDone(r chunkCutResult, detach bool) chunkCutResult { if detach { l.stMu.Lock() keep := r - keep.Head = copyHead(r.Head) + keep.Head = copyResultHead(r.Head) l.detached = &keep l.stMu.Unlock() } @@ -1938,7 +1981,7 @@ func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uin // Caller holds stMu. func (l *chunkLayerImpl) cutBaseLocked(candidates map[uint64]bool) chunkHead { if !l.commitByChange() { - return copyHead(l.head) + return l.wholeHeadLocked() } b := l.head b.Chunks, b.Segments = nil, nil @@ -1962,17 +2005,23 @@ func proposalOf(next chunkHead, changes map[uint64]*chunkRef) chunkHead { return next } -// cutResultHead is the HEAD a cut reports, whole: h, or, when h names only -// the cut's chunks (byChange), the HEAD the commit installed (one copy, -// after the settlement, outside the barrier; it goes with the flat map in -// V4-B PR 4 commit 4). -func (l *chunkLayerImpl) cutResultHead(h chunkHead, byChange bool) chunkHead { - if !byChange { - return copyHead(h) +// cutResultHead is the HEAD a cut reports: h whole, or on the v1.1 format +// (byChange, h naming the cut's chunks only) HEAD's identity alone, Chunks +// nil: a cut's result is read for its generation, epoch and holder, and a +// whole copy per cut is the map the ref table replaces +// (TestNoProductionReaderOfACutResultsChunks). +func cutResultHead(h chunkHead, byChange bool) chunkHead { + out := copyHead(h) + if byChange { + out.Chunks, out.Segments = nil, nil } - l.stMu.Lock() - defer l.stMu.Unlock() - return copyHead(l.head) + return out +} + +// copyResultHead copies a cut's reported HEAD as it was reported: a result +// that reports identity only (Chunks nil) stays so. +func copyResultHead(h chunkHead) chunkHead { + return cutResultHead(h, h.Chunks == nil) } // changedIndices is a change set's indices. @@ -1996,9 +2045,10 @@ func headLookup(h chunkHead) func(uint64) (chunkRef, bool) { // it. The publication report, when one is wanted, gets whole HEADs. Caller // holds stMu. func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { - prev := l.head - if l.cfg.OnPublishSettled != nil { - prev = copyHead(l.head) + report := l.cfg.OnPublishSettled != nil && id.Gen != l.head.Gen + var prev chunkHead + if report { + prev = l.wholeHeadLocked() } h := l.head h.Gen, h.Epoch, h.Holder, h.RemoteLSN, h.State = id.Gen, id.Epoch, id.Holder, id.RemoteLSN, id.State @@ -2008,18 +2058,26 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { d := *id.DetachedBy h.DetachedBy = &d } - if h.Chunks == nil { - h.Chunks = map[uint64]chunkRef{} - } for _, idx := range changed { - if r, ok := id.Chunks[idx]; ok { + r, ok := id.Chunks[idx] + switch { + case l.refs != nil && ok: + _ = l.refs.Set(idx, r) + case l.refs != nil: + l.refs.Delete(idx) + case ok: + if h.Chunks == nil { + h.Chunks = map[uint64]chunkRef{} + } h.Chunks[idx] = r - } else { + default: delete(h.Chunks, idx) } } - l.setHeadChangedLocked(h, changed) - l.noteSettled(prev, l.head) + l.head = h + if report { + l.noteSettled(prev, l.wholeHeadLocked()) + } } func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { @@ -2098,10 +2156,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { - cut.Head = copyHead(cur) - if inPlace { - cut.Head = copyHead(l.head) // cur names the cut's chunks only - } + cut.Head = cutResultHead(cur, inPlace) l.detached = &cut return errChunkLayerDetached } @@ -2131,7 +2186,7 @@ var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder // the one the layer holds; otherwise the layer is fenced // (errChunkForeignRoot). Caller holds stMu. func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error { - same := sameChunkRoot(l.head.Chunks, cur.Chunks) + same := sameChunkRoot(l.headChunksLocked(), cur.Chunks) l.setHeadLocked(copyHead(cur)) if !same { l.fenced = true @@ -2382,7 +2437,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap for _, idx := range batch { vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it } - head := copyHead(l.head) + inBatch := make(map[uint64]bool, len(batch)) + for _, idx := range batch { + inBatch[idx] = true + } + head := l.cutBaseLocked(inBatch) l.stMu.Unlock() st.StageRounds++ st.CandidateChunks = max(st.CandidateChunks, len(batch)) @@ -2440,7 +2499,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n l.applyCommitLocked(head, changed) } else { l.noteSettled(l.head, head) - l.setHeadChangedLocked(copyHead(head), changed) + l.setHeadLocked(copyHead(head)) } l.remoteLSN, l.pending = h, nil l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil diff --git a/seaweed-block/core/storage/chunk_layer_cut_test.go b/seaweed-block/core/storage/chunk_layer_cut_test.go index 757f055eb0..e977270fe4 100644 --- a/seaweed-block/core/storage/chunk_layer_cut_test.go +++ b/seaweed-block/core/storage/chunk_layer_cut_test.go @@ -6,7 +6,13 @@ import ( "testing" ) +// A cut's result on the v1.1 format reports HEAD's identity only (Chunks +// nil): it is the same HEAD when that identity is b's. func sameHead(a, b chunkHead) bool { + if a.Chunks == nil && a.Gen != 0 { + return a.Gen == b.Gen && a.Epoch == b.Epoch && a.Holder == b.Holder && a.RemoteLSN == b.RemoteLSN && + a.State == b.State && (a.DetachedBy == nil) == (b.DetachedBy == nil) && (a.DetachedBy == nil || *a.DetachedBy == *b.DetachedBy) + } if a.Gen != b.Gen || a.Epoch != b.Epoch || a.Holder != b.Holder || a.RemoteLSN != b.RemoteLSN || len(a.Chunks) != len(b.Chunks) { return false } diff --git a/seaweed-block/core/storage/chunk_layer_races_test.go b/seaweed-block/core/storage/chunk_layer_races_test.go index 630db87880..38c8330cf3 100644 --- a/seaweed-block/core/storage/chunk_layer_races_test.go +++ b/seaweed-block/core/storage/chunk_layer_races_test.go @@ -134,7 +134,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { // share one flight, so two guest reads cannot create this overlap. impl := layer.(*chunkLayerImpl) impl.stMu.Lock() - oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2] + oldGen, oldRef := impl.absentGen[2], impl.headChunk(2) impl.stMu.Unlock() readA := make(chan error, 1) joinedA := make(chan struct{}) diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index 6b004e08ee..d4c2f5b6bd 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -30,7 +30,7 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s defer l.capMu.Unlock() l.stMu.Lock() var picked []uint64 - for _, idx := range sortedForeign(l.head.Chunks, foreign) { + for _, idx := range sortedForeign(l.headChunksLocked(), foreign) { if len(picked) < n && l.chunkLocalLocked(idx) { picked = append(picked, idx) } @@ -73,8 +73,8 @@ type ownCount struct { // ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { - c := ownCount{head: l.head.Chunks} - for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c := ownCount{head: l.headChunksLocked()} + for _, idx := range sortedForeign(c.head, foreign) { c.Remaining++ if !l.chunkLocalLocked(idx) { c.NotLocal++ diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index 077c1f50cd..d29b006275 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -114,9 +114,9 @@ func TestV11LostCommitReplySettlesByChange(t *testing.T) { // On the v1.1 format a cut copies HEAD's chunks for its candidates only: its // base names those (at S and at S/16 chunks alike), and a landed commit -// changes HEAD in place (the same map, the changed chunk replaced), where -// the full form copied every chunk at the barrier, for the proposal and at -// the install. +// changes HEAD in place, its changed chunks only (a mark planted at an +// unchanged index survives it, where a whole install would replace it), with +// no flat map: the ref table is HEAD's chunks and equals the remote's. func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { withV11Format(t) s, _ := v11Store(t) @@ -129,25 +129,32 @@ func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } + planted := chunkRef{Key: "planted", Encoding: "full"} l.stMu.Lock() - before := reflect.ValueOf(l.head.Chunks).Pointer() + real3, _ := l.headRef(3) + setHeadChunkForTest(l, 3, planted) // chunk 3 is not in the next cut l.stMu.Unlock() w.write(t, s, 2*ctChunkBlocks, 0x77) if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } l.stMu.Lock() - after, n, ref2 := reflect.ValueOf(l.head.Chunks).Pointer(), len(l.head.Chunks), l.head.Chunks[2] + got3, _ := l.headRef(3) + setHeadChunkForTest(l, 3, real3) + whole, flat := l.wholeHeadLocked(), l.head.Chunks l.stMu.Unlock() - if after != before { - t.Fatal("a landed commit by change copied HEAD's chunk map instead of changing it in place") + if got3 != planted { + t.Fatal("a landed commit by change reinstalled HEAD whole instead of changing its changed chunks") + } + if flat != nil { + t.Fatalf("the layer keeps a flat map of %d chunks beside the ref table", len(flat)) } remote, err := f.GetHead(ctTimeout(t)) if err != nil { t.Fatal(err) } - if got := remote.Chunks; n != len(got) || ref2 != got[2] { - t.Fatalf("HEAD changed in place is not the remote's: %d chunks, chunk 2 %+v; remote %d, %+v", n, ref2, len(got), got[2]) + if !reflect.DeepEqual(whole.Chunks, remote.Chunks) { + t.Fatalf("HEAD changed in place is not the remote's: %d chunks, remote %d", len(whole.Chunks), len(remote.Chunks)) } for _, s := range []uint64{16384, 16384 / 16} { h := chunkHead{Gen: 5, Epoch: 1, Holder: "h", Chunks: make(map[uint64]chunkRef, s)} diff --git a/seaweed-block/core/storage/chunk_record_open.go b/seaweed-block/core/storage/chunk_record_open.go index 4574eabc93..803235fef6 100644 --- a/seaweed-block/core/storage/chunk_record_open.go +++ b/seaweed-block/core/storage/chunk_record_open.go @@ -52,7 +52,7 @@ func (l *chunkLayerImpl) openChunkRecordV11() (*chunkRecordShadow, error) { // the pages are valid through it). _, err := s.Sync() if err == nil { - seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, zero: l.zeroChunkSum()} + seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, ref: l.headRef, zero: l.zeroChunkSum()} err = upgradeChunkRecordSeeded(l.ctx, s, epoch, seed, l.attachProgress.add) } if h := testAfterChunkRecordUpgrade; h != nil { diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index 80a196dbe8..e8bbbd3493 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -18,16 +18,6 @@ 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. diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 1591befd2f..0252b6538e 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -158,7 +158,7 @@ func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) { t.Fatalf("an unraced fill: %s, want HP", k) } l.stMu.Lock() - want := l.head.Chunks[3].SHA256 + want := l.headChunk(3).SHA256 l.stMu.Unlock() l.shadow.rec.mu.Lock() got := l.shadow.rec.hashes[3] diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index 48bd87b7b1..e1f974b509 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -195,7 +195,10 @@ type ChunkCleanStop struct { type upgradeSeed struct { proof *ChunkCleanStop head chunkHead - zero [32]byte + // ref reads HEAD's chunks (the layer's ref table on the v1.1 format, + // where head lists none); nil: head.Chunks. + ref func(idx uint64) (chunkRef, bool) + zero [32]byte } // seedsLineage is the seed's lineage condition (the model's SameEpoch, by @@ -232,9 +235,12 @@ func cleanStopHashes(seed *upgradeSeed, pos uint64) func(uint64) [32]byte { return nil } log.Printf("level=INFO storage: chunk record upgrade: clean-stop seed at %d: whole local chunks take HEAD's hash", pos) - head, zero := seed.head, seed.zero + ref, zero := seed.ref, seed.zero + if ref == nil { + ref = headLookup(seed.head) + } return func(chunk uint64) [32]byte { - if ref, ok := head.Chunks[chunk]; ok { + if ref, ok := ref(chunk); ok { return ref.SHA256 } return zero diff --git a/seaweed-block/core/storage/chunk_ref_table_mirror_test.go b/seaweed-block/core/storage/chunk_ref_table_mirror_test.go deleted file mode 100644 index 7f36d0b55e..0000000000 --- a/seaweed-block/core/storage/chunk_ref_table_mirror_test.go +++ /dev/null @@ -1,43 +0,0 @@ -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) - } -} diff --git a/seaweed-block/core/storage/chunk_space_baseline_test.go b/seaweed-block/core/storage/chunk_space_baseline_test.go index c885a0ccc9..03c493a2eb 100644 --- a/seaweed-block/core/storage/chunk_space_baseline_test.go +++ b/seaweed-block/core/storage/chunk_space_baseline_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "fmt" - "os" "runtime" "strings" "testing" @@ -130,7 +129,13 @@ func TestSpaceMeasurementControls(t *testing.T) { long := strings.Repeat("v", 101) // a 100-byte longer owner name longer := heldPerChunk(t, chunks, 1, long) t.Logf("held per chunk with keys 100 B longer: %.0f B (+%.0f)", longer, longer-geo[1]) - if longer-geo[1] < 60 || longer-geo[1] > 160 { + if chunkV11Format { + // The ref table derives canonical keys from an interned owner prefix: + // a longer owner name costs once, not per chunk. + if d := longer - geo[1]; d > 10 || d < -10 { + t.Fatalf("keys 100 B longer moved the ref table's held heap by %.0f B/chunk, want about 0 (owner prefix interned)", d) + } + } else if longer-geo[1] < 60 || longer-geo[1] > 160 { t.Fatalf("keys 100 B longer moved the held heap by %.0f B/chunk, want about 100", longer-geo[1]) } } @@ -139,9 +144,10 @@ func TestSpaceMeasurementControls(t *testing.T) { // chunk for a 1 TiB volume's chunk count (262,144; one-block chunks, which // TestSpaceMeasurementControls shows stand for 4 MiB ones), every chunk // named by HEAD with canonical keys owned by the layer, after GC once the -// layer is attached. With CHUNK_SPACE_RED=1 it asserts the target, at most -// 200 B per chunk, which fails until PR 4 drops the flat map. +// layer is attached, on the v1.1 format (the layer keeps HEAD's chunks in +// the ref table, no flat map): at most 200 B per chunk. func TestSpacePerChunkAt1TiBShape(t *testing.T) { + withV11Format(t) const chunks = 262144 m0 := heapNow() oneMap := fullHead(chunks, "v1") @@ -151,8 +157,8 @@ func TestSpacePerChunkAt1TiBShape(t *testing.T) { per := heldPerChunk(t, chunks, 1, "v1") t.Logf("SPACE at 1 TiB's chunk count (%d chunks, v1.1 format %v, canonical %d-byte keys): %.0f B/chunk held after attach; one flat map with its keys is %.0f B/chunk", chunks, chunkV11Format, len(canonicalKey("v1", "309016fbc5b31531e1e7c44585851c7d", chunks-1, [32]byte{})), per, flat) - if os.Getenv("CHUNK_SPACE_RED") == "1" && per > 200 { - t.Fatalf("SPACE red: %.0f B/chunk, want at most 200", per) + if per > 200 { + t.Fatalf("SPACE: %.0f B/chunk held, want at most 200", per) } }