storage: on v1.1 a cut commits by change; an unresolved one is re-proposed with the same changes

On the draft v1.1 format a cut's commit check and CAS go to the remote by
change (CheckCommitDelta, CASHeadDelta) with one owned change set built
from the chunks the cut changed; an unresolved commit keeps that set and
the settlement re-proposes it at the same base. Release builds keep the
full commit. The commit-site guard now also requires a by-change check
before a by-change commit, and the test remotes that hook CASHead route
CASHeadDelta through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 04:13:58 -08:00
1 parent f647bfa955
commit 80a9dcb898
7 files changed
+457 -15

No files matched your search

@@ -21,7 +21,9 @@ import (
// site fails here until it checks first and is listed. The holder's snapshot
// of an unchanged image commits outside this package and outside the HEAD
// step: it calls the commit directly under its caller's limit, so it is not
// this path.
// this path. A commit by change (the ...By forms, CASHeadDelta) must be
// checked by change first (checkCommitFirstBy): a full check before a delta
// commit checks another proposal.
func TestEveryHeadCommitIsCheckedFirst(t *testing.T) {
sites := map[string]string{
"captureLocked": "the cut's commit",
@@ -51,7 +53,7 @@ func TestEveryHeadCommitIsCheckedFirst(t *testing.T) {
if !ok || fn.Body == nil {
continue
}
var checks, commits []token.Pos
var checks, checksBy, commits, commitsBy []token.Pos
ast.Inspect(fn.Body, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
@@ -62,13 +64,22 @@ func TestEveryHeadCommitIsCheckedFirst(t *testing.T) {
switch callee.Name {
case "casChunkHead", "casAndConfirmChunkHead", "casAndConfirmChunkHeadMeasured":
commits = append(commits, call.Pos())
case "casChunkHeadBy", "casAndConfirmChunkHeadBy":
commits = append(commits, call.Pos())
commitsBy = append(commitsBy, call.Pos())
}
case *ast.SelectorExpr:
switch callee.Sel.Name {
case "checkCommitFirst":
checks = append(checks, call.Pos())
case "checkCommitFirstBy":
checks = append(checks, call.Pos())
checksBy = append(checksBy, call.Pos())
case "CASHead":
commits = append(commits, call.Pos())
case "CASHeadDelta":
commits = append(commits, call.Pos())
commitsBy = append(commitsBy, call.Pos())
}
}
return true
@@ -90,6 +101,17 @@ func TestEveryHeadCommitIsCheckedFirst(t *testing.T) {
t.Errorf("%s: %s (%s) commits HEAD without checkCommitFirst before it", fset.Position(at), site, sites[site])
}
}
for _, at := range commitsBy {
first := false
for _, c := range checksBy {
if c < at {
first = true
}
}
if !first {
t.Errorf("%s: %s commits by change without checkCommitFirstBy before it", fset.Position(at), fn.Name.Name)
}
}
}
}
var missing []string
@@ -0,0 +1,48 @@
package storage
import "context"
// casDeltaVia makes a test remote's commit by change go through its own
// CASHead (its hooks, faults, delays and counters): the change set applied
// to the inner remote's HEAD, as the remotes' CASHeadDelta defines it, then
// the wrapper's full CASHead. A wrapper that overrides CASHead only would
// otherwise see no commit at all from a layer that commits by change (the
// embedded remote's CASHeadDelta bypasses it).
func casDeltaVia(ctx context.Context, get func(context.Context) (chunkHead, error),
cas func(context.Context, chunkHeadVersion, chunkHead) (uint64, error),
expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) (uint64, error) {
h, err := get(ctx)
if err != nil {
return 0, err
}
next.Chunks = ApplyChunkChanges(h.Chunks, changes)
return cas(ctx, expected, next)
}
func (r *currentCutHeldRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.fakeChunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *crashRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.fakeChunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *fixedSpanRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.fakeChunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *stepRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.chunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *plainCASRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.chunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *precopyTimedHeadRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.fakeChunkRemote.GetHead, r.CASHead, e, n, c)
}
func (r *claimFaultRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, c map[uint64]*chunkRef) (uint64, error) {
return casDeltaVia(ctx, r.ChunkRemote.GetHead, r.CASHead, e, n, c)
}
+22 -3
View File
@@ -57,15 +57,28 @@ func WithChunkCASAccounting(ctx context.Context) (context.Context, func() uint64
// that prepares. Either way no write of this CAS lands later than the bound
// after it was issued, which the HEAD cooling window relies on.
func casChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead) (uint64, error) {
return casChunkHeadBy(ctx, remote, expected, next, nil)
}
// casChunkHeadBy is casChunkHead by change when changes is not nil: the
// remote's CASHeadDelta with next's identity and the chunks that changed
// (the same changes map its commit check was given), under the same bound.
func casChunkHeadBy(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) (uint64, error) {
if counter, _ := ctx.Value(chunkCASCountKey{}).(*atomic.Uint64); counter != nil {
counter.Add(1)
}
cas := func(ctx context.Context) (uint64, error) {
if changes != nil {
return remote.CASHeadDelta(ctx, expected, next, changes)
}
return remote.CASHead(ctx, expected, next)
}
if b, ok := remote.(chunkHeadStepBounder); ok && b.BoundsHeadStep() {
return remote.CASHead(WithChunkHeadStepBudget(ctx, chunkHeadOperationTimeout), expected, next)
return cas(WithChunkHeadStepBudget(ctx, chunkHeadOperationTimeout))
}
ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout)
defer cancel()
return remote.CASHead(ctx, expected, next)
return cas(ctx)
}
// readChunkHead reads HEAD with its whole manifest. A remote that bounds
@@ -128,8 +141,14 @@ func casAndConfirmChunkHead(ctx context.Context, remote chunkRemote, expected ch
}
func casAndConfirmChunkHeadMeasured(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead, st *chunkCutStats) (uint64, error) {
return casAndConfirmChunkHeadBy(ctx, remote, expected, next, nil, st)
}
// casAndConfirmChunkHeadBy is casAndConfirmChunkHeadMeasured by change when
// changes is not nil (casChunkHeadBy); the confirmation is the same.
func casAndConfirmChunkHeadBy(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef, st *chunkCutStats) (uint64, error) {
start := time.Now()
gen, err := casChunkHead(ctx, remote, expected, next)
gen, err := casChunkHeadBy(ctx, remote, expected, next, changes)
if st != nil {
st.CASWriteNs += time.Since(start).Nanoseconds()
}
+57 -10
View File
@@ -154,7 +154,12 @@ type chunkLayerImpl struct {
// captured version and hash, no bytes): the record's Commit for them
// waits for the settlement that finds the proposal landed.
pendingCaptured []capturedChunk
pendingCut chunkCutResult
// pendingChanges is the unresolved commit's change set when it was a
// commit by change (nil: a full commit): the settlement re-proposes the
// SAME changes at the same base, never a recomputed set. Owned: nothing
// writes it after the commit that made it.
pendingChanges map[uint64]*chunkRef
pendingCut chunkCutResult
// pendingBase is the version the unresolved CAS expected. While HEAD is
// still at it, that CAS may still land, so a read alone never settles it.
pendingBase chunkHeadVersion
@@ -1428,13 +1433,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{H: h, Head: copyHead(cur), 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,
// built once from the captured chunks, for the check, the CAS and an
// unresolved commit's settlement alike (nil: the full commit).
changes := l.commitChanges(next, changed)
// A lookup failure writes nothing and leaves the session open; the dirty
// set returns for the next cut.
// ManifestNs is the manifest work of the commit check only: the check
// runs outside every other measured part, while a HEAD re-read (a
// settlement) reads the manifest inside HeadReadbackNs.
manifestBefore := work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load()
checkErr := l.checkCommitFirst(ctx, expected, next)
checkErr := l.checkCommitFirstBy(ctx, expected, next, changes)
st.ManifestNs += work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - manifestBefore
if err := checkErr; err != nil {
l.requeueCut(all)
@@ -1454,7 +1463,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
l.cutPhase("commit")
casStart := time.Now()
gen, casErr := casAndConfirmChunkHeadMeasured(ctx, l.remote, expected, next, &st)
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, next, changes, &st)
st.CASNs = time.Since(casStart).Nanoseconds()
st.CASResult = "ok"
if errors.Is(casErr, errChunkHeadPrecondition) {
@@ -1478,6 +1487,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
l.pending = &p
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = detach, chunkCutResult{H: h, FullHash: all}, expected, false
l.pendingCaptured = pendingCapture(captured, capturedVersions)
l.pendingChanges = changes
l.stMu.Unlock()
// The session stays open: the commit may still land, and the
// settlement replays it in the same session (resolvePending).
@@ -1618,7 +1628,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
l.pending = nil
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false
landed := l.pendingCaptured
l.pendingCaptured = nil
l.pendingCaptured, l.pendingChanges = nil, nil
switch {
case sameProposal(cur, *pending):
l.noteSettled(l.head, cur)
@@ -1747,17 +1757,54 @@ func sameProposal(cur, next chunkHead) bool {
// passes. A precondition or fence goes on to the CAS, which answers it from
// HEAD (before any lookup) and resolves it as without the check.
func (l *chunkLayerImpl) checkCommitFirst(ctx context.Context, expected chunkHeadVersion, next chunkHead) error {
return l.checkCommitFirstBy(ctx, expected, next, nil)
}
// checkCommitFirstBy is checkCommitFirst by change when changes is not nil:
// CheckCommitDelta with the change set the CAS will carry.
func (l *chunkLayerImpl) checkCommitFirstBy(ctx context.Context, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) error {
defer MeasureCutWork(ctx, CutCommitCheck)()
c, ok := l.remote.(chunkCommitChecker)
if !ok {
return nil
}
if err := c.CheckCommit(ctx, expected, next); err != nil && !errors.Is(err, errChunkHeadPrecondition) && !errors.Is(err, errChunkLayerFenced) {
var err error
if changes != nil {
err = c.CheckCommitDelta(ctx, expected, next, changes)
} else {
err = c.CheckCommit(ctx, expected, next)
}
if err != nil && !errors.Is(err, errChunkHeadPrecondition) && !errors.Is(err, errChunkLayerFenced) {
return err
}
return nil
}
// commitByChange reports whether this layer's cuts commit by change: on the
// draft v1.1 format (its chunk record is open there); release builds keep
// the full commit until the format is declared.
func (l *chunkLayerImpl) commitByChange() bool { return l.shadow != nil && l.shadow.v11 }
// commitChanges is the change set of a cut's commit by change (nil when the
// layer commits in full): each changed chunk's new reference, or nil for a
// chunk now read as zeros, from next. Owned (each reference copied): the
// check, the CAS and a later settlement read the same set.
func (l *chunkLayerImpl) commitChanges(next chunkHead, changed []uint64) map[uint64]*chunkRef {
if !l.commitByChange() {
return nil
}
out := make(map[uint64]*chunkRef, len(changed))
for _, idx := range changed {
if ref, ok := next.Chunks[idx]; ok {
r := ref
out[idx] = &r
} else {
out[idx] = nil
}
}
return out
}
func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
// Registered before the state unlock, so invalidation runs without stMu.
defer func() {
@@ -1766,7 +1813,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
}
}()
l.stMu.Lock()
pending, base, aborted := l.pending, l.pendingBase, l.pendingAborted
pending, base, aborted, changes := l.pending, l.pendingBase, l.pendingAborted, l.pendingChanges
l.stMu.Unlock()
if pending == nil {
return nil
@@ -1786,10 +1833,10 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
if err := l.admit(); err != nil {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err)
}
if err := l.checkCommitFirst(ctx, base, *pending); err != nil {
if err := l.checkCommitFirstBy(ctx, base, *pending, changes); err != nil {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal check failed: %w", errChunkCASOutcomeUnknown, err)
}
gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, copyHead(*pending))
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, copyHead(*pending), changes, nil)
if casErr == nil {
cur = copyHead(*pending)
cur.Gen = gen
@@ -1817,7 +1864,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
wasDetach, cut := l.pendingDetach, l.pendingCut
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false
landed := l.pendingCaptured
l.pendingCaptured = nil
l.pendingCaptured, l.pendingChanges = nil, nil
switch {
case sameProposal(cur, *pending):
l.noteSettled(l.head, cur)
@@ -2161,7 +2208,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n
defer l.stMu.Unlock()
l.noteSettled(l.head, head)
l.head, l.remoteLSN, l.pending = copyHead(head), h, nil
l.pendingCaptured = nil
l.pendingCaptured, l.pendingChanges = nil, nil
l.reusable = nil
l.inflight = map[uint64]bool{}
l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
@@ -0,0 +1,168 @@
package storage
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"testing"
)
// deltaSpyRemote records every commit check and CAS a layer sends, full or
// by change; lose makes the next CAS by change answer an unknown outcome
// without applying it (a lost request).
type deltaSpyRemote struct {
*fakeChunkRemote
mu sync.Mutex
fullChecks, fullCAS int
checks, deltas []map[uint64]*chunkRef
lose bool
}
func (r *deltaSpyRemote) CheckCommit(context.Context, chunkHeadVersion, chunkHead) error {
r.mu.Lock()
defer r.mu.Unlock()
r.fullChecks++
return nil
}
func (r *deltaSpyRemote) CheckCommitDelta(_ context.Context, _ chunkHeadVersion, _ chunkHead, changes map[uint64]*chunkRef) error {
r.mu.Lock()
defer r.mu.Unlock()
r.checks = append(r.checks, changes)
return nil
}
func (r *deltaSpyRemote) CASHead(ctx context.Context, e chunkHeadVersion, n chunkHead) (uint64, error) {
r.mu.Lock()
r.fullCAS++
r.mu.Unlock()
return r.fakeChunkRemote.CASHead(ctx, e, n)
}
func (r *deltaSpyRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n chunkHead, changes map[uint64]*chunkRef) (uint64, error) {
r.mu.Lock()
r.deltas = append(r.deltas, changes)
lose := r.lose
r.lose = false
r.mu.Unlock()
if lose {
return 0, errors.New("spy: the request was lost")
}
return r.fakeChunkRemote.CASHeadDelta(ctx, e, n, changes)
}
func deltaSpyLayer(t *testing.T) (*WALStore, *chunkLayerImpl, *deltaSpyRemote) {
t.Helper()
s, _ := v11Store(t)
spy := &deltaSpyRemote{fakeChunkRemote: newFakeChunkRemote()}
cfg := ctConfig(1)
cfg.Bitmap = nil
return s, mustAttach(t, s, spy, cfg).(*chunkLayerImpl), spy
}
func refsOf(m map[uint64]*chunkRef) map[uint64]chunkRef {
out := map[uint64]chunkRef{}
for k, v := range m {
if v == nil {
out[k] = chunkRef{Key: "<zero>"}
} else {
out[k] = *v
}
}
return out
}
// On the v1.1 format a cut commits by change: its check and its CAS carry
// the SAME change set, exactly the chunks the cut changed with the
// references HEAD then names, and no full check or CAS is sent. On v1.0 the
// cut still commits in full.
func TestV11CutCommitsByChange(t *testing.T) {
t.Run("v1.1", func(t *testing.T) {
withV11Format(t)
s, l, spy := deltaSpyLayer(t)
if _, err := s.Write(2*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xA1)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if spy.fullChecks != 0 || spy.fullCAS != 0 || len(spy.checks) != 1 || len(spy.deltas) != 1 {
t.Fatalf("full checks %d, full CAS %d, checks by change %d, CAS by change %d; want 0, 0, 1, 1",
spy.fullChecks, spy.fullCAS, len(spy.checks), len(spy.deltas))
}
got := refsOf(spy.deltas[0])
head, err := spy.GetHead(context.Background())
if err != nil {
t.Fatal(err)
}
if want := map[uint64]chunkRef{2: head.Chunks[2]}; !reflect.DeepEqual(got, want) {
t.Fatalf("the change set %v, want only chunk 2 as HEAD names it %v", got, want)
}
if fmt.Sprintf("%p", spy.checks[0]) != fmt.Sprintf("%p", spy.deltas[0]) {
t.Fatal("the check and the CAS were given different change sets")
}
})
t.Run("v1.0", func(t *testing.T) {
v10Only(t)
s, l, spy := deltaSpyLayer(t)
if _, err := s.Write(2*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xA1)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if spy.fullChecks != 1 || spy.fullCAS != 1 || len(spy.checks) != 0 || len(spy.deltas) != 0 {
t.Fatalf("full checks %d, full CAS %d, by change %d/%d; want the full commit only",
spy.fullChecks, spy.fullCAS, len(spy.checks), len(spy.deltas))
}
})
}
// A commit by change whose outcome is unknown is settled by re-proposing the
// SAME change set at the same base (never a recomputed one, which could
// differ after later writes): the next cut's settlement sends that set,
// checked first, and HEAD ends with the change; the written chunk is not
// lost.
func TestV11UnknownCommitByChangeReproposesTheSameChanges(t *testing.T) {
withV11Format(t)
s, l, spy := deltaSpyLayer(t)
want := makeBlock(ctBlockSize, 0xB2)
if _, err := s.Write(3*ctChunkBlocks, want); err != nil {
t.Fatal(err)
}
spy.lose = true
if _, err := l.Cut(ctTimeout(t)); err == nil {
t.Fatal("a cut whose CAS was lost reported success")
}
if len(spy.deltas) != 1 {
t.Fatalf("%d CAS by change; want 1", len(spy.deltas))
}
lost := spy.deltas[0]
// A later write to another chunk: the settlement must not fold it in.
if _, err := s.Write(5*ctChunkBlocks, makeBlock(ctBlockSize, 0xC3)); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if len(spy.deltas) < 2 || fmt.Sprintf("%p", spy.deltas[1]) != fmt.Sprintf("%p", lost) {
t.Fatalf("the settlement did not re-propose the lost change set (%d CAS by change)", len(spy.deltas))
}
if !reflect.DeepEqual(refsOf(spy.deltas[1]), refsOf(lost)) {
t.Fatal("the re-proposed change set differs from the lost one")
}
if len(spy.checks) < 2 || fmt.Sprintf("%p", spy.checks[1]) != fmt.Sprintf("%p", lost) {
t.Fatal("the re-proposal was not checked by change first with the same set")
}
head, err := spy.GetHead(context.Background())
if err != nil {
t.Fatal(err)
}
for _, c := range []uint64{3, 5} {
if _, ok := head.Chunks[c]; !ok {
t.Fatalf("chunk %d is not in HEAD after the settlement and the next cut: %v", c, head.Chunks)
}
}
}
@@ -0,0 +1,94 @@
package storage_test
import (
"context"
"fmt"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type memBlobs struct {
mu sync.Mutex
b map[string][]byte
}
func (m *memBlobs) Put(_ context.Context, data []byte) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
fid := fmt.Sprintf("1,%x", len(m.b)+1)
m.b[fid] = append([]byte(nil), data...)
return fid, nil
}
func (m *memBlobs) Get(_ context.Context, fid string) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()
b, ok := m.b[fid]
if !ok {
return nil, chunkstore.ErrBlobNotFound
}
return append([]byte(nil), b...), nil
}
type endedLease struct{}
func (endedLease) OldLeaseEnded(context.Context, uint64) error { return nil }
// A one-chunk cut on a volume of three shards, through the real layout
// remote, reads HEAD's root and the one segment the change touches and
// writes one segment (SegCut rows 137-142: an untouched segment is never
// read): on the v1.1 format, where the cut commits by change. On v1.0 the
// full commit reads every segment (the control).
func TestV11OneChunkCutReadsOnlyItsShard(t *testing.T) {
for _, tc := range []struct {
name string
v11 bool
segReads int64
}{{"v1.1", true, 1}, {"v1.0", false, 3}} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
chunks := uint32(3 * layout.ShardSize)
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &memBlobs{b: map[string][]byte{}}, "/cuts")
if err != nil {
t.Fatal(err)
}
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
v := chunkstore.VolumeRef{Name: "v1", ID: id}
geo := layout.Geometry{SizeBytes: uint64(chunks) * 4096, BlockSize: 4096, ChunkBytes: 4096}
if _, err := cat.CreateVolume(ctx, v, geo); err != nil {
t.Fatal(err)
}
st, err := cat.Store(v)
if err != nil {
t.Fatal(err)
}
me := layout.HolderID{Epoch: 1, Holder: "host-a", ClaimID: "k-a"}
if _, err := layout.Start(ctx, st, endedLease{}, layout.HolderID{Epoch: 1, Holder: "host-a"},
layout.LocalRoot{Geometry: geo, ClaimID: "k-a", Fresh: true, CanStartFrom: func(layout.Head) error { return nil }}); err != nil {
t.Fatal(err)
}
remote, err := chunkstore.NewLayoutRemote(cat, v, me)
if err != nil {
t.Fatal(err)
}
write, cut := storage.CutWorkForTest(t, remote, chunks, 1, "host-a", tc.v11)
for sh := uint32(0); sh < 3; sh++ { // every shard holds a chunk
write(sh*layout.ShardSize+7, byte(0x10+sh))
}
cut()
write(layout.ShardSize+9, 0x99) // one chunk, in shard 1
segReads, segWrites, rootReads := cut()
if segReads != tc.segReads || segWrites != 1 || rootReads != 1 {
t.Fatalf("a one-chunk cut read %d segments and %d roots, wrote %d segments; want %d, 1, 1",
segReads, rootReads, segWrites, tc.segReads)
}
})
}
}
@@ -0,0 +1,44 @@
package storage
import "testing"
// CutWorkForTest exposes a chunk layer on a mapped store of numBlocks
// one-block chunks, attached to remote (the external regression uses
// chunkstore's LayoutRemote), on the v1.1 format when v11 is set: write
// writes one block, cut cuts and reports the cut's manifest reads and writes.
func CutWorkForTest(t *testing.T, remote ChunkRemote, numBlocks uint32, epoch uint64, holder string, v11 bool) (write func(lba uint32, fill byte), cut func() (segReads, segWrites, rootReads int64)) {
t.Helper()
if v11 {
withV11Format(t)
} else {
v10Only(t)
}
s, err := createMappedWALStoreV3ForTest(t.TempDir()+"/mapped", numBlocks, 4096, v3TestWAL, WModeStrict, 1)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { s.Close() })
s.HoldExtentDrainUntilChunkLayer()
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
cfg := ctConfig(epoch)
cfg.ChunkBlocks, cfg.Holder, cfg.Bitmap = 1, holder, nil
layer := mustAttach(t, s, remote, cfg)
write = func(lba uint32, fill byte) {
t.Helper()
if _, err := s.Write(lba, blk(fill)); err != nil {
t.Fatal(err)
}
}
cut = func() (int64, int64, int64) {
t.Helper()
res, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
return res.Stats.ManifestSegmentReads, res.Stats.ManifestSegmentWrites, res.Stats.ManifestRootReads
}
return write, cut
}