test(chunkstore): controls for the bounded commit check; wait and invariant ledger

Tests only, plus the ledger; the product code is unchanged.

- TestCommitLookupsNeverExceedTheCap: every lookup is held until the cap
  is reached; no 33rd starts (a cap-33 mutant fails it).
- TestACancelledCommitStopsJoinsAndWritesNothing: cancelled before any
  lookup and mid-flight, the commit returns within a bound with no lookup
  still running, admission stopped and HEAD not written (a mutant that
  keeps admitting after a failure starts 502 lookups and fails it).
- TestTheEarliestFailureByPositionDecidesTheError: of two failures the
  earlier position wins, whichever finishes first (a first-to-finish
  mutant fails it both ways).
- invariants.md: the admission and join waits of allOwnedBySession in
  C.W, and the scale, detach and control tests on
  INV-SNAPK-COMMIT-REACH-001.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-27 17:02:33 -08:00
1 parent aebf06e8d9
commit 786f3a4d82
3 files changed
+181 -3

No files matched your search

@@ -0,0 +1,175 @@
package layout
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
)
// scriptedObjects runs a per-object script around each Stat and counts the
// lookups in flight. Stat honours its context, as the production store does.
type scriptedObjects struct {
*memObjects
active, peak, started atomic.Int64
script func(ctx context.Context, rel string) error // nil: answer from the store
}
func (s *scriptedObjects) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) {
s.started.Add(1)
n := s.active.Add(1)
defer s.active.Add(-1)
for {
p := s.peak.Load()
if n <= p || s.peak.CompareAndSwap(p, n) {
break
}
}
if s.script != nil {
if err := s.script(ctx, rel); err != nil {
return ObjectMeta{}, false, err
}
}
return s.memObjects.Stat(ctx, rel)
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(time.Millisecond)
}
}
// The check never has more than commitVerifyParallel lookups in flight:
// every lookup is held until the test sees the cap reached, and no further
// lookup may start while they are held.
func TestCommitLookupsNeverExceedTheCap(t *testing.T) {
f, st, req := firstCommitOf(t, 500, "s1")
release := make(chan struct{})
so := &scriptedObjects{memObjects: f, script: func(ctx context.Context, _ string) error {
select {
case <-release:
return nil
case <-ctx.Done():
return ctx.Err()
}
}}
done := make(chan error, 1)
go func() { _, err := RunCommit(context.Background(), st, so, "v1", me, req); done <- err }()
waitFor(t, "the cap to be reached", func() bool { return so.active.Load() >= commitVerifyParallel })
time.Sleep(50 * time.Millisecond) // a 33rd lookup would start here if admission did not wait
if a, s := so.active.Load(), so.started.Load(); a != commitVerifyParallel || s != commitVerifyParallel {
t.Fatalf("while %d lookups are held: %d in flight, %d started; want exactly %d of each", commitVerifyParallel, a, s, commitVerifyParallel)
}
close(release)
if err := <-done; err != nil {
t.Fatal(err)
}
if p := so.peak.Load(); p > commitVerifyParallel {
t.Fatalf("peak %d lookups in flight; the cap is %d", p, commitVerifyParallel)
}
}
// A cancelled commit returns within a bound, with every admitted lookup
// joined (none still running), no further lookup started, and HEAD not
// written: before any lookup, and with the cap's worth of lookups in flight.
func TestACancelledCommitStopsJoinsAndWritesNothing(t *testing.T) {
for _, mid := range []bool{false, true} {
name := map[bool]string{false: "before any lookup", true: "mid-flight"}[mid]
t.Run(name, func(t *testing.T) {
f, st, req := firstCommitOf(t, 500, "s1")
before := *st.h
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
so := &scriptedObjects{memObjects: f, script: func(ctx context.Context, _ string) error {
<-ctx.Done() // a lookup that answers only when cancelled
return ctx.Err()
}}
if !mid {
cancel()
}
done := make(chan error, 1)
start := time.Now()
go func() { _, err := RunCommit(ctx, st, so, "v1", me, req); done <- err }()
if mid {
waitFor(t, "lookups in flight", func() bool { return so.active.Load() == commitVerifyParallel })
cancel()
}
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled commit: %v; want context.Canceled", err)
}
case <-time.After(5 * time.Second):
t.Fatal("a cancelled commit did not return within 5 s")
}
if a := so.active.Load(); a != 0 {
t.Fatalf("%d lookups still running after the commit returned; every admitted one must be joined", a)
}
if s := so.started.Load(); s > 2*commitVerifyParallel {
t.Fatalf("%d lookups started after the cancellation; admission must stop (at most about one cap's worth)", s)
}
if st.h.Gen != before.Gen || st.h.Current != nil {
t.Fatalf("HEAD written by a cancelled commit: %+v", *st.h)
}
t.Logf("returned after %v, %d lookups started", time.Since(start).Round(time.Millisecond), so.started.Load())
})
}
}
// Of two failures, the one at the earlier position decides the error, even
// when the later one finishes first: a slow lookup error at an early chunk
// against a fast "not prepared" at a later one, and the reverse.
func TestTheEarliestFailureByPositionDecidesTheError(t *testing.T) {
errSlow := errors.New("slow filer error")
for _, early := range []string{"lookup error", "not prepared"} {
t.Run(early+" first", func(t *testing.T) {
f, st, req := firstCommitOf(t, 400, "s1")
earlyRel, lateRel := req.Next[40].Chunk.Path(), req.Next[300].Chunk.Path()
var lateDone sync.WaitGroup
lateDone.Add(1)
so := &scriptedObjects{memObjects: f, script: func(ctx context.Context, rel string) error {
switch rel {
case earlyRel:
lateDone.Wait() // the later failure has already completed
if early == "lookup error" {
return errSlow
}
case lateRel:
defer lateDone.Done()
if early == "lookup error" {
return nil // reported "not prepared" below: it was removed
}
return errSlow
}
return nil
}}
if early == "lookup error" {
delete(f.objs, f.full(lateRel))
} else {
delete(f.objs, f.full(earlyRel))
}
before := *st.h
_, err := RunCommit(context.Background(), st, so, "v1", me, req)
switch early {
case "lookup error":
if !errors.Is(err, errSlow) {
t.Fatalf("error %v; want the earlier lookup error (index 40), not the later not-prepared", err)
}
case "not prepared":
if !errors.Is(err, ErrNotPrepared) || errors.Is(err, errSlow) {
t.Fatalf("error %v; want the earlier not-prepared (index 40), not the later lookup error", err)
}
}
if st.h.Gen != before.Gen {
t.Fatal("HEAD written by a refused commit")
}
})
}
}
@@ -44,8 +44,9 @@ func firstCommitOf(t *testing.T, n int, session string) (*memObjects, *memHead,
}
// A commit's check that every new chunk is this session's must not grow
// with the volume in serial filer round trips: a 1 TiB first snapshot names
// about 262k chunks, and one lookup each, one at a time, outlasted the
// with the changed data in serial filer round trips: a 1 TiB volume's
// snapshot named about 17k changed chunks, and one lookup each, one at a
// time, outlasted the
// cut's whole budget, on every retry. Here 6000 chunks at 1 ms a lookup
// take 6 s in series and must commit within a 2 s context.
func TestCommitVerifiesManyNewChunksWithinTheBudget(t *testing.T) {
+3 -1
View File
@@ -1062,7 +1062,7 @@ Notes:
| `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `Head.Commit` | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `Head.Commit` | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; host `chunkControl.Snapshot`, `ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE |
| `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | ACTIVE |
| `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE |
@@ -1134,6 +1134,8 @@ One row per wait in the data and control paths. Guest-visible rows on one path m
| `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no |
| `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (capacity one, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no |
| `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (one goroutine per recovery of a workspace chunk primary awaiting authority) | a healthy projection (own assignment and a lease grant), then the HEAD claim | none while blockmaster gives no reply or refuses the node's credentials or identity (it serves nothing and holds no lease); otherwise max(the first reply after the local open and recovery, the master's barrier time) + 30 s; each attach attempt 30 s | the host's contact observations (`core/host/volume/master_wait.go`), provider Close, a later recovery | exit 75 `assignment_timeout`; 78 `moved` or `deleted` at once on a typed refusal | none: the bound is read on the 20 ms poll without `p.mu` or `h.attachMu` | no (no target listens) |
| `core/frontend/chunkstore/layout/commit.go` `allOwnedBySession`, admission (`sem <-`, on the commit caller's goroutine) | a free slot among `commitVerifyParallel` (32) object lookups in flight | one lookup's duration: each admitted lookup honours the commit's context (`ObjectStore.Stat` returns on cancellation) and frees its slot when it returns | the admitted lookup's goroutine (`<-sem` on return) | none of its own: the caller's context ends the lookups; once any lookup fails, no further one is admitted | none (the HEAD store is not held during the object check) | indirect: within the cut or snapshot deadline (5 min) |
| `core/frontend/chunkstore/layout/commit.go` `allOwnedBySession`, join (`wg.Wait`) | every admitted lookup to return | the slowest admitted lookup, bounded by the commit's context | `allOwnedBySession` (it admitted them; it returns only after the join, so none outlives the call) | none of its own, as the admission row | none | indirect: within the cut or snapshot deadline (5 min) |
Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step.