mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Merge main into the declare-format branch: the HEAD guard with the stamp
runTransition now runs the format level guard first (it refuses only a raise of HEAD from version 0 to 1 below level 1; stamping never changes the version, so a refused write is never stamped), then the write-time snapshot stamp, then the write check. The stamp tests run a v1.1 holder's cut at level 1; the v1.0 landing control pins v1.0 whatever the package mode. Both invariant rows are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1e40d947da
30 files changed
+2149
-162
No files matched your search
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests require-nvme.sh with df and lsblk replaced by stubs on PATH.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
t=$(mktemp -d)
|
||||
trap 'rm -rf "$t"' EXIT
|
||||
mkdir -p "$t/bin" "$t/nvme" "$t/sata" "$t/mem" "$t/raid" "$t/share" "$t/half"
|
||||
# df --output=source,fstype DIR: the stub answers by the directory's name.
|
||||
cat >"$t/bin/df" <<STUB
|
||||
#!/usr/bin/env bash
|
||||
printf 'Filesystem Type\n'
|
||||
case "\$2" in
|
||||
$t/nvme*) echo '/dev/nvme0n1p1 ext4' ;;
|
||||
$t/mem*) echo 'shm tmpfs' ;;
|
||||
$t/raid*) echo '/dev/md0 ext4' ;;
|
||||
$t/share*) echo '//nas/work cifs' ;;
|
||||
$t/half*) echo '/dev/nvme1n1p1 ext4' ;;
|
||||
*) echo '/dev/sda2 ext4' ;;
|
||||
esac
|
||||
STUB
|
||||
# lsblk -nrso TYPE,TRAN SOURCE: the source and the devices under it.
|
||||
cat >"$t/bin/lsblk" <<'STUB'
|
||||
#!/usr/bin/env bash
|
||||
case "$3" in
|
||||
/dev/nvme0n1p1) printf 'part \ndisk nvme\n' ;;
|
||||
/dev/sda2) printf 'part \ndisk sata\n' ;;
|
||||
/dev/md0) printf 'raid1 \npart \ndisk nvme\npart \ndisk sata\n' ;;
|
||||
/dev/nvme1n1p1) printf 'part \ndisk nvme\n'; echo "lsblk: read error" >&2; exit 32 ;;
|
||||
*) echo "lsblk: $3: not a block device" >&2; exit 32 ;;
|
||||
esac
|
||||
STUB
|
||||
chmod +x "$t/bin/df" "$t/bin/lsblk"
|
||||
run() { PATH="$t/bin:$PATH" RUNNER_NAME=r1 bash "$here/require-nvme.sh" "$@" >"$t/out" 2>&1; }
|
||||
fail() { echo "FAIL: $*"; cat "$t/out"; exit 1; }
|
||||
|
||||
run "$t/nvme" "$t/mem" "" || fail "nvme + tmpfs (any source name) + empty arg must pass"
|
||||
run "$t/nvme/not/made/yet" || fail "a missing dir is judged by its nearest existing parent"
|
||||
! run "$t/nvme" "$t/sata" || fail "a SATA dir must fail"
|
||||
grep -q "runner r1" "$t/out" || fail "the failure must name the runner"
|
||||
grep -q "FAIL $t/sata" "$t/out" || fail "the failure must name the directory"
|
||||
! run "$t/raid" || fail "an array with a SATA member must fail"
|
||||
! run "$t/share" || fail "a network share must fail"
|
||||
grep -q "not a block device" "$t/out" || fail "a network share must say why"
|
||||
! run "$t/half" || fail "an lsblk error after partial NVMe output must fail"
|
||||
echo "require-nvme tests: ok"
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails a self-hosted job whose workspace, temp or Go cache directory is not
|
||||
# on an NVMe disk. The process-level tests write and fsync real files; on a
|
||||
# box whose system disk is SATA, a default runner install puts _work there and
|
||||
# the tests time out under the disk load instead of failing on a real bug.
|
||||
# A tmpfs directory is accepted (memory, not a slow disk).
|
||||
# Usage: require-nvme.sh DIR...
|
||||
set -euo pipefail
|
||||
bad=0
|
||||
for p in "$@"; do
|
||||
[ -n "$p" ] || continue
|
||||
d=$p
|
||||
while [ ! -e "$d" ]; do d=$(dirname "$d"); done
|
||||
read -r src fstype < <(df --output=source,fstype "$d" | tail -n 1)
|
||||
if [ "$fstype" = tmpfs ]; then
|
||||
echo "ok $p: $src (tmpfs)"
|
||||
continue
|
||||
fi
|
||||
# Every disk under the source (all members of an array) must be NVMe; an
|
||||
# lsblk error voids whatever it printed.
|
||||
disks=
|
||||
if tree=$(lsblk -nrso TYPE,TRAN "$src" 2>/dev/null); then
|
||||
disks=$(printf '%s\n' "$tree" |
|
||||
awk '$1 == "disk" { print ($2 == "" ? "unknown" : $2) }' | sort -u | tr '\n' ' ')
|
||||
fi
|
||||
if [ "$disks" = "nvme " ]; then
|
||||
echo "ok $p: $src (nvme)"
|
||||
else
|
||||
echo "FAIL $p: $src (disk: ${disks:-not a block device})"
|
||||
bad=1
|
||||
fi
|
||||
done
|
||||
if [ "$bad" -ne 0 ]; then
|
||||
echo "runner ${RUNNER_NAME:-?}: work, temp and Go cache directories must be on NVMe; move them before this runner takes jobs" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -27,6 +27,15 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Runner disk is NVMe
|
||||
# A self-hosted runner whose work, temp or Go cache directory sits on a
|
||||
# SATA system disk times the process-level tests out under disk load;
|
||||
# this names the runner and stops the job before it starts.
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: |
|
||||
bash .github/scripts/require-nvme-test.sh
|
||||
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
|
||||
+9
@@ -55,6 +55,15 @@ jobs:
|
||||
# step can see which packages the PR touches.
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Runner disk is NVMe
|
||||
# A self-hosted runner whose work, temp or Go cache directory sits on a
|
||||
# SATA system disk times the process-level tests out under disk load;
|
||||
# this names the runner and stops the job before it starts.
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: |
|
||||
bash .github/scripts/require-nvme-test.sh
|
||||
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
|
||||
|
||||
- name: Docs-only pull request
|
||||
id: scope
|
||||
if: matrix.suite == 'process' && github.event_name == 'pull_request'
|
||||
|
||||
@@ -681,10 +681,19 @@ func runTransition(ctx context.Context, st HeadStore, cause HeadWriteCause, t fu
|
||||
if err != nil || !changed {
|
||||
return next, err
|
||||
}
|
||||
// The format level guard judges the write first (it refuses only a raise
|
||||
// of HEAD from version 0 to 1 below level 1; stamping never changes the
|
||||
// version), so a refused write is never stamped. Then every write that
|
||||
// leaves a version-1 HEAD stamps its unstamped snapshots here, once for
|
||||
// every writer: a legacy snapshot of an upgraded volume and one this
|
||||
// write creates both get this write's generation.
|
||||
if err := checkFormatLevel(ctx, h, next); err != nil {
|
||||
return Head{}, err
|
||||
}
|
||||
if err := next.check(); err != nil {
|
||||
if next, err = next.stampedForWrite(h.Gen); err != nil {
|
||||
return Head{}, err
|
||||
}
|
||||
if err := next.checkWrite(); err != nil {
|
||||
return Head{}, err
|
||||
}
|
||||
// Preserve the observed session for logging when the transition closes it.
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
// ErrSnapshotGenerationMissing refuses admission against an unstamped legacy
|
||||
// snapshot. Zero is not an incarnation and cannot be a delete target.
|
||||
var ErrSnapshotGenerationMissing = errors.New("layout: snapshot needs its v1.1 publishing generation: start a v1.1 holder to upgrade HEAD")
|
||||
var ErrSnapshotGenerationMissing = errors.New("layout: snapshot needs its v1.1 publishing generation: the first HEAD write by a v1.1 holder (its first cut) stamps it")
|
||||
|
||||
// ErrHeadGenerationExhausted refuses publication instead of wrapping an
|
||||
// incarnation to zero.
|
||||
@@ -35,13 +35,55 @@ func (h Head) StampSnapshotGenerations() (Head, bool, error) {
|
||||
}
|
||||
next := h.clone()
|
||||
next.Version = HeadVersion1
|
||||
next, err := next.stampedForWrite(h.Gen)
|
||||
if err != nil {
|
||||
return Head{}, false, err
|
||||
}
|
||||
return next, true, nil
|
||||
}
|
||||
|
||||
// stampedForWrite gives every unstamped snapshot of a version-1 HEAD the
|
||||
// generation the write over base publishes (base + 1). A version-0 HEAD and
|
||||
// a fully stamped one come back as they are. runTransition applies it to
|
||||
// every write, so no writer leaves a version-1 HEAD with an unstamped entry.
|
||||
func (h Head) stampedForWrite(base uint64) (Head, error) {
|
||||
if h.Version != HeadVersion1 || !h.hasUnstampedSnapshot() {
|
||||
return h, nil
|
||||
}
|
||||
if base == ^uint64(0) {
|
||||
return Head{}, ErrHeadGenerationExhausted
|
||||
}
|
||||
next := h.clone()
|
||||
for name, s := range next.Snapshots {
|
||||
if s.Gen == 0 {
|
||||
s.Gen = h.Gen + 1
|
||||
s.Gen = base + 1
|
||||
next.Snapshots[name] = s
|
||||
}
|
||||
}
|
||||
return next, true, nil
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func (h Head) hasUnstampedSnapshot() bool {
|
||||
for _, s := range h.Snapshots {
|
||||
if s.Gen == 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkWrite is check for a HEAD about to be written: a version-1 HEAD
|
||||
// carries no unstamped snapshot. Reads stay tolerant (DecodeHead re-encodes
|
||||
// through check), so a version-1 HEAD written before stamping still opens,
|
||||
// and its next write stamps it.
|
||||
func (h Head) checkWrite() error {
|
||||
if err := h.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Version == HeadVersion1 && h.hasUnstampedSnapshot() {
|
||||
return fmt.Errorf("%w: a version-1 HEAD write leaves a snapshot without its publishing generation", ErrMalformed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteSnapshotAt removes only an already admitted incarnation. Admission
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// v11Commit is the HEAD step of a v1.1 holder's cut (RunCommit's
|
||||
// transition without the object checks): Commit, then the v1.1 manifest
|
||||
// size step, which writes HEAD version 1.
|
||||
func v11Commit(t *testing.T, st *memHead, snapshot string) Head {
|
||||
t.Helper()
|
||||
me := HolderID{Holder: "srv-a", Epoch: 3, ClaimID: "k-a"}
|
||||
root := RootName{Hash: Sum([]byte("image " + snapshot))}
|
||||
h, err := runTransition(WithFormatLevel(context.Background(), 1), st, CauseCommit, func(h Head) (Head, bool, error) { // a v1.1 holder runs at level 1
|
||||
next, changed, err := h.Commit(me, "s", root, h.Position+1, snapshot, SnapshotMeta{}, StateLive)
|
||||
if err == nil && changed {
|
||||
next = next.withManifestBytes(snapshot, nil, true)
|
||||
}
|
||||
return next, changed, err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("v1.1 commit: %v", err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func openSnapHead() Head {
|
||||
h := idleHead()
|
||||
h.State = StateLive
|
||||
h.Activity = Activity{Kind: ActSnap, Session: "s"}
|
||||
return h
|
||||
}
|
||||
|
||||
// A snapshot a v1.1 holder's cut creates carries the generation of the
|
||||
// write that published it, so it can be deleted by its captured target.
|
||||
func TestV11CutPublishesASnapshotThatCanBeDeletedByItsTarget(t *testing.T) {
|
||||
h := openSnapHead()
|
||||
st := &memHead{h: &h}
|
||||
after := v11Commit(t, st, "daily")
|
||||
gen := after.Snapshots["daily"].Gen
|
||||
if after.Version != HeadVersion1 || gen != h.Gen+1 {
|
||||
t.Fatalf("the cut's snapshot: version %d gen %d, want version 1 gen %d", after.Version, gen, h.Gen+1)
|
||||
}
|
||||
if _, err := RunDeleteSnapshotAt(context.Background(), st, "daily", gen); err != nil {
|
||||
t.Fatalf("delete by target: %v", err)
|
||||
}
|
||||
if _, ok := st.h.Snapshots["daily"]; ok {
|
||||
t.Fatal("the snapshot survived its delete by target")
|
||||
}
|
||||
}
|
||||
|
||||
// A v1.0 volume's snapshots are stamped by the first write of a v1.1
|
||||
// holder (its first cut, naming no snapshot), and each can then be deleted
|
||||
// by its target.
|
||||
func TestV11FirstCutStampsTheLegacySnapshots(t *testing.T) {
|
||||
h := openSnapHead()
|
||||
h.Snapshots = map[string]Snapshot{"a": {Root: RootName{}}, "b": {Root: RootName{}}}
|
||||
st := &memHead{h: &h}
|
||||
after := v11Commit(t, st, "")
|
||||
for _, n := range []string{"a", "b"} {
|
||||
if g := after.Snapshots[n].Gen; g != h.Gen+1 {
|
||||
t.Fatalf("legacy snapshot %s after the first v1.1 cut: gen %d, want %d", n, g, h.Gen+1)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"a", "b"} {
|
||||
if _, err := RunDeleteSnapshotAt(context.Background(), st, n, h.Gen+1); err != nil {
|
||||
t.Fatalf("delete legacy %s by target: %v", n, err)
|
||||
}
|
||||
}
|
||||
if len(st.h.Snapshots) != 0 {
|
||||
t.Fatalf("legacy snapshots left: %v", st.h.Snapshots)
|
||||
}
|
||||
}
|
||||
|
||||
// The write check refuses a version-1 HEAD with an unstamped snapshot,
|
||||
// while a read of one (written before stamping) still decodes, and the next
|
||||
// write through runTransition stamps it instead of failing.
|
||||
func TestVersion1UnstampedSnapshotIsRefusedOnWriteOnly(t *testing.T) {
|
||||
h := idleHead()
|
||||
h.State = StateLive
|
||||
h.Version = HeadVersion1
|
||||
h.Snapshots = map[string]Snapshot{"old": {Root: RootName{}}}
|
||||
if err := h.checkWrite(); !errors.Is(err, ErrMalformed) {
|
||||
t.Fatalf("write check on a version-1 HEAD with gen 0: %v, want ErrMalformed", err)
|
||||
}
|
||||
raw, err := h.Encode()
|
||||
if err != nil {
|
||||
t.Fatalf("encode (the read path's check): %v", err)
|
||||
}
|
||||
decoded, err := DecodeHead(raw, h.Gen, h.VolumeID)
|
||||
if err != nil || decoded.Snapshots["old"].Gen != 0 {
|
||||
t.Fatalf("decode of a version-1 HEAD written before stamping: %v", err)
|
||||
}
|
||||
again, err := decoded.Encode()
|
||||
if err != nil || !bytes.Equal(again, raw) {
|
||||
t.Fatalf("re-encode changed or refused: %v", err)
|
||||
}
|
||||
st := &memHead{h: &decoded}
|
||||
next, err := runTransition(context.Background(), st, CauseSnapshotRetire, func(h Head) (Head, bool, error) {
|
||||
n := h.clone()
|
||||
n.Position++ // any change
|
||||
return n, true, nil
|
||||
})
|
||||
if err != nil || next.Snapshots["old"].Gen != h.Gen+1 || st.h.Snapshots["old"].Gen != h.Gen+1 {
|
||||
t.Fatalf("the next write: %v; gen %d stored %d, want %d", err, next.Snapshots["old"].Gen, st.h.Snapshots["old"].Gen, h.Gen+1)
|
||||
}
|
||||
// A version-0 HEAD keeps gen 0: stamping is a v1.1 field.
|
||||
legacy := idleHead()
|
||||
legacy.Snapshots = map[string]Snapshot{"old": {Root: RootName{}}}
|
||||
if out, err := legacy.stampedForWrite(legacy.Gen); err != nil || out.Snapshots["old"].Gen != 0 || legacy.checkWrite() != nil {
|
||||
t.Fatalf("version 0 stamped or refused: %+v %v", out.Snapshots["old"], err)
|
||||
}
|
||||
exhausted := h.clone()
|
||||
exhausted.Gen = ^uint64(0)
|
||||
if _, err := exhausted.stampedForWrite(exhausted.Gen); err != ErrHeadGenerationExhausted {
|
||||
t.Fatalf("exhaustion: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -32,6 +34,268 @@ func (b *noFlushBackend) Write(ctx context.Context, offset int64, data []byte) (
|
||||
return n, err
|
||||
}
|
||||
|
||||
// boundedRead runs get and waits for it no later than deadline: ok is false
|
||||
// when the read is still blocked then (it may be waiting for a store lock that
|
||||
// a stalled checkpoint publication holds); the read then finishes on its own.
|
||||
func boundedRead(get func() uint64, deadline time.Time) (uint64, bool) {
|
||||
got := make(chan uint64, 1)
|
||||
go func() { got <- get() }()
|
||||
t := time.NewTimer(time.Until(deadline))
|
||||
defer t.Stop()
|
||||
select {
|
||||
case v := <-got:
|
||||
return v, true
|
||||
case <-t.C:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
type passiveResult struct {
|
||||
cp uint64 // the last checkpoint read
|
||||
lastInCycle time.Time // the last moment a flusher cycle was in progress
|
||||
blocked bool // a checkpoint read was still blocked at the deadline
|
||||
}
|
||||
|
||||
// passiveCheckpointWait waits, with getters only, for the checkpoint to pass
|
||||
// cpAtBusy. The window counts from the last moment a flusher cycle was in
|
||||
// progress: a cycle slower than the window (a slow disk on a loaded host) is
|
||||
// waited for, up to deadline; a completed cycle that did not advance the
|
||||
// checkpoint does not extend it, so a flusher that cycles without reclaiming
|
||||
// still fails within the window. Every read is bounded by deadline, so a
|
||||
// read blocked behind a stalled store lock ends the wait there too.
|
||||
func passiveCheckpointWait(getCP func() uint64, flushing func() bool, cpAtBusy, target uint64, deadline time.Time, window time.Duration) passiveResult {
|
||||
r := passiveResult{cp: cpAtBusy, lastInCycle: time.Now()}
|
||||
for cpAtBusy < target && r.cp <= cpAtBusy && time.Since(r.lastInCycle) < window && time.Now().Before(deadline) {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
if !time.Now().Before(deadline) {
|
||||
break // the deadline passed while sleeping: no read is started past it
|
||||
}
|
||||
v, ok := boundedRead(getCP, deadline)
|
||||
if !ok {
|
||||
r.blocked = true
|
||||
return r
|
||||
}
|
||||
r.cp = v
|
||||
if flushing() {
|
||||
r.lastInCycle = time.Now()
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// storeView is what the no-Flush check observes, with getters only.
|
||||
// checkpoint and next take the store lock (CheckpointLSN, NextLSN); flushing
|
||||
// reads atomic flusher counters.
|
||||
type storeView struct {
|
||||
checkpoint, next func() uint64
|
||||
flushing func() bool
|
||||
}
|
||||
|
||||
// storeSnap is one bounded observation. When ok is false a read was still
|
||||
// blocked at its deadline and cp and next are unavailable, never re-read.
|
||||
type storeSnap struct {
|
||||
cp, next uint64
|
||||
ok bool
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (s storeSnap) String() string {
|
||||
if !s.ok {
|
||||
return fmt.Sprintf("cp=unavailable next=unavailable (a store read blocked, %v ago)", time.Since(s.at).Round(time.Millisecond))
|
||||
}
|
||||
return fmt.Sprintf("cp=%d next=%d", s.cp, s.next)
|
||||
}
|
||||
|
||||
// snapshot reads the checkpoint and the next LSN, each bounded by deadline.
|
||||
func (v storeView) snapshot(deadline time.Time) storeSnap {
|
||||
cp, ok := boundedRead(v.checkpoint, deadline)
|
||||
if !ok {
|
||||
return storeSnap{at: time.Now()}
|
||||
}
|
||||
next, ok := boundedRead(v.next, deadline)
|
||||
if !ok {
|
||||
return storeSnap{at: time.Now()}
|
||||
}
|
||||
return storeSnap{cp: cp, next: next, ok: true, at: time.Now()}
|
||||
}
|
||||
|
||||
// busyCheck is the outcome of the first busy write's passive check.
|
||||
type busyCheck struct {
|
||||
atBusy storeSnap // the checkpoint at the busy write, and the next LSN for the target
|
||||
wait passiveResult
|
||||
waited time.Duration
|
||||
failed string // empty when the check passed
|
||||
}
|
||||
|
||||
func (c busyCheck) String() string {
|
||||
return fmt.Sprintf("wait=%v atBusy: %v cpObserved=%d, last in a cycle %v ago, read blocked=%v", c.waited, c.atBusy, c.wait.cp, time.Since(c.wait.lastInCycle), c.wait.blocked)
|
||||
}
|
||||
|
||||
// passiveBusyCheck is the first busy write's check: with getters only, the
|
||||
// checkpoint must pass its value at the busy write before the window ends.
|
||||
// Every store observation, including the target, is bounded by deadline.
|
||||
func passiveBusyCheck(v storeView, deadline time.Time, window time.Duration) busyCheck {
|
||||
start := time.Now()
|
||||
c := busyCheck{atBusy: v.snapshot(deadline)}
|
||||
c.wait.lastInCycle = start
|
||||
if !c.atBusy.ok {
|
||||
c.waited = time.Since(start)
|
||||
c.failed = "a store read at the busy write blocked past the write's retry deadline (a store lock held)"
|
||||
return c
|
||||
}
|
||||
target := c.atBusy.next - 1
|
||||
c.wait = passiveCheckpointWait(v.checkpoint, v.flushing, c.atBusy.cp, target, deadline, window)
|
||||
c.waited = time.Since(start)
|
||||
if c.atBusy.cp < target && c.wait.cp <= c.atBusy.cp {
|
||||
c.failed = "the checkpoint did not advance without another write"
|
||||
if c.wait.blocked {
|
||||
c.failed = "a checkpoint read blocked past the write's retry deadline (a store lock held)"
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// lockedStore models the store's lock-taking getters: the first free reads
|
||||
// answer at once, later ones take mu, which a test holds as a stalled
|
||||
// checkpoint publication would.
|
||||
type lockedStore struct {
|
||||
mu sync.RWMutex
|
||||
free int32
|
||||
reads atomic.Int32
|
||||
finished atomic.Int32
|
||||
cp, next atomic.Uint64
|
||||
}
|
||||
|
||||
func (s *lockedStore) get(v *atomic.Uint64) func() uint64 {
|
||||
return func() uint64 {
|
||||
defer s.finished.Add(1)
|
||||
if s.reads.Add(1) > s.free {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
}
|
||||
return v.Load()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *lockedStore) view() storeView {
|
||||
return storeView{checkpoint: s.get(&s.cp), next: s.get(&s.next), flushing: func() bool { return true }}
|
||||
}
|
||||
|
||||
// join waits, bounded, for every read started to return (call it after mu is
|
||||
// released): a read left running would outlive the test.
|
||||
func (s *lockedStore) join(t *testing.T) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for s.finished.Load() != s.reads.Load() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("store reads did not return after the lock was released: started=%d finished=%d", s.reads.Load(), s.finished.Load())
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// heldUntil holds s.mu until release (nil: never), or until the test ends,
|
||||
// and at the end joins every read it held.
|
||||
func heldUntil(t *testing.T, s *lockedStore, release <-chan struct{}) {
|
||||
s.mu.Lock()
|
||||
stop, done := make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
select {
|
||||
case <-release:
|
||||
case <-stop:
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
t.Cleanup(func() { close(stop); <-done; s.join(t) })
|
||||
}
|
||||
|
||||
// The passive wait waits for a read held behind the store lock: one released
|
||||
// before the deadline returns the advanced checkpoint, not blocked; one held
|
||||
// past it ends the wait at the deadline, not before. A flusher reported in a
|
||||
// cycle the whole time does not extend the wait past the deadline.
|
||||
func TestPassiveCheckpointWaitIsBoundedByItsDeadline(t *testing.T) {
|
||||
const bound = 300 * time.Millisecond
|
||||
const early = bound - 50*time.Millisecond // tolerant lower bound
|
||||
const late = bound + 200*time.Millisecond
|
||||
inCycle := func() bool { return true }
|
||||
|
||||
t.Run("released before the deadline", func(t *testing.T) {
|
||||
s := &lockedStore{}
|
||||
s.cp.Store(5)
|
||||
release := make(chan struct{})
|
||||
heldUntil(t, s, release)
|
||||
start := time.Now()
|
||||
time.AfterFunc(bound/3, func() { s.cp.Store(7); close(release) })
|
||||
r := passiveCheckpointWait(s.get(&s.cp), inCycle, 5, 9, start.Add(bound), 10*time.Second)
|
||||
if took := time.Since(start); r.blocked || r.cp != 7 || took < bound/3-20*time.Millisecond || took >= bound {
|
||||
t.Fatalf("a read released at %v: blocked=%v cp=%d after %v, want cp=7 not blocked before the %v deadline", bound/3, r.blocked, r.cp, took, bound)
|
||||
}
|
||||
})
|
||||
t.Run("held past the deadline", func(t *testing.T) {
|
||||
s := &lockedStore{free: 1} // the first read answers; later ones wait for the lock
|
||||
s.cp.Store(5)
|
||||
heldUntil(t, s, nil)
|
||||
start := time.Now()
|
||||
r := passiveCheckpointWait(s.get(&s.cp), inCycle, 5, 9, start.Add(bound), 10*time.Second)
|
||||
if took := time.Since(start); !r.blocked || r.cp != 5 || took < early || took > late {
|
||||
t.Fatalf("a read held behind the lock: blocked=%v cp=%d after %v, want blocked at the %v deadline", r.blocked, r.cp, took, bound)
|
||||
}
|
||||
})
|
||||
t.Run("never advances", func(t *testing.T) {
|
||||
start := time.Now()
|
||||
r := passiveCheckpointWait(func() uint64 { return 5 }, inCycle, 5, 9, start.Add(bound), 10*time.Second)
|
||||
if took := time.Since(start); r.blocked || r.cp != 5 || took < early || took > late {
|
||||
t.Fatalf("a checkpoint that never advances with a flusher always in a cycle: blocked=%v cp=%d after %v, want the %v deadline", r.blocked, r.cp, took, bound)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The busy path itself, with the store lock held across the deadline at each
|
||||
// of its observations (the checkpoint at the busy write, the target, a read in
|
||||
// the wait), fails at the deadline and formats its report without a store
|
||||
// read; released early, it passes with the advanced checkpoint.
|
||||
func TestPassiveBusyCheckWithTheStoreLockHeld(t *testing.T) {
|
||||
const bound = 300 * time.Millisecond
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
free int32
|
||||
}{{"at the busy checkpoint read", 0}, {"at the target read", 1}, {"in the wait", 2}} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &lockedStore{free: tc.free}
|
||||
s.cp.Store(5)
|
||||
s.next.Store(10)
|
||||
heldUntil(t, s, nil)
|
||||
start := time.Now()
|
||||
c := passiveBusyCheck(s.view(), start.Add(bound), 10*time.Second)
|
||||
report := c.String()
|
||||
took := time.Since(start)
|
||||
if c.failed == "" || took < bound-50*time.Millisecond || took > bound+200*time.Millisecond {
|
||||
t.Fatalf("lock held %s: failed=%q after %v (%s), want a failure at the %v deadline", tc.name, c.failed, took, report, bound)
|
||||
}
|
||||
if tc.free < 2 && (c.atBusy.ok || !bytes.Contains([]byte(report), []byte("cp=unavailable"))) {
|
||||
t.Fatalf("lock held %s: the report must say unavailable: %s", tc.name, report)
|
||||
}
|
||||
if tc.free == 2 && (!c.wait.blocked || c.atBusy.cp != 5 || c.atBusy.next != 10) {
|
||||
t.Fatalf("lock held %s: %s", tc.name, report)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("released before the deadline", func(t *testing.T) {
|
||||
s := &lockedStore{free: 2}
|
||||
s.cp.Store(5)
|
||||
s.next.Store(10)
|
||||
release := make(chan struct{})
|
||||
heldUntil(t, s, release)
|
||||
start := time.Now()
|
||||
time.AfterFunc(bound/3, func() { s.cp.Store(7); close(release) })
|
||||
c := passiveBusyCheck(s.view(), start.Add(bound), 10*time.Second)
|
||||
if c.failed != "" || c.wait.blocked || c.wait.cp != 7 || time.Since(start) >= bound {
|
||||
t.Fatalf("lock released at %v: failed=%q %s", bound/3, c.failed, c)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Public provider + actual NVMe handler, file-backed v3 with the default
|
||||
// 64 MiB WAL. No injected I/O failures, private selector, or flusher control.
|
||||
func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) {
|
||||
@@ -79,6 +343,13 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
if err := ws.SetWMode(mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Getters only: no Write, Sync, NotifyUrgent or Close may drive progress
|
||||
// before the first retry. Inside the write loop the store is observed only
|
||||
// through bounded reads, so a held store lock cannot outlast a deadline.
|
||||
view := storeView{checkpoint: ws.CheckpointLSN, next: ws.NextLSN, flushing: func() bool {
|
||||
fi := ws.FlusherInstrumentation()
|
||||
return fi.CyclesStarted > fi.CyclesSucceeded+fi.CyclesFailed
|
||||
}}
|
||||
syncsBefore := ws.WALSyncCount()
|
||||
var durations []time.Duration
|
||||
busyCount := 0
|
||||
@@ -94,7 +365,8 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
}
|
||||
}
|
||||
retryDeadline := time.Now().Add(30 * time.Second)
|
||||
cpBefore := ws.CheckpointLSN()
|
||||
snapBefore := view.snapshot(retryDeadline)
|
||||
last := snapBefore // diagnostics use the last observation, never a fresh read
|
||||
retried := false
|
||||
for {
|
||||
writeStart := time.Now()
|
||||
@@ -105,11 +377,11 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
dump := make([]byte, 2<<20)
|
||||
n := runtime.Stack(dump, true)
|
||||
t.Logf("TIMEOUT STACKS\n%s", dump[:n])
|
||||
t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v cp=%d next=%d", off, elapsed, time.Since(start), busyCount, r, ws.CheckpointLSN(), ws.NextLSN())
|
||||
t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v last observed %v", off, elapsed, time.Since(start), busyCount, r, last)
|
||||
}
|
||||
if r.AsError() == nil {
|
||||
if retried {
|
||||
t.Logf("NO FLUSH resumed bytes=%d cp=%d->%d next=%d syncs=%d busy=%d", off, cpBefore, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount(), busyCount)
|
||||
t.Logf("NO FLUSH resumed bytes=%d before: %v now: %v syncs=%d busy=%d", off, snapBefore, view.snapshot(retryDeadline), ws.WALSyncCount(), busyCount)
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -118,28 +390,21 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
}
|
||||
busyCount++
|
||||
retried = true
|
||||
t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v cp=%d next=%d syncs=%d", off, busyCount, elapsed, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount())
|
||||
last = view.snapshot(retryDeadline)
|
||||
t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v %v syncs=%d", off, busyCount, elapsed, last, ws.WALSyncCount())
|
||||
if busyCount == 1 {
|
||||
passiveStart := time.Now()
|
||||
cpAtBusy := ws.CheckpointLSN()
|
||||
target := ws.NextLSN() - 1
|
||||
cpObserved := cpAtBusy
|
||||
// Getters only: no Write, Sync, NotifyUrgent or Close may
|
||||
// drive progress before the first retry.
|
||||
for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
cpObserved = ws.CheckpointLSN()
|
||||
}
|
||||
t.Logf("NO FLUSH passive bytes=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d", off, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target)
|
||||
if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) {
|
||||
t.Fatalf("NO FLUSH passive checkpoint did not advance without another write: bytes=%d cp=%d busy=%d", off, cpObserved, busyCount)
|
||||
c := passiveBusyCheck(view, retryDeadline, 10*time.Second)
|
||||
fi := ws.FlusherInstrumentation()
|
||||
t.Logf("NO FLUSH passive bytes=%d before: %v %v flusher: cycles started=%d succeeded=%d failed=%d max=%v", off, snapBefore, c, fi.CyclesStarted, fi.CyclesSucceeded, fi.CyclesFailed, time.Duration(fi.CycleMaxDurationNanos))
|
||||
if c.failed != "" {
|
||||
t.Fatalf("NO FLUSH passive check: %s: bytes=%d busy=%d %v", c.failed, off, busyCount, c)
|
||||
}
|
||||
}
|
||||
// Retry the identical command; no caller Flush drives reclamation.
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
if (off+transfer)%(16*1024*1024) == 0 {
|
||||
t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN())
|
||||
t.Logf("NO FLUSH progress bytes=%d elapsed=%v %v", off+transfer, time.Since(start), view.snapshot(time.Now().Add(5*time.Second)))
|
||||
}
|
||||
}
|
||||
// The expected bytes come from the submitted pattern, not another reader.
|
||||
|
||||
@@ -5,11 +5,44 @@ import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
)
|
||||
|
||||
func TestAttachReadinessReadAndWriteHonourCallerCancellation(t *testing.T) {
|
||||
for _, write := range []bool{false, true} {
|
||||
name := "read"
|
||||
if write {
|
||||
name = "write"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// A nil store makes any access before attachment an immediate failure.
|
||||
b := &StorageBackend{waitAttachReady: true}
|
||||
b.opEvidence.Store("attachment pending")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
b.testBeforeReadReadyWait = cancel
|
||||
started := time.Now()
|
||||
var err error
|
||||
if write {
|
||||
_, err = b.Write(ctx, 0, make([]byte, 4096))
|
||||
} else {
|
||||
_, err = b.Read(ctx, 0, make([]byte, 4096))
|
||||
}
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancelled readiness wait returned %v", err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed != 0 {
|
||||
t.Fatalf("cancelled wait consumed the readiness allowance: %s", elapsed)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) {
|
||||
for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} {
|
||||
name := mode
|
||||
|
||||
@@ -620,6 +620,10 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
|
||||
})
|
||||
s.recordWriteHandler(time.Since(handlerStart))
|
||||
if res.AsError() != nil {
|
||||
if s.logger != nil && res.SCT == SCTGeneric && res.SC == SCNamespaceNotReady &&
|
||||
(s.target == nil || s.target.allowWriteFailureLog(time.Now())) {
|
||||
s.logger.Printf("nvme: Write failed qid=%d nsid=%d lba=%d blocks=%d sct=%#x sc=%#x elapsed=%s reason=%q", s.qid, req.capsule.NSID, req.capsule.Lba(), req.capsule.LbaLength(), res.SCT, res.SC, time.Since(arrival), res.Reason)
|
||||
}
|
||||
req.resp.Status = res.completionStatus()
|
||||
}
|
||||
s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()})
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
)
|
||||
@@ -81,6 +82,8 @@ type Target struct {
|
||||
sessions sync.WaitGroup
|
||||
logger Logger
|
||||
closed chan struct{}
|
||||
// Shared by all connections of this volume; guarded by mu.
|
||||
nextWriteFailureLog time.Time
|
||||
|
||||
// Admin controller registry — populated on admin-queue
|
||||
// Connect (§3.1 A10.5 + R3), looked up on IO-queue Connect
|
||||
@@ -92,6 +95,18 @@ type Target struct {
|
||||
stats targetStats
|
||||
}
|
||||
|
||||
// Retryable failures can arrive on many connections at once. Keep the first
|
||||
// cause immediately, then emit at most one diagnostic per second per target.
|
||||
func (t *Target) allowWriteFailureLog(now time.Time) bool {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if now.Before(t.nextWriteFailureLog) {
|
||||
return false
|
||||
}
|
||||
t.nextWriteFailureLog = now.Add(time.Second)
|
||||
return true
|
||||
}
|
||||
|
||||
// NewTarget builds a Target. Provider must be non-nil.
|
||||
func NewTarget(cfg TargetConfig) *Target {
|
||||
if cfg.Provider == nil {
|
||||
@@ -244,6 +259,9 @@ func (t *Target) handleConn(conn net.Conn) {
|
||||
go func() {
|
||||
select {
|
||||
case <-t.closed:
|
||||
// Open can still be waiting for provider readiness before a session
|
||||
// starts. Closing the socket alone cannot wake that wait.
|
||||
cancel()
|
||||
_ = conn.Close()
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package nvme_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
)
|
||||
|
||||
type cancelProviderFunc func(context.Context, string) (frontend.Backend, error)
|
||||
|
||||
func (f cancelProviderFunc) Open(ctx context.Context, volume string) (frontend.Backend, error) {
|
||||
return f(ctx, volume)
|
||||
}
|
||||
|
||||
type pendingOpenView struct{ observed chan struct{} }
|
||||
|
||||
func (v pendingOpenView) Projection() frontend.Projection {
|
||||
select {
|
||||
case v.observed <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return frontend.Projection{VolumeID: "v1"} // Never healthy during this test.
|
||||
}
|
||||
|
||||
type cancelTestListener struct {
|
||||
conns chan net.Conn
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (l *cancelTestListener) Accept() (net.Conn, error) {
|
||||
select {
|
||||
case c := <-l.conns:
|
||||
return c, nil
|
||||
case <-l.done:
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
}
|
||||
func (l *cancelTestListener) Close() error { l.once.Do(func() { close(l.done) }); return nil }
|
||||
func (l *cancelTestListener) Addr() net.Addr { return &net.TCPAddr{} }
|
||||
|
||||
type pendingOpenWitness struct {
|
||||
ctx chan context.Context
|
||||
returned chan error
|
||||
}
|
||||
|
||||
func pendingReadinessTarget(t *testing.T) (*nvme.Target, context.CancelFunc, pendingOpenWitness) {
|
||||
t.Helper()
|
||||
view := pendingOpenView{observed: make(chan struct{}, 1)}
|
||||
provider, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(),
|
||||
NumBlocks: 32, BlockSize: 4096, OpenTimeout: time.Hour,
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Only failure cleanup may release the wait independently of the target.
|
||||
abort, release := context.WithCancel(context.Background())
|
||||
|
||||
witness := pendingOpenWitness{ctx: make(chan context.Context, 1), returned: make(chan error, 1)}
|
||||
wrapped := cancelProviderFunc(func(ctx context.Context, volume string) (frontend.Backend, error) {
|
||||
witness.ctx <- ctx
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
stop := context.AfterFunc(abort, cancel)
|
||||
defer stop()
|
||||
backend, err := provider.Open(ctx, volume)
|
||||
witness.returned <- err
|
||||
return backend, err
|
||||
})
|
||||
listener := &cancelTestListener{conns: make(chan net.Conn), done: make(chan struct{})}
|
||||
target := nvme.NewTarget(nvme.TargetConfig{
|
||||
VolumeID: "v1", Provider: wrapped, Logger: log.New(io.Discard, "", 0),
|
||||
ListenerFactory: func(nvme.Transport, string) (net.Listener, error) { return listener, nil },
|
||||
})
|
||||
if _, err := target.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, server := net.Pipe()
|
||||
|
||||
listener.conns <- server
|
||||
<-view.observed // The real DurableProvider is inside its readiness wait.
|
||||
t.Cleanup(func() { release(); _ = client.Close(); _ = target.Close(); _ = provider.Close() })
|
||||
return target, release, witness
|
||||
}
|
||||
|
||||
func TestTargetCloseCancelsPendingProviderReadiness(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
target, release, witness := pendingReadinessTarget(t)
|
||||
openCtx := <-witness.ctx
|
||||
closed := make(chan error, 1)
|
||||
go func() { closed <- target.Close() }()
|
||||
synctest.Wait()
|
||||
select {
|
||||
case err := <-closed:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := openCtx.Err(); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("target-supplied Open context: %v; want cancellation", err)
|
||||
}
|
||||
select {
|
||||
case err := <-witness.returned:
|
||||
if !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Errorf("Open settled with %v; want not-ready from the cancelled wait", err)
|
||||
}
|
||||
default:
|
||||
t.Error("target Close returned before Open settled")
|
||||
}
|
||||
default:
|
||||
t.Error("target Close waits for provider readiness instead of cancelling it")
|
||||
release()
|
||||
<-closed // Join even when the cancellation assertion fails.
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// This child owns the same real Target and DurableProvider as the holder. Its
|
||||
// stdin EOF is the stop event; no readiness publication or provider close may
|
||||
// help the target finish. This is a component process, not a blockvolume replay.
|
||||
func TestNVMeReadinessCancelProcess(t *testing.T) {
|
||||
if os.Getenv("SWBLOCK_NVME_CANCEL_HELPER") == "1" {
|
||||
target, _, _ := pendingReadinessTarget(t)
|
||||
fmt.Println("provider-readiness-wait")
|
||||
if _, err := io.Copy(io.Discard, os.Stdin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := target.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, kill := context.WithCancel(context.Background())
|
||||
defer kill()
|
||||
cmd := exec.CommandContext(ctx, executable, "-test.run=^TestNVMeReadinessCancelProcess$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_NVME_CANCEL_HELPER=1")
|
||||
input, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
var waitErr error
|
||||
go func() { waitErr = cmd.Wait(); close(done) }()
|
||||
t.Cleanup(func() {
|
||||
kill()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("child did not join after kill")
|
||||
}
|
||||
})
|
||||
observed := make(chan bool, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(output)
|
||||
for scanner.Scan() {
|
||||
if scanner.Text() == "provider-readiness-wait" {
|
||||
observed <- true
|
||||
return
|
||||
}
|
||||
}
|
||||
observed <- false
|
||||
}()
|
||||
select {
|
||||
case ok := <-observed:
|
||||
if !ok {
|
||||
t.Fatal("child did not enter provider readiness")
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("child readiness witness timed out")
|
||||
}
|
||||
if err := input.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
if waitErr != nil {
|
||||
t.Fatalf("cancelled component exit: %v\n%s", waitErr, stderr.String())
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("cancelled component exceeded the 5s stop budget")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package nvme
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
func TestSessionRetryableWriteLogsReason(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
expired bool
|
||||
}{
|
||||
{"busy", frontend.ErrBackendBusy, false},
|
||||
{"not-ready", frontend.ErrNotReady, false},
|
||||
{"deadline", context.DeadlineExceeded, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: &Target{}, logger: log.New(&logs, "", 0), qid: 7, respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1, D10: 23}}
|
||||
if tc.expired {
|
||||
req.receivedAt = time.Now().Add(-5 * time.Second)
|
||||
}
|
||||
s.handleWrite(context.Background(), req)
|
||||
if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) {
|
||||
t.Fatalf("completion=%#x", got)
|
||||
}
|
||||
for _, want := range []string{"nvme: Write failed", "qid=7", "nsid=1", "lba=23", "sc=0x82", "backend temporarily unavailable on write", tc.err.Error()} {
|
||||
if !strings.Contains(logs.String(), want) {
|
||||
t.Fatalf("missing %q in log %q", want, logs.String())
|
||||
}
|
||||
}
|
||||
if strings.Count(logs.String(), "\n") != 1 {
|
||||
t.Fatalf("want one failure line: %q", logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionRetryableWriteLogBoundAcrossConnections(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
logger := log.New(&logs, "", 0)
|
||||
target := &Target{}
|
||||
write := func(target *Target, cause error) {
|
||||
backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: cause}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: target, logger: logger, respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1}}
|
||||
s.handleWrite(context.Background(), req)
|
||||
<-s.respCh
|
||||
}
|
||||
// Neither a successful write nor an unrelated error consumes the first
|
||||
// transient diagnostic or creates a new log stream.
|
||||
write(target, nil)
|
||||
write(target, errors.New("permanent failure"))
|
||||
if logs.Len() != 0 {
|
||||
t.Fatalf("unrelated writes logged: %q", logs.String())
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); write(target, frontend.ErrBackendBusy) }()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 1 {
|
||||
t.Fatalf("burst across connections logged %d lines, want 1", got)
|
||||
}
|
||||
// A different volume must retain its first diagnostic.
|
||||
write(&Target{}, frontend.ErrNotReady)
|
||||
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 2 {
|
||||
t.Fatalf("second target did not log independently: %d lines", got)
|
||||
}
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
write(target, frontend.ErrBackendBusy)
|
||||
if got := strings.Count(logs.String(), "nvme: Write failed"); got != 3 {
|
||||
t.Fatalf("diagnostics did not resume after the rate window: %d lines", got)
|
||||
}
|
||||
}
|
||||
@@ -61,13 +61,16 @@ type ChunkCutResponse struct {
|
||||
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
|
||||
// step); every duration is in nanoseconds.
|
||||
type ChunkCutStatsBody struct {
|
||||
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
|
||||
CandidateNs int64 `json:"candidateNs"`
|
||||
WindowSetupNs int64 `json:"windowSetupNs"`
|
||||
PublishPrepareNs int64 `json:"publishPrepareNs"`
|
||||
ManifestNs int64 `json:"manifestNs"`
|
||||
CommitStateNs int64 `json:"commitStateNs"`
|
||||
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
|
||||
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
|
||||
CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched
|
||||
PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause
|
||||
PauseCandidateOps int64 `json:"pauseCandidateOps"` // per-candidate operations done while the guest was paused
|
||||
CandidateNs int64 `json:"candidateNs"`
|
||||
WindowSetupNs int64 `json:"windowSetupNs"`
|
||||
PublishPrepareNs int64 `json:"publishPrepareNs"`
|
||||
ManifestNs int64 `json:"manifestNs"`
|
||||
CommitStateNs int64 `json:"commitStateNs"`
|
||||
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
|
||||
|
||||
PayloadNs int64 `json:"payloadNs"`
|
||||
COWWALReadAttempts uint64 `json:"cowWALReadAttempts"`
|
||||
@@ -111,13 +114,16 @@ type ChunkCutStatsBody struct {
|
||||
|
||||
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
|
||||
return ChunkCutStatsBody{
|
||||
SyncPhases: s.SyncPhases,
|
||||
CandidateNs: s.CandidateNs,
|
||||
WindowSetupNs: s.WindowSetupNs,
|
||||
PublishPrepareNs: s.PublishPrepareNs,
|
||||
ManifestNs: s.ManifestNs,
|
||||
CommitStateNs: s.CommitStateNs,
|
||||
NonPayloadCopyNs: s.NonPayloadCopyNs,
|
||||
SyncPhases: s.SyncPhases,
|
||||
CandidateVisits: s.CandidateVisits,
|
||||
PreSyncNs: s.PreSyncNs,
|
||||
PauseCandidateOps: s.PauseCandidateOps,
|
||||
CandidateNs: s.CandidateNs,
|
||||
WindowSetupNs: s.WindowSetupNs,
|
||||
PublishPrepareNs: s.PublishPrepareNs,
|
||||
ManifestNs: s.ManifestNs,
|
||||
CommitStateNs: s.CommitStateNs,
|
||||
NonPayloadCopyNs: s.NonPayloadCopyNs,
|
||||
|
||||
PayloadNs: s.PayloadNs,
|
||||
COWWALReadAttempts: s.COWWALReadAttempts,
|
||||
|
||||
@@ -656,6 +656,9 @@ func (s *WALStore) markMapUnknownV3(lba uint64) {
|
||||
}
|
||||
e.LSN = max(e.LSN, birth)
|
||||
v.mapEntries.set(index, e)
|
||||
if h := s.chunk.Load(); h != nil {
|
||||
h.sink.OnMapEntryChange(uint64(index))
|
||||
}
|
||||
}
|
||||
|
||||
// InstalledBaseLSN reports a completed local BASE obligation, not a normal
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The guest pause does O(1) work: a cut's first barrier after writes to many
|
||||
// chunks does no per-candidate operation between the barrier's lock and its
|
||||
// release (counted, not timed), at 32 blocks and at the 1 TiB shape with
|
||||
// 256 changed chunks. The candidates are judged, versioned and based after
|
||||
// the pause, under the copy window.
|
||||
func TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause(t *testing.T) {
|
||||
t.Run("small", func(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
|
||||
w := newWriteLog()
|
||||
for lba := uint32(0); lba < ctNumBlocks; lba++ {
|
||||
w.write(t, s, lba, byte(lba+1))
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.CandidateChunks == 0 || r.Stats.PauseCandidateOps != 0 {
|
||||
t.Fatalf("first cut over %d candidates: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, r.Stats.PauseCandidateOps)
|
||||
}
|
||||
})
|
||||
t.Run("one-TiB-shape", func(t *testing.T) {
|
||||
const n, changed = 262144, 256
|
||||
s, l := freshShape(t, n)
|
||||
for i := 0; i < changed; i++ {
|
||||
if _, err := s.Write(uint32(i*997%n), []byte(fmt.Sprintf("%-512d", i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.CandidateChunks < changed || r.Stats.PauseCandidateOps != 0 {
|
||||
t.Fatalf("first cut over %d candidates of %d chunks: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, n, r.Stats.PauseCandidateOps)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A layer's first cut finds its touched sets ready: the barrier only swaps
|
||||
// them; no set is allocated in the pause (size-dependent work).
|
||||
func TestAColdFirstCutAllocatesNoSetInThePause(t *testing.T) {
|
||||
const n = 262144
|
||||
s, l := freshShape(t, n)
|
||||
if _, err := s.Write(3, []byte(fmt.Sprintf("%-512s", "cold"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.PauseCandidateOps != 0 {
|
||||
t.Fatalf("a layer's first cut over %d chunks did %d size-dependent operations in the pause, want 0", n, r.Stats.PauseCandidateOps)
|
||||
}
|
||||
}
|
||||
|
||||
// A recovery that lands between a cut's pre-barrier work and its barrier
|
||||
// moves every clean fill's version: the cut still judges those fills (their
|
||||
// proofs are gone), after the pause, and the pause does no per-fill work.
|
||||
func TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause(t *testing.T) {
|
||||
_, l, _ := filledFreshVolume(t)
|
||||
l.stMu.Lock()
|
||||
fills := len(l.filledClean)
|
||||
l.stMu.Unlock()
|
||||
if fills == 0 {
|
||||
t.Fatal("setup: no clean fills")
|
||||
}
|
||||
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() }
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
l.testBeforeBarrierLockHook = nil
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.PauseCandidateOps != 0 {
|
||||
t.Fatalf("a recovery just before the barrier cost %d per-fill operations in the pause, want 0", r.Stats.PauseCandidateOps)
|
||||
}
|
||||
if r.Stats.CandidateChunks < fills {
|
||||
t.Fatalf("the cut after the recovery judged %d candidates, want all %d clean fills (their proofs are gone)", r.Stats.CandidateChunks, fills)
|
||||
}
|
||||
}
|
||||
|
||||
// A reader of the candidates (status, pre-copy, the shadow) running beside
|
||||
// cuts and recoveries never charges its work to a cut's pause nor touches the
|
||||
// capture's pause accounting: run with -race, the schedule (a reader that
|
||||
// can consume a recovery's request while a cut enters its barrier) has no
|
||||
// race, and every cut's pause does no per-candidate work.
|
||||
func TestAReaderBesideCutsAndRecoveriesIsNotChargedToThePause(t *testing.T) {
|
||||
_, l, _ := filledFreshVolume(t)
|
||||
stop := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
_ = l.captureCandidates() // the readers' path: peekTouched, resolveTouchFilled
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stop)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Error("the reader did not stop")
|
||||
}
|
||||
}()
|
||||
for i := 0; i < 20; i++ {
|
||||
l.noteAllMutated() // a recovery the reader may consume first
|
||||
if i%2 == 1 {
|
||||
l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } // or one just before the barrier
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
l.testBeforeBarrierLockHook = nil
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Stats.PauseCandidateOps != 0 {
|
||||
t.Fatalf("cut %d: %d per-candidate operations charged to the pause beside a reader", i, r.Stats.PauseCandidateOps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A fill whose fetch outlives a same-open recovery installs HEAD's bytes but
|
||||
// no clean mark (the recovery moved the chunk's version), so the chunk is a
|
||||
// candidate again, as the full scan says; the absent-to-present install
|
||||
// touches it. (The package's candidate oracle checks the cut's barrier too.)
|
||||
func TestAFillThatOutlivesARecoveryMakesItsChunkACandidate(t *testing.T) {
|
||||
s, l, remote, _ := hydrationFixture(t, 2, 64)
|
||||
// The engine's predicate is what is checked here. The chunk record names
|
||||
// such a chunk HashPublished (the fill verified HEAD's hash), so the
|
||||
// engine's conservative candidate is an extra to the record's shadow, as
|
||||
// it was with the full scan: the shadow is off for this schedule.
|
||||
l.shadow = nil
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
read := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := s.Read(0)
|
||||
read <- err
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("the read miss never reached the remote")
|
||||
}
|
||||
if l.captureCandidates()[0] {
|
||||
t.Fatal("setup: the absent chunk is already a candidate")
|
||||
}
|
||||
l.noteAllMutated() // a same-open recovery, while the fetch is held
|
||||
release()
|
||||
select {
|
||||
case err := <-read:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("the read did not complete")
|
||||
}
|
||||
l.stMu.Lock()
|
||||
absent, marked := l.absent[0], l.filledClean[0] != (filledMark{})
|
||||
l.stMu.Unlock()
|
||||
if absent || marked {
|
||||
t.Fatalf("setup: after the fill, absent=%v clean-marked=%v; want present without a mark", absent, marked)
|
||||
}
|
||||
if !l.captureCandidates()[0] {
|
||||
t.Fatal("a chunk filled across a recovery, present without a clean mark, is not a candidate")
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// freshShape attaches a lazy fresh-from-HEAD layer over n one-block chunks
|
||||
// (512-byte blocks), every chunk named by HEAD and absent locally, as the
|
||||
// SPACE test builds the 1 TiB shape (n = 262,144).
|
||||
func freshShape(t *testing.T, n int) (*WALStore, *chunkLayerImpl) {
|
||||
t.Helper()
|
||||
const bs = 512
|
||||
f := newFakeChunkRemote()
|
||||
head := chunkHead{Epoch: 1, Holder: "seed", RemoteLSN: 10, Chunks: make(map[uint64]chunkRef, n)}
|
||||
for i := 0; i < n; i++ {
|
||||
data := make([]byte, bs)
|
||||
binary.LittleEndian.PutUint64(data, uint64(i)+1)
|
||||
key := fmt.Sprintf("seed/%d", i)
|
||||
f.objs[key] = data
|
||||
f.everStored[key] = true
|
||||
head.Chunks[uint64(i)] = chunkRef{Key: key, SHA256: sha256.Sum256(data), Encoding: "full"}
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.installLocked(head)
|
||||
f.mu.Unlock()
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), uint32(n), bs, WALStoreOptions{ChunkBlocks: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { closeBounded(t, s) })
|
||||
if err := s.SeedChunkFrontier(10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "host-a", Bitmap: newFakeBitmap(), ReadMissTimeout: ctLocalBound, FreshFromHead: true}
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
// Publishing a write to an absent chunk of a fresh-from-HEAD layer makes
|
||||
// the chunk record refuse its Commit (U/Commit), with or without the
|
||||
// candidate set; that record question is apart from what these tests
|
||||
// count, so the shadow is off for this shape.
|
||||
l.shadow = nil
|
||||
return s, l
|
||||
}
|
||||
|
||||
// visitBound is the candidate step's allowance for a cut with changed chunks
|
||||
// at n chunks: the changed chunks plus one summary word per 4,096 chunks,
|
||||
// and a small constant.
|
||||
func visitBound(changed, n int) int64 { return int64(changed + n/4096 + 16) }
|
||||
|
||||
// An idle cut's candidate step does work flat in S: at the 1 TiB shape it
|
||||
// visits no more chunk indices than at 4,096 chunks (counted, not timed).
|
||||
func TestIdleCutCandidateWorkIsFlatInS(t *testing.T) {
|
||||
for _, n := range []int{4096, 262144} {
|
||||
t.Run(fmt.Sprintf("chunks-%d", n), func(t *testing.T) {
|
||||
s, l := freshShape(t, n)
|
||||
if _, err := s.Write(0, make([]byte, 512)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, max := r.Stats.CandidateVisits, visitBound(0, n); got > max {
|
||||
t.Fatalf("an idle cut over %d chunks visited %d chunk indices in its candidate step, want <= %d", n, got, max)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A cut with one changed chunk at the 1 TiB shape scans no chunk map: its
|
||||
// candidate step visits the changed chunk and the summary words only.
|
||||
func TestOneChangedChunkCutVisitsNoFullScan(t *testing.T) {
|
||||
const n = 262144
|
||||
s, l := freshShape(t, n)
|
||||
if _, err := s.Write(0, make([]byte, 512)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(7*1, []byte(fmt.Sprintf("%-512s", "changed"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, max := r.Stats.CandidateVisits, visitBound(1, n); got > max {
|
||||
t.Fatalf("a one-chunk cut over %d chunks visited %d chunk indices, want <= %d", n, got, max)
|
||||
}
|
||||
}
|
||||
|
||||
// The cut syncs the store before its barrier, outside the guest pause, so
|
||||
// the pause's own sync has only what came after; the pre-sync's time is
|
||||
// reported apart from the pause.
|
||||
func TestCutSyncsBeforeItsBarrier(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
|
||||
w := newWriteLog()
|
||||
for lba := uint32(0); lba < ctNumBlocks; lba++ {
|
||||
w.write(t, s, lba, byte(lba+1))
|
||||
}
|
||||
before := s.syncs.Load()
|
||||
var atLock uint64
|
||||
l.testBeforeBarrierLockHook = func() { atLock = s.syncs.Load() }
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after := s.syncs.Load(); after <= atLock {
|
||||
t.Fatalf("the counter missed the pause's own sync (%d then %d): the measure is wrong", atLock, after)
|
||||
}
|
||||
if atLock <= before {
|
||||
t.Fatalf("no store sync between the cut's start and its barrier (sync count %d then %d): the pause syncs the whole fill", before, atLock)
|
||||
}
|
||||
}
|
||||
|
||||
// A cut whose commit outcome is unknown (and did not land) loses no chunk:
|
||||
// its captured chunks, and a write made after it, are all published by the
|
||||
// next cut, and no other chunk changes.
|
||||
func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl)
|
||||
w := newWriteLog()
|
||||
for lba := uint32(0); lba < ctNumBlocks; lba++ {
|
||||
w.write(t, s, lba, byte(lba+1))
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := f.imageOf(t, f.stats().head) // the remote's full image, any format
|
||||
w.write(t, s, 0*ctChunkBlocks, 0xa0) // chunk 0
|
||||
w.write(t, s, 2*ctChunkBlocks, 0xa2) // chunk 2
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casUnknownNotApplied}
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
|
||||
t.Fatalf("the injected cut answered %v, want its outcome unknown", err)
|
||||
}
|
||||
w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
|
||||
var err error
|
||||
var last chunkCutResult
|
||||
for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish
|
||||
if last, err = l.Cut(ctTimeout(t)); err == nil && !last.Noop {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img := f.imageOf(t, f.stats().head)
|
||||
chunkBytes := ctChunkBlocks * ctBlockSize
|
||||
for idx := 0; idx < ctNumBlocks/ctChunkBlocks; idx++ {
|
||||
at := idx * chunkBytes
|
||||
changed := !bytes.Equal(img[at:at+chunkBytes], base[at:at+chunkBytes])
|
||||
want := idx == 0 || idx == 2 || idx == 5
|
||||
if changed != want {
|
||||
t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The candidate set's OR keeps the summary, so a set ORed back is listed in
|
||||
// full; each lists exactly the set bits.
|
||||
func TestCandidateSetOrBackKeepsTheSummary(t *testing.T) {
|
||||
const n = 64 * 64 * 3
|
||||
taken, live := newCandidateSet(n), newCandidateSet(n)
|
||||
want := []uint64{1, 64*64 + 5, n - 1}
|
||||
for _, c := range want {
|
||||
taken.set(c)
|
||||
}
|
||||
live.set(7)
|
||||
live.or(taken)
|
||||
var got []uint64
|
||||
live.each(func(c uint64) { got = append(got, c) })
|
||||
exp := []uint64{1, 7, 64*64 + 5, n - 1}
|
||||
if fmt.Sprint(got) != fmt.Sprint(exp) || live.Len() != len(exp) {
|
||||
t.Fatalf("after OR-back the set lists %v (len %d), want %v", got, live.Len(), exp)
|
||||
}
|
||||
live.clear()
|
||||
got = nil
|
||||
live.each(func(c uint64) { got = append(got, c) })
|
||||
if len(got) != 0 || live.Len() != 0 {
|
||||
t.Fatalf("a cleared set lists %v", got)
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,10 @@ type cutCOWEntry struct {
|
||||
// were captured: their image at H is HEAD's, filled by the copier from the
|
||||
// cut's base HEAD after it released the entry (never under a guest write).
|
||||
missing []uint64
|
||||
// version is the chunk's mutation version when a guest write's save
|
||||
// claimed the entry: the version of the bytes it saves (the write's own
|
||||
// version move comes after its mutation).
|
||||
version uint64
|
||||
}
|
||||
type cutCOWWindow struct {
|
||||
layer *chunkLayerImpl
|
||||
@@ -137,6 +141,19 @@ type cutCOWWindow struct {
|
||||
saveNs atomic.Int64
|
||||
waitNs atomic.Int64
|
||||
// Scheduling/fault controls are nil in production and set before installation.
|
||||
|
||||
// entries (above) are made on a chunk's first touch (a guest write's
|
||||
// save, or the copier), never at the barrier: the window covers cand, the
|
||||
// cut's candidate set (immutable once installed), and staged marks the
|
||||
// ones a pre-copy already holds. nextSlot hands out side-file slots in
|
||||
// touch order. The barrier's work is O(1), not one entry per candidate.
|
||||
cand map[uint64]bool
|
||||
staged map[uint64]bool
|
||||
nextSlot int64
|
||||
// covers is the window's reach from the barrier until narrow sets cand:
|
||||
// the sets the barrier took (O(1) a lookup), a superset of the
|
||||
// candidates, judged after the pause.
|
||||
covers func(uint64) bool
|
||||
}
|
||||
|
||||
func (s *WALStore) beforeChunkMutation(first, count uint64) {
|
||||
@@ -200,12 +217,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() {
|
||||
}
|
||||
|
||||
// The caller owns captureMu exclusive, so no writer can miss this publication.
|
||||
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) {
|
||||
func (l *chunkLayerImpl) installCOWWindow(covers func(uint64) bool, spill cowSpillCap) (*cutCOWWindow, error) {
|
||||
size := uint64(l.blockSize) * l.chunkBlocks
|
||||
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
|
||||
if size == 0 || size > math.MaxInt64 || l.numChunks > math.MaxInt64/size {
|
||||
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
|
||||
}
|
||||
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
|
||||
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), covers: covers, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)}
|
||||
w.ctx, w.cancel = context.WithCancel(context.Background())
|
||||
_, reserved, limit := l.cutPayloadWorkers()
|
||||
savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size))))
|
||||
@@ -214,15 +231,6 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he
|
||||
reserved += int64(2*savers) * int64(size)
|
||||
w.memory, w.memoryLimit = reserved, limit
|
||||
w.saverSlots = make(chan struct{}, savers)
|
||||
var slot int64
|
||||
for _, idx := range sortedKeys(candidates) {
|
||||
state := cowPending
|
||||
if staged[idx] {
|
||||
state = cowDone
|
||||
}
|
||||
w.entries[idx] = &cutCOWEntry{state: state, ready: make(chan struct{}), slot: slot}
|
||||
slot++
|
||||
}
|
||||
l.cowMu.Lock()
|
||||
defer l.cowMu.Unlock()
|
||||
if l.cowClosed || l.cowTransitions != 0 {
|
||||
@@ -266,7 +274,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
|
||||
if w.terminal {
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
e := w.entries[idx]
|
||||
e := w.entryLocked(idx)
|
||||
if e == nil {
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
@@ -277,6 +285,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
|
||||
case cowPending:
|
||||
if saving {
|
||||
e.state = cowSaving
|
||||
e.version = w.layer.chunkVersion(idx) // before the write's own move
|
||||
} else {
|
||||
e.state = cowCopying
|
||||
}
|
||||
@@ -302,6 +311,57 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch
|
||||
return nil, cowDone, nil
|
||||
}
|
||||
}
|
||||
|
||||
// entryLocked is idx's entry, made on its first touch: nil when the window
|
||||
// does not cover idx, done when a pre-copy holds it. Caller holds w.mu.
|
||||
func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry {
|
||||
if e := w.entries[idx]; e != nil {
|
||||
return e
|
||||
}
|
||||
if w.cand != nil {
|
||||
if !w.cand[idx] {
|
||||
return nil
|
||||
}
|
||||
} else if w.covers == nil || !w.covers(idx) {
|
||||
return nil
|
||||
}
|
||||
state := cowPending
|
||||
if w.staged[idx] {
|
||||
state = cowDone
|
||||
}
|
||||
e := &cutCOWEntry{state: state, ready: make(chan struct{}), slot: w.nextSlot}
|
||||
w.nextSlot++
|
||||
w.entries[idx] = e
|
||||
return e
|
||||
}
|
||||
|
||||
// versionAt is chunk idx's version at the barrier, read atomically with the
|
||||
// write path: the version a guest write's save recorded with the bytes it
|
||||
// saved, else the live version, read under w.mu so no writer can claim the
|
||||
// entry (and move the version) in between.
|
||||
func (w *cutCOWWindow) versionAt(idx uint64) uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if e := w.entries[idx]; e != nil {
|
||||
e.mu.Lock()
|
||||
state, v := e.state, e.version
|
||||
e.mu.Unlock()
|
||||
if state == cowSaving || state == cowSaved {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return w.layer.chunkVersion(idx)
|
||||
}
|
||||
|
||||
// narrow sets the window's final reach after the candidates are judged (and
|
||||
// versioned): the candidates, the staged ones a pre-copy holds, and the cut's
|
||||
// base HEAD for missing blocks. Entries already made stay as they are.
|
||||
func (w *cutCOWWindow) narrow(cand, staged map[uint64]bool, head map[uint64]chunkRef) {
|
||||
w.mu.Lock()
|
||||
w.cand, w.staged, w.head, w.covers = cand, staged, head, nil
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
@@ -613,6 +673,18 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
|
||||
// Each worker owns one immutable image from local read through remote Put.
|
||||
// Once copied, its entry is done: guest writes need not wait for remote I/O.
|
||||
// The window remains installed for candidates not yet read by a worker.
|
||||
// endCOWWindow ends a window: abort, join its savers, and unpublish it.
|
||||
func (l *chunkLayerImpl) endCOWWindow(w *cutCOWWindow) {
|
||||
w.abort(errCutCOWAborted)
|
||||
w.join()
|
||||
l.cowMu.Lock()
|
||||
if l.cow == w {
|
||||
l.cow = nil
|
||||
l.cowActive.Store(nil)
|
||||
}
|
||||
l.cowMu.Unlock()
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, error) {
|
||||
parent := ctx
|
||||
abortStop := context.AfterFunc(parent, func() { w.abort(parent.Err()) })
|
||||
@@ -621,25 +693,26 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec
|
||||
stop := context.AfterFunc(w.ctx, cancel)
|
||||
defer stop()
|
||||
defer cancel()
|
||||
defer func() {
|
||||
w.abort(errCutCOWAborted)
|
||||
w.join()
|
||||
l.cowMu.Lock()
|
||||
if l.cow == w {
|
||||
l.cow = nil
|
||||
l.cowActive.Store(nil)
|
||||
defer l.endCOWWindow(w)
|
||||
// The copier's work: every covered chunk a pre-copy does not hold and no
|
||||
// touch has finished. Outside the pause (writers are back), O(candidates).
|
||||
indices := make(map[uint64]bool, len(w.cand))
|
||||
w.mu.Lock()
|
||||
for idx := range w.cand {
|
||||
if w.staged[idx] {
|
||||
continue
|
||||
}
|
||||
l.cowMu.Unlock()
|
||||
}()
|
||||
indices := make(map[uint64]bool, len(w.entries))
|
||||
for idx, e := range w.entries {
|
||||
e.mu.Lock()
|
||||
done := e.state == cowDone
|
||||
e.mu.Unlock()
|
||||
if !done {
|
||||
indices[idx] = true
|
||||
if e := w.entries[idx]; e != nil {
|
||||
e.mu.Lock()
|
||||
done := e.state == cowDone
|
||||
e.mu.Unlock()
|
||||
if done {
|
||||
continue
|
||||
}
|
||||
}
|
||||
indices[idx] = true
|
||||
}
|
||||
w.mu.Unlock()
|
||||
order := hotChunkKeys(indices, recent)
|
||||
out, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) {
|
||||
c, ok, err := l.copyCOWEntry(w, idx)
|
||||
|
||||
@@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) {
|
||||
for i := 0; i < candidates; i++ {
|
||||
pending[uint64(i)] = true
|
||||
}
|
||||
w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit())
|
||||
w, err := l.installCOWWindow(func(i uint64) bool { return pending[i] }, l.cowSpillLimit())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -188,6 +188,29 @@ type chunkLayerImpl struct {
|
||||
// own names the chunks OwnBatch re-uploads under this layer's own keys in
|
||||
// the cut it runs (set and cleared under capMu, read under stMu).
|
||||
own map[uint64]bool
|
||||
// paused is set from a capture's barrier lock to its release, and
|
||||
// pauseOps counts per-candidate operations done meanwhile (pauseOp);
|
||||
// both are touched only by the capturing goroutine.
|
||||
paused bool
|
||||
pauseOps int64
|
||||
|
||||
// touched holds the chunks whose candidacy may have changed since a
|
||||
// capture last took them: a map entry change (OnMapEntryChange), a HEAD
|
||||
// ref change of a clean fill, and, once per layer, every entry UNKNOWN
|
||||
// or above remoteLSN (seedTouched). The candidate step judges only these
|
||||
// members against the same predicate the map scan used, so it never
|
||||
// walks the map; the barrier takes the set whole. unkMu is a leaf lock.
|
||||
// The set is a chunk bitmap with a per-word summary (candidateSet: 1 bit
|
||||
// a chunk, 32 KiB at 1 TiB), and touchedSpare is its cleared twin, so
|
||||
// the barrier's take is a pointer swap.
|
||||
unkMu sync.Mutex
|
||||
touched *candidateSet
|
||||
touchedSpare *candidateSet
|
||||
touchedSeed sync.Once // the once-per-layer seed (seedTouched)
|
||||
// touchFilled asks the next set user to touch every clean fill: a
|
||||
// recovery moved every chunk's version (noteAllMutated), ending their
|
||||
// knownEqual proofs, at a point that may hold the layer's locks.
|
||||
touchFilled atomic.Bool
|
||||
|
||||
cutLSN uint64 // H of the latest cut taken (in flight or installed)
|
||||
// chunkMut counts the mutations of each chunk: every dirty-map insert
|
||||
@@ -516,6 +539,7 @@ func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) {
|
||||
func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
|
||||
if !l.v11 {
|
||||
l.head, l.refs = h, nil
|
||||
l.touchRefChangedLocked()
|
||||
return
|
||||
}
|
||||
if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks {
|
||||
@@ -524,6 +548,162 @@ func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
|
||||
l.refs.fillAll(h.Chunks)
|
||||
h.Chunks = nil
|
||||
l.head = h
|
||||
l.touchRefChangedLocked()
|
||||
}
|
||||
|
||||
// touchRefChangedLocked adds to the touched set every clean fill whose HEAD
|
||||
// ref no longer matches its mark (a whole HEAD install): its knownEqual
|
||||
// proof is gone, so the next candidate step must judge it. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) touchRefChangedLocked() {
|
||||
var gone []uint64
|
||||
for idx, m := range l.filledClean {
|
||||
if l.headChunk(idx) != m.ref {
|
||||
gone = append(gone, idx)
|
||||
}
|
||||
}
|
||||
l.touch(gone...)
|
||||
}
|
||||
|
||||
// resolveTouchFilled touches every clean fill if a recovery asked for it.
|
||||
// The caller holds neither stMu nor WALStore.mu. byCapture is true only on
|
||||
// the capturing goroutine: the pause accounting (paused, pauseOps) is its
|
||||
// own, so a reader's work (status, pre-copy, the shadow) is never charged to
|
||||
// a cut nor touches those fields.
|
||||
func (l *chunkLayerImpl) resolveTouchFilled(byCapture bool) {
|
||||
if !l.touchFilled.Swap(false) {
|
||||
return
|
||||
}
|
||||
l.stMu.Lock()
|
||||
filled := make([]uint64, 0, len(l.filledClean))
|
||||
for idx := range l.filledClean {
|
||||
filled = append(filled, idx)
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
if byCapture {
|
||||
l.pauseOp(len(filled))
|
||||
}
|
||||
l.touch(filled...)
|
||||
}
|
||||
|
||||
// newTouchedSet allocates a touched set (its words and summary: size
|
||||
// dependent, counted as pause work when the capturing goroutine allocates it
|
||||
// while the guest is paused).
|
||||
func (l *chunkLayerImpl) newTouchedSet(byCapture bool) *candidateSet {
|
||||
if byCapture {
|
||||
l.pauseOp(int(l.numChunks/64) + 1)
|
||||
}
|
||||
return newCandidateSet(l.numChunks)
|
||||
}
|
||||
|
||||
// candidateOracle, when set (by this package's tests), receives every chunk
|
||||
// the full predicate scan finds that a barrier's touched-set candidate step
|
||||
// missed. Production leaves it nil: the scan is O(chunks).
|
||||
var candidateOracle func(string)
|
||||
|
||||
// candidateOracleScan is the oracle's half at the barrier (tests only, nil
|
||||
// in production, never counted as pause work): the full scan of the old
|
||||
// candidate step, the chunks it would make candidates now.
|
||||
func (l *chunkLayerImpl) candidateOracleScan() map[uint64]bool {
|
||||
if candidateOracle == nil {
|
||||
return nil
|
||||
}
|
||||
l.stMu.Lock()
|
||||
base := l.remoteLSN
|
||||
l.stMu.Unlock()
|
||||
want := map[uint64]bool{}
|
||||
l.s.mu.RLock()
|
||||
defer l.s.mu.RUnlock()
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
pendingFilled := l.touchFilled.Load()
|
||||
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
|
||||
i := uint64(idx)
|
||||
if l.absent[i] && !l.chunkHasLocalLocked(i) {
|
||||
continue
|
||||
}
|
||||
e := l.s.v3.mapEntries.at(idx)
|
||||
if (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
|
||||
if pendingFilled && l.filledClean[i] != (filledMark{}) {
|
||||
continue // a recovery's touches are pending: the next cut's
|
||||
}
|
||||
want[i] = true
|
||||
}
|
||||
}
|
||||
return want
|
||||
}
|
||||
|
||||
// candidateOracleCompare is the oracle's half after the judgement: a chunk
|
||||
// the barrier's full scan makes a candidate that the judged candidates miss
|
||||
// is a finding.
|
||||
func candidateOracleCompare(want, got map[uint64]bool) {
|
||||
report := candidateOracle
|
||||
if report == nil {
|
||||
return
|
||||
}
|
||||
for i := range want {
|
||||
if !got[i] {
|
||||
report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan at the barrier but not by the judged touched set", i))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requeueTaken returns a cut's taken sets when it ends before judging them
|
||||
// (a refusal in or right after the pause): the touched members are touched
|
||||
// again, the dirty set rejoins l.dirty, and a BASE write's allDirty stays.
|
||||
func (l *chunkLayerImpl) requeueTaken(taken *candidateSet, dirty map[uint64]bool, all bool) {
|
||||
var back []uint64
|
||||
taken.each(func(c uint64) { back = append(back, c) })
|
||||
l.touch(back...)
|
||||
l.returnTouched(taken)
|
||||
l.stMu.Lock()
|
||||
for idx := range dirty {
|
||||
l.dirty[idx] = true
|
||||
}
|
||||
if all {
|
||||
l.allDirty = true
|
||||
}
|
||||
l.dirtyVer++
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
|
||||
// writtenSinceTake reports whether chunk idx was touched since the barrier
|
||||
// took the set: a write after the barrier (the live set holds it).
|
||||
func (l *chunkLayerImpl) writtenSinceTake(idx uint64) bool {
|
||||
l.unkMu.Lock()
|
||||
defer l.unkMu.Unlock()
|
||||
return l.touched != nil && idx < l.numChunks && l.touched.has(idx)
|
||||
}
|
||||
|
||||
// pauseOp counts n per-candidate operations if the guest is paused.
|
||||
func (l *chunkLayerImpl) pauseOp(n int) {
|
||||
if l.paused {
|
||||
l.pauseOps += int64(n)
|
||||
}
|
||||
}
|
||||
|
||||
// touch adds chunks to the touched set (leaf lock).
|
||||
func (l *chunkLayerImpl) touch(chunks ...uint64) {
|
||||
if len(chunks) == 0 {
|
||||
return
|
||||
}
|
||||
l.unkMu.Lock()
|
||||
set := l.touchedLocked(false) // any goroutine
|
||||
for _, c := range chunks {
|
||||
if c < l.numChunks {
|
||||
set.set(c)
|
||||
}
|
||||
}
|
||||
l.unkMu.Unlock()
|
||||
}
|
||||
|
||||
// touchedLocked is the live touched set, made on first use. Caller holds
|
||||
// unkMu; byCapture as in resolveTouchFilled.
|
||||
func (l *chunkLayerImpl) touchedLocked(byCapture bool) *candidateSet {
|
||||
if l.touched == nil {
|
||||
l.touched = l.newTouchedSet(byCapture)
|
||||
}
|
||||
return l.touched
|
||||
}
|
||||
|
||||
// readAttachHead reads HEAD at attach and installs it. On the v1.1 format,
|
||||
@@ -622,6 +802,92 @@ func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool {
|
||||
|
||||
// ---- sink callbacks ----
|
||||
|
||||
// OnMapEntryChange is O(1): it only marks memory, under the leaf unkMu.
|
||||
func (l *chunkLayerImpl) OnMapEntryChange(chunk uint64) { l.touch(chunk) }
|
||||
|
||||
// seedTouched adds, once per layer, every chunk whose map entry is UNKNOWN
|
||||
// or above remoteLSN now (writes a restart left behind, which no
|
||||
// OnExtentWrite of this layer saw). It runs on the set's first use: before
|
||||
// the first capture's barrier (outside the guest pause), or at an earlier
|
||||
// reader. An entry that turns UNKNOWN later arrives through OnMapEntryChange,
|
||||
// which may already have run (the set is a union). The caller holds neither
|
||||
// stMu nor WALStore.mu.
|
||||
func (l *chunkLayerImpl) seedTouched() {
|
||||
l.stMu.Lock()
|
||||
base := l.remoteLSN
|
||||
l.stMu.Unlock()
|
||||
var seed []uint64
|
||||
l.s.mu.RLock()
|
||||
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
|
||||
if e := l.s.v3.mapEntries.at(idx); e.Unknown || e.LSN > base {
|
||||
seed = append(seed, uint64(idx))
|
||||
}
|
||||
}
|
||||
l.s.mu.RUnlock()
|
||||
// An absent chunk with no local write is HEAD's content: it is left out
|
||||
// here, outside the pause (a fresh attach makes nearly every chunk so),
|
||||
// as the candidate step would drop it.
|
||||
kept := seed[:0]
|
||||
l.stMu.Lock()
|
||||
for _, idx := range seed {
|
||||
if !l.absent[idx] || l.chunkHasLocalLocked(idx) {
|
||||
kept = append(kept, idx)
|
||||
}
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
l.touch(kept...)
|
||||
}
|
||||
|
||||
// peekTouched lists the touched set's members, for a reader.
|
||||
func (l *chunkLayerImpl) peekTouched() []uint64 {
|
||||
l.touchedSeed.Do(l.seedTouched)
|
||||
l.resolveTouchFilled(false)
|
||||
l.unkMu.Lock()
|
||||
defer l.unkMu.Unlock()
|
||||
set := l.touchedLocked(false)
|
||||
out := make([]uint64, 0, set.Len())
|
||||
set.each(func(c uint64) { out = append(out, c) })
|
||||
return out
|
||||
}
|
||||
|
||||
// takeTouched hands the touched set to a capture's barrier and puts the
|
||||
// cleared spare in its place, a pointer swap: a chunk marked after the take
|
||||
// is the next cut's. The caller gives the set back (returnTouched).
|
||||
func (l *chunkLayerImpl) takeTouched() *candidateSet {
|
||||
l.unkMu.Lock()
|
||||
defer l.unkMu.Unlock()
|
||||
taken := l.touchedLocked(true)
|
||||
if l.touchedSpare == nil {
|
||||
l.touchedSpare = l.newTouchedSet(true) // only if prepareTouched was skipped
|
||||
}
|
||||
l.touched, l.touchedSpare = l.touchedSpare, nil
|
||||
return taken
|
||||
}
|
||||
|
||||
// prepareTouched readies the touched sets before a barrier, outside the
|
||||
// pause: the once-per-layer seed, a pending recovery's clean-fill touches,
|
||||
// and the cleared spare the barrier swaps in. The barrier then only swaps.
|
||||
func (l *chunkLayerImpl) prepareTouched() {
|
||||
l.touchedSeed.Do(l.seedTouched)
|
||||
l.resolveTouchFilled(true)
|
||||
l.unkMu.Lock()
|
||||
l.touchedLocked(true)
|
||||
if l.touchedSpare == nil {
|
||||
l.touchedSpare = l.newTouchedSet(true)
|
||||
}
|
||||
l.unkMu.Unlock()
|
||||
}
|
||||
|
||||
// returnTouched clears a taken set (O(members)) and keeps it as the spare.
|
||||
func (l *chunkLayerImpl) returnTouched(set *candidateSet) {
|
||||
set.clear()
|
||||
l.unkMu.Lock()
|
||||
if l.touchedSpare == nil {
|
||||
l.touchedSpare = set
|
||||
}
|
||||
l.unkMu.Unlock()
|
||||
}
|
||||
|
||||
// OnExtentWrite is O(1): it only marks memory. It runs under extent or
|
||||
// publication locks.
|
||||
func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) {
|
||||
@@ -662,9 +928,11 @@ func (l *chunkLayerImpl) noteMutation(lba, lsn uint64) {
|
||||
cov = func() string { return localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local) }
|
||||
}
|
||||
sh.write(idx, lsn, func() { l.chunkMut[idx].Add(1) }, cov)
|
||||
l.touch(idx)
|
||||
return
|
||||
}
|
||||
l.chunkMut[idx].Add(1)
|
||||
l.touch(idx) // its version moved: a clean fill's proof ends
|
||||
}
|
||||
}
|
||||
|
||||
@@ -675,6 +943,7 @@ func (l *chunkLayerImpl) noteAllMutated() {
|
||||
for i := range l.chunkMut {
|
||||
l.chunkMut[i].Add(1)
|
||||
}
|
||||
l.touchFilled.Store(true)
|
||||
if sh := l.shadow; sh != nil {
|
||||
l.recoveredLocked(sh)
|
||||
}
|
||||
@@ -757,6 +1026,52 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) {
|
||||
// UNKNOWN never certifies clean; a max LSN beyond HEAD must be captured even
|
||||
// after the WAL entry has checkpointed and the legacy bitmap says clean.
|
||||
func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
|
||||
members := l.peekTouched()
|
||||
out, _ := l.candidatesFrom(func(f func(uint64)) {
|
||||
for _, c := range members {
|
||||
f(c)
|
||||
}
|
||||
}, math.MaxUint64)
|
||||
return out
|
||||
}
|
||||
|
||||
// The candidate predicate, per chunk i (INV-WAL-V3-CAPTURE-CANDIDATES-001):
|
||||
//
|
||||
// (entry.Unknown && !knownEqualToHead(i)) || entry.LSN > remoteLSN,
|
||||
// unless absent(i) && !chunkHasLocal(i)
|
||||
//
|
||||
// The touched set must hold every chunk whose answer can turn true between
|
||||
// two barriers. Each input that moves, and what touches the chunk:
|
||||
//
|
||||
// input mover touch
|
||||
// entry.LSN up recordMapWriteV3 (write, replay) OnMapEntryChange
|
||||
// entry.Unknown on markMapUnknownV3, recordMapWriteV3 OnMapEntryChange
|
||||
// (reused LSN); map creation, open seedTouched
|
||||
// entry.Unknown off capture's clear, known-zero clear none: true to false only
|
||||
// (persistCapturedMapV3)
|
||||
// remoteLSN up finishCut none: true to false only
|
||||
// version (proof) noteMutation touch(i)
|
||||
// noteAllMutated (Recover, BASE resume touchFilled, resolved at
|
||||
// under WALStore.mu; BASE transition the next take or peek
|
||||
// under capMu)
|
||||
// HEAD ref (proof) setHeadLocked, applyCommitLocked touchRefChangedLocked,
|
||||
// touch(changed)
|
||||
// clean mark added a fill none: true to false only
|
||||
// clean marks gone BASE install (allDirty: every chunk) none: allDirty
|
||||
// own (proof) OwnBatch addOwnCandidatesLocked
|
||||
// absent off a fill's install touch(i)
|
||||
// a local write; BASE install noteMutation; allDirty
|
||||
// absent on an evict none: true to false only
|
||||
//
|
||||
// A recovery that lands after a barrier's take is the next cut's, as a write
|
||||
// after the barrier is. Under tests, every barrier also runs the full scan as
|
||||
// an oracle (candidateOracle) and reports any chunk the set missed.
|
||||
//
|
||||
// candidatesFrom is the candidate step over a touched set (peeked by a
|
||||
// reader, taken by the barrier). Its work is O(changed): the WAL's dirty
|
||||
// entries, the own batch, and the set's members, each judged on its own; no
|
||||
// map of every chunk is walked. visits counts every chunk index it touched.
|
||||
func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64)), upTo uint64) (map[uint64]bool, int64) {
|
||||
out := map[uint64]bool{}
|
||||
var base uint64
|
||||
|
||||
@@ -764,42 +1079,40 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
|
||||
base = l.remoteLSN
|
||||
l.stMu.Unlock()
|
||||
|
||||
visits := int64(0)
|
||||
for _, e := range l.s.dm.snapshot() {
|
||||
visits++
|
||||
// Retention in the local WAL is not dirt since HEAD. Lower-LSN
|
||||
// BASE/direct changes remain conservative through UNKNOWN below.
|
||||
if e.LSN > base {
|
||||
if e.LSN > base && e.LSN <= upTo {
|
||||
out[l.chunkOf(e.LBA)] = true
|
||||
}
|
||||
}
|
||||
{
|
||||
|
||||
l.stMu.Lock()
|
||||
absent := map[uint64]bool{}
|
||||
for idx := range l.absent {
|
||||
if !l.chunkHasLocalLocked(idx) {
|
||||
absent[idx] = true
|
||||
}
|
||||
l.s.mu.RLock() // before stMu, the established order
|
||||
defer l.s.mu.RUnlock()
|
||||
l.stMu.Lock()
|
||||
visits += int64(len(l.own))
|
||||
l.addOwnCandidatesLocked(out)
|
||||
// The map is not scanned. An entry above remoteLSN is a write that is
|
||||
// either still in the WAL (the dirty map above), flushed above the last
|
||||
// cut (l.dirty, OnExtentWrite) or captured by a cut that did not land
|
||||
// (requeued into l.dirty); the first use seeds every entry above
|
||||
// remoteLSN at that time (a restart's earlier writes) with the UNKNOWN
|
||||
// ones. An absent chunk with no local write is HEAD's content and leaves
|
||||
// the set: it becomes present only by a fill (known equal to HEAD) or by
|
||||
// local writes (l.dirty). A clean fill still equal to HEAD is not
|
||||
// compared again.
|
||||
members(func(i uint64) {
|
||||
visits++
|
||||
if i >= uint64(l.s.v3.mapEntries.len()) || (l.absent[i] && !l.chunkHasLocalLocked(i)) {
|
||||
return
|
||||
}
|
||||
filled := map[uint64]bool{}
|
||||
for idx := range l.filledClean {
|
||||
if l.knownEqualToHeadLocked(idx) {
|
||||
filled[idx] = true
|
||||
}
|
||||
if e := l.s.v3.mapEntries.at(int(i)); (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base {
|
||||
out[i] = true
|
||||
}
|
||||
l.addOwnCandidatesLocked(out)
|
||||
l.stMu.Unlock()
|
||||
l.s.mu.RLock()
|
||||
for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ {
|
||||
e := l.s.v3.mapEntries.at(idx)
|
||||
i := uint64(idx)
|
||||
if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) {
|
||||
out[i] = true
|
||||
}
|
||||
}
|
||||
l.s.mu.RUnlock()
|
||||
}
|
||||
|
||||
return out
|
||||
})
|
||||
l.stMu.Unlock()
|
||||
return out, visits
|
||||
}
|
||||
|
||||
// filledMark is a clean fill: the chunk's version and the HEAD ref it was
|
||||
@@ -929,6 +1242,10 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat
|
||||
sh.fill(idx, ref.SHA256)
|
||||
}
|
||||
delete(l.absent, idx)
|
||||
// Absent to present: the predicate's exclusion ends. Without a fresh
|
||||
// clean mark (a version moved during the fetch, e.g. by a recovery) the
|
||||
// chunk may now be a candidate, so the next candidate step judges it.
|
||||
l.touch(idx)
|
||||
for i := uint64(0); i < l.chunkBlocks; i++ {
|
||||
delete(l.localBlocks, first+i)
|
||||
}
|
||||
@@ -1339,6 +1656,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
return chunkCutResult{}, cause
|
||||
}
|
||||
|
||||
// Before the pause: the once-per-layer UNKNOWN seed, and one sync so the
|
||||
// pause's own sync flushes only what came after it (the first cut after a
|
||||
// fill pays its write-back here). The in-pause sync still fixes H.
|
||||
l.prepareTouched()
|
||||
preSync := time.Now()
|
||||
if _, err := l.s.syncWithPhases(nil); err != nil {
|
||||
st.PreSyncNs = time.Since(preSync).Nanoseconds()
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err)
|
||||
}
|
||||
st.PreSyncNs = time.Since(preSync).Nanoseconds()
|
||||
|
||||
// Quiesced cut. The guest pause starts at the Lock REQUEST: a pending
|
||||
// writer blocks new readers of captureMu, so a write arriving while the cut
|
||||
// waits for writers already holding it (e.g. parked in WAL admission) is
|
||||
@@ -1365,6 +1693,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
// Resume rejected tentative admission before any ordinary COW upload.
|
||||
unlockCapture := func() {
|
||||
l.paused = false
|
||||
l.s.captureMu.Unlock()
|
||||
if !detach && releasePrecopy != nil {
|
||||
releasePrecopy()
|
||||
@@ -1375,6 +1704,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
hook()
|
||||
}
|
||||
l.s.captureMu.Lock()
|
||||
l.paused, l.pauseOps = true, 0
|
||||
defer func() { st.PauseCandidateOps = l.pauseOps }()
|
||||
barrier := time.Now()
|
||||
st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds()
|
||||
h, err := l.s.syncWithPhases(&st.SyncPhases)
|
||||
@@ -1389,17 +1720,89 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
l.cutPhase("candidates")
|
||||
candidateStart := time.Now()
|
||||
candidates := map[uint64]bool{}
|
||||
for idx := range l.captureCandidates() {
|
||||
// The pause does O(1) work: the touched set and the dirty set are taken
|
||||
// by pointer swaps and the copy window opens over what they name (a
|
||||
// superset of the candidates). Every per-candidate step runs after the
|
||||
// pause, under the window: the judgement, the versions (atomic with the
|
||||
// write path), staged reuse, the base refs and the copy-order hint.
|
||||
taken := l.takeTouched()
|
||||
// A recovery that landed after prepareTouched moved every clean fill's
|
||||
// version: its request is taken here as a flag (O(1)); the window covers
|
||||
// every chunk until it narrows, and the fills are judged after the pause.
|
||||
filledTaken := l.touchFilled.Swap(false)
|
||||
oracleWant := l.candidateOracleScan() // tests only (nil in production)
|
||||
l.stMu.Lock()
|
||||
dirtyTaken, all := l.dirty, l.allDirty
|
||||
l.dirty, l.allDirty = map[uint64]bool{}, false
|
||||
l.cutLSN = h
|
||||
l.stMu.Unlock()
|
||||
own := l.own // stable for the cut (set and cleared under capMu)
|
||||
covers := func(idx uint64) bool { return all || filledTaken || taken.has(idx) || dirtyTaken[idx] || own[idx] }
|
||||
windowStart := time.Now()
|
||||
w, installErr := l.installCOWWindow(covers, spill)
|
||||
if installErr == nil {
|
||||
w.budget = budget
|
||||
}
|
||||
// The barrier ends here. A pre-copy attempt's drained frontend stays
|
||||
// drained until its freeze decision below, made on the judged tail: its
|
||||
// guest pause runs to that release, as before. An ordinary cut's guest
|
||||
// is back now, and its pause did O(1) work.
|
||||
drained := releasePrecopy != nil
|
||||
l.s.captureMu.Unlock()
|
||||
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
|
||||
if !drained {
|
||||
l.paused = false
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
}
|
||||
releaseDrain := func() {
|
||||
if drained {
|
||||
if releasePrecopy != nil && !detach {
|
||||
releasePrecopy()
|
||||
releasePrecopy = nil
|
||||
}
|
||||
l.paused = false
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
drained = false
|
||||
}
|
||||
}
|
||||
if installErr != nil {
|
||||
releaseDrain()
|
||||
if filledTaken {
|
||||
l.touchFilled.Store(true)
|
||||
}
|
||||
l.requeueTaken(taken, dirtyTaken, all)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr)
|
||||
}
|
||||
|
||||
// After the pause. The judgement: the touched set's members with the
|
||||
// map scan's predicate, the WAL entries up to H, the own batch, the
|
||||
// taken dirty set, and every chunk after a BASE write.
|
||||
members := taken.each
|
||||
if filledTaken {
|
||||
l.stMu.Lock()
|
||||
filled := make([]uint64, 0, len(l.filledClean))
|
||||
for idx := range l.filledClean {
|
||||
filled = append(filled, idx)
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
members = func(f func(uint64)) {
|
||||
taken.each(f)
|
||||
for _, idx := range filled {
|
||||
f(idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates, visits := l.candidatesFrom(members, h)
|
||||
visits += int64(len(taken.summary)) // the summary words the walk read
|
||||
l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause
|
||||
for idx := range dirtyTaken {
|
||||
visits++
|
||||
candidates[idx] = true
|
||||
}
|
||||
l.stMu.Lock()
|
||||
all := l.allDirty
|
||||
for idx := range l.dirty {
|
||||
candidates[idx] = true
|
||||
}
|
||||
if all {
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
visits++
|
||||
// An absent chunk with no local write is HEAD's content by
|
||||
// definition: comparing it would only fetch it back.
|
||||
if l.absent[i] && !l.chunkHasLocalLocked(i) {
|
||||
@@ -1408,72 +1811,79 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
candidates[i] = true
|
||||
}
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
candidateOracleCompare(oracleWant, candidates) // tests only
|
||||
// A chunk known to hold HEAD's bytes at its current version (a clean
|
||||
// fill, or a compare by a cut that did not publish) is not compared
|
||||
// again, whatever returned it to the dirty set: any write since raises
|
||||
// its version, and a newer HEAD changes its ref. A chunk an own batch
|
||||
// re-uploads under this layer's key stays: equal bytes are its point.
|
||||
l.stMu.Lock()
|
||||
l.pauseOp(len(candidates))
|
||||
for idx := range candidates {
|
||||
if l.knownEqualToHeadLocked(idx) {
|
||||
delete(candidates, idx)
|
||||
}
|
||||
}
|
||||
if sh := l.shadow; sh != nil {
|
||||
// Extras are judged only for a cut that can proceed: a store behind
|
||||
// HEAD (H below its RemoteLSN) is refused before any upload, and its
|
||||
// writes are not dirt above HEAD to the engine.
|
||||
proceeds := h >= l.head.RemoteLSN
|
||||
miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != nil && proceeds, proceeds)
|
||||
if hook := l.testShadowCheck; hook != nil {
|
||||
hook(miss, extra)
|
||||
}
|
||||
}
|
||||
// A staged chunk stands for the barrier copy while no write reached
|
||||
// it since staging (its version is unchanged) and HEAD is the one it
|
||||
// was compared against.
|
||||
l.stMu.Unlock()
|
||||
// Each candidate's version at the barrier: the version a guest write's
|
||||
// save recorded with its bytes, else the live one, read atomically with
|
||||
// the write path; the window closes on a chunk only after this and its
|
||||
// upload. A staged chunk stands for the barrier copy while its version
|
||||
// is the barrier's and HEAD is the one it was compared against.
|
||||
var captured []capturedChunk
|
||||
var capturedVersions map[uint64]uint64
|
||||
|
||||
capturedVersions = make(map[uint64]uint64, len(candidates))
|
||||
|
||||
useStaged := map[uint64]bool{}
|
||||
capturedVersions := make(map[uint64]uint64, len(candidates))
|
||||
l.pauseOp(2 * len(candidates)) // versions, staged reuse
|
||||
for idx := range candidates {
|
||||
if capturedVersions != nil {
|
||||
capturedVersions[idx] = l.chunkVersion(idx)
|
||||
}
|
||||
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen {
|
||||
capturedVersions[idx] = w.versionAt(idx)
|
||||
}
|
||||
useStaged := map[uint64]bool{}
|
||||
l.stMu.Lock()
|
||||
for idx := range candidates {
|
||||
if sc, ok := staged[idx]; ok && sc.ver == capturedVersions[idx] && sc.headGen == l.head.Gen {
|
||||
useStaged[idx] = true
|
||||
captured = append(captured, sc.capturedChunk)
|
||||
}
|
||||
}
|
||||
if sh := l.shadow; sh != nil {
|
||||
// Extras are judged only for a cut that can proceed: a store behind
|
||||
// HEAD (H below its RemoteLSN) is refused before any upload, and its
|
||||
// writes are not dirt above HEAD to the engine. A chunk written since
|
||||
// the barrier is in the live touched set: the record counts its write.
|
||||
proceeds := h >= l.head.RemoteLSN
|
||||
after := l.writtenSinceTake
|
||||
skip := func(idx uint64) bool { return l.shadowExemptLocked(idx) || after(idx) }
|
||||
miss, extra := sh.checkAfter(candidates, skip, after, l.testShadowCheck != nil && proceeds, proceeds)
|
||||
if hook := l.testShadowCheck; hook != nil {
|
||||
hook(miss, extra)
|
||||
}
|
||||
}
|
||||
st.CandidateVisits = visits
|
||||
l.inflight = candidates
|
||||
l.dirty = map[uint64]bool{}
|
||||
l.allDirty = false
|
||||
l.cutLSN = h
|
||||
l.pauseOp(2 * len(candidates)) // the shadow check, the base refs
|
||||
baseHead := l.cutBaseLocked(candidates)
|
||||
l.stMu.Unlock()
|
||||
w.narrow(candidates, useStaged, baseHead.Chunks)
|
||||
l.returnTouched(taken)
|
||||
l.cutPhase("compare")
|
||||
// Candidates, mutation versions and the copy-order hint belong to the same barrier.
|
||||
// Do not sample the owned map after COW writers are admitted again.
|
||||
l.pauseOp(len(candidates))
|
||||
recent := l.chunkRecency(candidates, h)
|
||||
st.CandidateNs += time.Since(candidateStart).Nanoseconds()
|
||||
// The authoritative candidate set is fixed with mutation admission closed.
|
||||
// The owner callback is nonblocking and may stop only an already drained
|
||||
// frontend; rejected attempts remain ordinary COW cuts.
|
||||
if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil {
|
||||
tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
|
||||
detach = freeze(tail, pauseStart, st)
|
||||
}
|
||||
releaseDrain()
|
||||
if guestFrozen && !detach {
|
||||
unlockCapture()
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
l.endCOWWindow(w)
|
||||
l.requeueCut(all)
|
||||
return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit())
|
||||
}
|
||||
|
||||
if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) {
|
||||
unlockCapture()
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
l.endCOWWindow(w)
|
||||
// HEAD holds the image of a later LSN than this host's log has
|
||||
// reached: publishing would move remote_lsn backwards. Refused
|
||||
// before any upload. (A HEAD of a newer holder fences below.)
|
||||
@@ -1482,35 +1892,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
|
||||
st.CandidateChunks = max(st.CandidateChunks, len(candidates))
|
||||
var copyErr error
|
||||
copyStart := time.Now()
|
||||
bytesBeforeCopy := st.UploadedBytes
|
||||
{
|
||||
var w *cutCOWWindow
|
||||
windowStart := time.Now()
|
||||
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill)
|
||||
if copyErr == nil {
|
||||
w.budget = budget
|
||||
}
|
||||
unlockCapture()
|
||||
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
copyStart = time.Now()
|
||||
if copyErr == nil {
|
||||
var copied []capturedChunk
|
||||
copied, copyErr = l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
|
||||
for _, c := range copied {
|
||||
if c.key != "" {
|
||||
st.UploadedChunks++
|
||||
st.UploadedBytes += int64(c.size)
|
||||
}
|
||||
}
|
||||
captured = append(captured, copied...)
|
||||
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
|
||||
st.COWSavedChunks = int(w.saved.Load())
|
||||
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
|
||||
copied, copyErr := l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead)
|
||||
for _, c := range copied {
|
||||
if c.key != "" {
|
||||
st.UploadedChunks++
|
||||
st.UploadedBytes += int64(c.size)
|
||||
}
|
||||
}
|
||||
captured = append(captured, copied...)
|
||||
st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load()
|
||||
st.COWSavedChunks = int(w.saved.Load())
|
||||
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
|
||||
|
||||
st.CopyNs = time.Since(copyStart).Nanoseconds()
|
||||
if st.UploadedBytes > bytesBeforeCopy {
|
||||
@@ -2176,6 +2570,7 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) {
|
||||
d := *id.DetachedBy
|
||||
h.DetachedBy = &d
|
||||
}
|
||||
l.touch(changed...) // their refs changed: the next candidate step judges them
|
||||
for _, idx := range changed {
|
||||
r, ok := id.Chunks[idx]
|
||||
switch {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package storage
|
||||
|
||||
import "math/bits"
|
||||
|
||||
// candidateSet is the record's chunk candidate set of one cut interval:
|
||||
// one bit per chunk, and a summary of one bit per 64-chunk word
|
||||
// that has any bit set. Setting a bit is O(1); walking the set is O(C + S/4096)
|
||||
// (the summary's words, then only the words it names); clearing it is O(C).
|
||||
// It is a superset: a bit stays set when the chunk later leaves the candidate
|
||||
// kinds (committed, evicted), and the reader keeps only the chunks whose kind
|
||||
// is still a candidate.
|
||||
type candidateSet struct {
|
||||
words []uint64
|
||||
summary []uint64
|
||||
n int // bits set (a chunk counted once)
|
||||
}
|
||||
|
||||
func newCandidateSet(chunks uint64) *candidateSet {
|
||||
w := (chunks + 63) / 64
|
||||
return &candidateSet{words: make([]uint64, w), summary: make([]uint64, (w+63)/64)}
|
||||
}
|
||||
|
||||
func (s *candidateSet) set(chunk uint64) {
|
||||
w, b := chunk/64, uint64(1)<<(chunk%64)
|
||||
if s.words[w]&b != 0 {
|
||||
return
|
||||
}
|
||||
s.words[w] |= b
|
||||
s.summary[w/64] |= 1 << (w % 64)
|
||||
s.n++
|
||||
}
|
||||
|
||||
func (s *candidateSet) has(chunk uint64) bool { return s.words[chunk/64]&(1<<(chunk%64)) != 0 }
|
||||
|
||||
// each calls f for every chunk in the set, in chunk order.
|
||||
func (s *candidateSet) each(f func(chunk uint64)) {
|
||||
for si, sw := range s.summary {
|
||||
for sw != 0 {
|
||||
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
|
||||
sw &= sw - 1
|
||||
for word := s.words[w]; word != 0; word &= word - 1 {
|
||||
f(w*64 + uint64(bits.TrailingZeros64(word)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// or adds every chunk of o (same shape).
|
||||
func (s *candidateSet) or(o *candidateSet) {
|
||||
o.each(s.set)
|
||||
}
|
||||
|
||||
// clear empties the set, touching only the words it names.
|
||||
func (s *candidateSet) clear() {
|
||||
for si, sw := range s.summary {
|
||||
for sw != 0 {
|
||||
w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw))
|
||||
sw &= sw - 1
|
||||
s.words[w] = 0
|
||||
}
|
||||
s.summary[si] = 0
|
||||
}
|
||||
s.n = 0
|
||||
}
|
||||
|
||||
// Len is the number of chunks in the set.
|
||||
func (s *candidateSet) Len() int { return s.n }
|
||||
@@ -139,6 +139,13 @@ type chunkRecordRuntime struct {
|
||||
changes []int // changes since the page was last written
|
||||
firstDirty []time.Time // when the page went dirty
|
||||
headerG uint64 // the G last written
|
||||
// cand is the candidate set of the current cut interval: every
|
||||
// applied event whose result is a candidate kind (P, U, HU) sets its
|
||||
// chunk, a write that leaves U as U included (new dirt since the last
|
||||
// take). A cut takes it whole and leaves the empty spare in its place;
|
||||
// candTaken counts the takes (the barrier's O(1) work, for its counters).
|
||||
cand, spare *candidateSet
|
||||
candTaken uint64
|
||||
}
|
||||
|
||||
// newChunkRecordRuntime builds the runtime from the record as the open left
|
||||
@@ -157,12 +164,16 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u
|
||||
valid: append([]uint64(nil), valid...),
|
||||
dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs), since: make([]uint64, segs),
|
||||
changes: make([]int, segs), firstDirty: make([]time.Time, segs), headerG: headerG}
|
||||
r.cand, r.spare = newCandidateSet(chunks), newCandidateSet(chunks)
|
||||
for c, k := range kinds {
|
||||
code, err := chunkRecordStateCode(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.kinds[c] = code
|
||||
if isRecordCandidate(k) { // at open: the persisted kinds are the source of truth
|
||||
r.cand.set(uint64(c))
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
for seg, changed := range changedAtOpen {
|
||||
@@ -250,6 +261,9 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
|
||||
delete(r.unmarked, chunk) // an evict: nothing local is claimed
|
||||
}
|
||||
}
|
||||
if isRecordCandidate(res.State.Kind) {
|
||||
r.cand.set(chunk)
|
||||
}
|
||||
if res.State.Kind != cur || newHash != r.hashes[chunk] {
|
||||
code, err := chunkRecordStateCode(res.State.Kind)
|
||||
if err != nil {
|
||||
@@ -274,6 +288,46 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
|
||||
return eff, nil
|
||||
}
|
||||
|
||||
// TakeCandidates hands the current interval's candidate set to a cut and
|
||||
// starts an empty one, in O(1): the record keeps setting chunks into the new
|
||||
// set, so a write after the take is the next cut's. The cut gives the set
|
||||
// back with ReturnCandidates (its candidates OR'd back if the cut did not
|
||||
// commit them), never keeps it.
|
||||
func (r *chunkRecordRuntime) TakeCandidates() *candidateSet {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
taken := r.cand
|
||||
if r.spare == nil { // a second take before the first set came back
|
||||
r.spare = newCandidateSet(r.chunks)
|
||||
}
|
||||
r.cand, r.spare = r.spare, nil
|
||||
r.candTaken++
|
||||
return taken
|
||||
}
|
||||
|
||||
// ReturnCandidates gives a taken set back. With keep (a refused, unknown or
|
||||
// aborted cut) its chunks join the current interval's set again, so no
|
||||
// candidate is lost; the set is then cleared (O(C)) and becomes the spare.
|
||||
func (r *chunkRecordRuntime) ReturnCandidates(taken *candidateSet, keep bool) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if keep {
|
||||
r.cand.or(taken)
|
||||
}
|
||||
taken.clear()
|
||||
if r.spare == nil {
|
||||
r.spare = taken
|
||||
}
|
||||
}
|
||||
|
||||
// IsCandidate reports whether a chunk's kind is a candidate now (a taken
|
||||
// set is a superset: the cut keeps only these).
|
||||
func (r *chunkRecordRuntime) IsCandidate(chunk uint64) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return isRecordCandidate(kindByCode[r.kinds[chunk]])
|
||||
}
|
||||
|
||||
// PersistSegmentOf writes the page holding chunk if it is dirty (no-op if
|
||||
// its last written content is current): the durable receipt an evict needs
|
||||
// before the store's bits may clear, also when the in-memory state was
|
||||
|
||||
@@ -257,13 +257,19 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head
|
||||
}
|
||||
|
||||
// commit is E5 and E6: a HEAD names the chunk's captured hash. Skipped when
|
||||
// the chunk was written since its capture.
|
||||
// the chunk was written since its capture, and when the record does not hold
|
||||
// a hash for it (HU or HP): a cut that captured the chunk while its absence
|
||||
// stood sent no Hash, and on v1.0 its local bits can complete since (landed,
|
||||
// P to U, with no version change); the chunk stays a candidate.
|
||||
func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) bool {
|
||||
if c.idx >= s.rec.chunks {
|
||||
return false
|
||||
}
|
||||
same := capturedAt(c.version, current)
|
||||
_, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same)
|
||||
hashedAt := func(k chunkkernel.Kind) bool {
|
||||
return (k == chunkkernel.HashUnpublished || k == chunkkernel.HashPublished) && same(k)
|
||||
}
|
||||
_, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, hashedAt)
|
||||
if err != nil {
|
||||
s.defect(c.idx, chunkkernel.Commit, err)
|
||||
}
|
||||
@@ -370,6 +376,13 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat
|
||||
// the misses and, when withExtra (tests: a full scan of the record, too
|
||||
// slow for a barrier), the record's extra candidates. Caller holds stMu.
|
||||
func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
|
||||
return s.checkAfter(engine, skip, nil, withExtra, proceeds)
|
||||
}
|
||||
|
||||
// checkAfter is check for candidates judged after the guest pause: after,
|
||||
// when set, names the chunks written since the barrier (the record already
|
||||
// counts those writes), which are no record extra of this cut.
|
||||
func (s *chunkRecordShadow) checkAfter(engine map[uint64]bool, skip, after func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
|
||||
s.rec.mu.Lock()
|
||||
for idx := range engine {
|
||||
if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) {
|
||||
@@ -381,7 +394,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool
|
||||
s.fullScans++
|
||||
for idx, code := range s.rec.kinds {
|
||||
k := kindByCode[code]
|
||||
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) {
|
||||
if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) && (after == nil || !after(uint64(idx))) {
|
||||
extra = append(extra, uint64(idx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,12 @@ func TestMain(m *testing.M) {
|
||||
found = append(found, msg)
|
||||
mu.Unlock()
|
||||
}
|
||||
// Every barrier also checks its touched-set candidates against the full
|
||||
// scan; a chunk the set missed is a finding too.
|
||||
candidateOracle = func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg) // in place, next to the test that ran it
|
||||
shadowFindings(msg)
|
||||
}
|
||||
// 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.
|
||||
@@ -28,7 +34,7 @@ func TestMain(m *testing.M) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(found) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0])
|
||||
fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow or candidate oracle findings; first: %s\n", len(found), found[0])
|
||||
if code == 0 {
|
||||
code = 1
|
||||
}
|
||||
@@ -42,8 +48,13 @@ func TestMain(m *testing.M) {
|
||||
func forgetMarksAsARestart(t *testing.T, l *chunkLayerImpl) {
|
||||
t.Helper()
|
||||
l.stMu.Lock()
|
||||
forgotten := make([]uint64, 0, len(l.filledClean))
|
||||
for idx := range l.filledClean {
|
||||
forgotten = append(forgotten, idx)
|
||||
}
|
||||
l.filledClean = map[uint64]filledMark{}
|
||||
l.stMu.Unlock()
|
||||
l.touch(forgotten...) // a restarted layer's seed judges them again
|
||||
sh, err := newChunkRecordShadow(l)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -620,3 +620,77 @@ func TestShadowScratchExemptionIsBoundToItsCapturedVersion(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// E6 on a v1.0 shadow: a cut captured a written absent chunk while its
|
||||
// absence stood (P: Hash skipped), and the flusher then completed the
|
||||
// chunk's local bits (landed, P to U, with no write and so no version
|
||||
// change) before the cut published. The publish's Commit at the captured
|
||||
// version meets U: it is skipped, not sent (the kernel refuses U/Commit),
|
||||
// and the chunk stays U, a candidate for the next cut.
|
||||
func TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped(t *testing.T) {
|
||||
s, l, _ := lazyFreshVolume(t)
|
||||
const idx = 3
|
||||
if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD3)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k := shadowKind(l, idx); k != chunkkernel.Partial {
|
||||
t.Fatalf("setup: the written absent chunk is %s, want P", k)
|
||||
}
|
||||
current := func() uint64 { return l.chunkVersion(idx) }
|
||||
c := capturedChunk{idx: idx, version: current(), sum: [32]byte{1}}
|
||||
l.shadow.hashed(c, current, chunkHead{}) // the cut's compare: skipped on P (a scratch capture)
|
||||
l.stMu.Lock()
|
||||
l.shadow.landed(idx) // the flusher completes the chunk's local bits
|
||||
l.stMu.Unlock()
|
||||
if k := shadowKind(l, idx); k != chunkkernel.Unknown || current() != c.version {
|
||||
t.Fatalf("setup: after landing %s at version %d, want U at the captured version %d", k, current(), c.version)
|
||||
}
|
||||
l.shadowCommit([]capturedChunk{c}, map[uint64]uint64{idx: c.version}) // the publish
|
||||
if n := shadowDefects(l); n != 0 {
|
||||
t.Fatalf("%d shell events refused: Commit was sent for a chunk the record holds U", n)
|
||||
}
|
||||
if k := shadowKind(l, idx); k != chunkkernel.Unknown {
|
||||
t.Fatalf("after the publish: %s, want U (a candidate for the next cut)", k)
|
||||
}
|
||||
}
|
||||
|
||||
// The model's premise "every record state change moves the chunk version"
|
||||
// holds on v1.1 only: there an extent write never lands an absent chunk
|
||||
// (the write's own event carries the store's bits), so completing a written
|
||||
// chunk's local bits through the flusher leaves its kind and version as they
|
||||
// were. On v1.0 the same extent writes land it (P to U) with no version
|
||||
// change: the case the Commit guard covers.
|
||||
func TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10(t *testing.T) {
|
||||
for _, v11 := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "v1.1", false: "v1.0"}[v11], func(t *testing.T) {
|
||||
if v11 {
|
||||
withV11Format(t)
|
||||
} else {
|
||||
v10Only(t) // the control is v1.0's, whatever format the run selected
|
||||
}
|
||||
s, l, _ := lazyFreshVolume(t)
|
||||
const idx = 3
|
||||
lsn, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD4))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kind, version := shadowKind(l, idx), l.chunkVersion(idx)
|
||||
if kind != chunkkernel.Partial {
|
||||
t.Fatalf("setup: the written absent chunk is %s, want P", kind)
|
||||
}
|
||||
for b := uint64(0); b < ctChunkBlocks; b++ {
|
||||
l.OnExtentWrite(idx*ctChunkBlocks+b, lsn) // the flusher's extent writes complete the local bits
|
||||
}
|
||||
after, v := shadowKind(l, idx), l.chunkVersion(idx)
|
||||
switch {
|
||||
case v11 && (after != kind || v != version):
|
||||
t.Fatalf("v1.1: extent writes moved the record %s->%s (version %d->%d): an extent write must not land a chunk", kind, after, version, v)
|
||||
case !v11 && (after != chunkkernel.Unknown || v != version):
|
||||
t.Fatalf("v1.0 control: %s at version %d, want U at the same version %d (landed)", after, v, version)
|
||||
}
|
||||
if n := shadowDefects(l); n != 0 {
|
||||
t.Fatalf("%d shell events refused", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,10 @@ import (
|
||||
// under-report.
|
||||
type chunkSink interface {
|
||||
OnExtentWrite(lba uint64, lsn uint64)
|
||||
// OnMapEntryChange is called when the store changes a chunk's map entry
|
||||
// (a write's LSN, or UNKNOWN by a direct/BASE mutation or a reused LSN):
|
||||
// O(1), under WALStore.mu; it takes only a leaf lock.
|
||||
OnMapEntryChange(chunk uint64)
|
||||
BeforeCheckpointAdvance(lsn uint64) error
|
||||
BeginBaseInstall() error
|
||||
EndBaseInstall(frontier uint64) error
|
||||
@@ -419,6 +423,17 @@ type SyncPhaseStats struct {
|
||||
|
||||
type chunkCutStats struct {
|
||||
SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it)
|
||||
// CandidateVisits counts the chunk indices the barrier's candidate step
|
||||
// visited (scanned entries and set members), the work a pause pays for.
|
||||
CandidateVisits int64
|
||||
// PauseCandidateOps counts per-candidate operations done while the guest
|
||||
// is paused (from the barrier lock to its release): zero when the pause
|
||||
// does O(1) work.
|
||||
PauseCandidateOps int64
|
||||
// PreSyncNs is the sync right before the barrier, outside the guest
|
||||
// pause (never part of BarrierPauseNs): the pause's own sync then has
|
||||
// only what came after it.
|
||||
PreSyncNs int64
|
||||
// Disjoint non-payload intervals within barrier-to-settlement fixed cost.
|
||||
CandidateNs int64
|
||||
WindowSetupNs int64
|
||||
|
||||
@@ -34,6 +34,9 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) {
|
||||
e.Local = e.Local.mark(lba%cb, count)
|
||||
}
|
||||
v.mapEntries.set(index, e)
|
||||
if h := s.chunk.Load(); h != nil {
|
||||
h.sink.OnMapEntryChange(uint64(index))
|
||||
}
|
||||
}
|
||||
|
||||
// Recover may scan retained records already represented by the durable bitmap.
|
||||
|
||||
@@ -18,6 +18,7 @@ func (h *heldWALReadMiss) OnReadMiss(uint64) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (*heldWALReadMiss) OnExtentWrite(uint64, uint64) {}
|
||||
func (*heldWALReadMiss) OnMapEntryChange(uint64) {}
|
||||
func (*heldWALReadMiss) BeforeCheckpointAdvance(uint64) error { return nil }
|
||||
func (*heldWALReadMiss) BeginBaseInstall() error { return nil }
|
||||
func (*heldWALReadMiss) EndBaseInstall(uint64) error { return nil }
|
||||
|
||||
@@ -617,6 +617,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`); also in `core/frontend/durable/takeover_read_ready_test.go` | — | ACTIVE |
|
||||
| `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-NVME-CANCEL-001` | Closing an NVMe target cancels connection readiness waits before joining workers. Attach-pending reads and writes honour caller cancellation without accessing storage. | M1 Opened / Recovering; frontend shutdown | `core/frontend/nvme/target.go` `handleConn`; `session.go` `serve`; `core/frontend/durable/storage_adapter.go` `awaitAttachAdmission` | `TestTargetCloseCancelsPendingProviderReadiness`, `TestNVMeReadinessCancelProcess` (`core/frontend/nvme/target_cancel_test.go`); `TestAttachReadinessReadAndWriteHonourCallerCancellation` (`core/frontend/durable/read_ready_wait_test.go`) | NONE (frontend cancellation plumbing; no durable state transition) | ACTIVE |
|
||||
| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE |
|
||||
| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 when the startup wait runs out (`INV-WS-MASTER-WAIT-001`). | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; shared readiness rule); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`); `cmd/sw-block/shell_check.go` `FrontendPrimaryReady` | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE |
|
||||
@@ -637,6 +638,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
|
||||
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
|
||||
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
|
||||
| `INV-WAL-V3-CAPTURE-CANDIDATES-TOUCHED-001` | The barrier's candidate step judges only a touched set (a chunk bitmap with a word summary) with INV-WAL-V3-CAPTURE-CANDIDATES-001's predicate, never every chunk; the set covers every chunk whose answer may have changed since the barrier took it. The cut syncs before the barrier, outside the pause. | M5 candidate selection (CandBitmap: NoBitLost, SummaryCovers) | `chunk_layer.go` `candidatesFrom`, `takeTouched`, `seedTouched`, `touch`, `OnMapEntryChange`, `noteMutation`, `setHeadLocked`, `applyCommitLocked`; `walstore_map_checkpoint_v3.go` `recordMapWriteV3`; `base_install_v3.go` `markMapUnknownV3`; `chunk_record_candidates.go` `candidateSet` | `TestIdleCutCandidateWorkIsFlatInS`, `TestOneChangedChunkCutVisitsNoFullScan`, `TestCutSyncsBeforeItsBarrier`, `TestUnknownCommitOutcomeLosesNoChunk`, `TestCandidateSetOrBackKeepsTheSummary` (`chunk_cut_candidate_set_test.go`); `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestACleanFillRecordEndsWithItsHeadRef` (`chunk_fresh_readback_candidates_test.go`); `TestSpacePerChunkAt1TiBShape` (`chunk_space_baseline_test.go`) | The candidate set is the same; an idle cut's candidate work no longer grows with S | ACTIVE |
|
||||
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE |
|
||||
| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB |
|
||||
| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE |
|
||||
@@ -647,7 +649,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-CHUNK-RECORD-SEED-001` | The v1.0.x upgrade seeds a whole local chunk as published with HEAD's hash only on an unmarked store, with a clean stop read on the HEAD the claim was built on (an idle detach of the store's lineage) at the store's synced position; otherwise it is unknown. | M1 Recovering → Serving (v1.1 upgrade at attach, after a clean stop) | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `TestStart_ReportsTheCleanStopItClaimedFrom`, `TestStart_TheCleanStopIsTheClaimsOwnRead`, `TestStart_NoCleanStopWithoutADetachOfThisLineage` (`core/frontend/chunkstore/layout/start_cleanstop_test.go`); `TestUpgradeSeedsAfterACleanStop`, `TestUpgradeSeedNeedsTheStoreAtTheProofPosition`, `TestUpgradeSeedNeedsTheStoresLineage`, `TestUpgradeSeedNeedsAProofHEADStillShows`, `TestUpgradeSeedCrashAtEachStep` (`core/storage/chunk_record_seed_test.go`); `TestV11AttachSeedsFromTheCleanStopInItsConfig` (`core/storage/chunk_record_v11_seed_test.go`); `TestStartLayoutRootReportsTheCleanStop` (`core/frontend/durable/provider_layout_cleanstop_test.go`) | UpgradeWide3 rows 122 and 123 (`Proof`, `SameEpoch` judged on the HEAD the claim is built on; the claim is a stutter on image and position), 126 to 128 (the per-chunk state models are not in this repository) | STUB |
|
||||
| `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB |
|
||||
| `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a hash only with its evidence; a page dirties only on a state or hash change and is written by its count or age (an evict's at once), in snapshot order, after the WAL is synced through the position it shows; G <= min(applied, dirty-from, WAL synced). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush`, `writeSegmentLocked` (`syncThrough`), `writeHeaderLocked` (`durable`) | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`); the WAL bound: `TestV11NoPageClaimsMoreThanTheDurableWAL`, `TestV11APageNeverShowsAWriteTheWALCanLose` (`core/storage/chunk_record_v11_review_test.go`, `chunk_record_v11_hold_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB |
|
||||
| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE |
|
||||
| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped`, `TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE |
|
||||
| `INV-CHUNK-RECORD-V11-001` | On the draft v1.1 format a layer upgrades its store once at attach and opens from its record; a fill's page claims no local block before one durable mark (partial fills and later writes too); an evict clears the store's bits only after its absent page is durable, retries too. | M1 Opened, M3 Serving (draft v1.1 format) | `core/storage/chunk_record_open.go` `openChunkRecordV11`, `loadChunkRecordV11`, `markFills`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordWith`; `core/storage/chunk_record_runtime.go` `holdFills`, `PersistSegmentOf`; `core/storage/chunk_record_shadow.go` `evict`; `core/storage/chunk_layer.go` `EvictChunk`, `Close` | `TestV11AttachUpgradesTheStoreOnce`, `TestV11ReopenJudgesAWriteAfterThePageAsChanged`, `TestV11CleanStopWritesOnlyTheDirtyPages`, `TestV11UpgradeRecoversFromACrashAtEachStep`, `TestV11DamagedPageIsRebuiltFromTheStoreBits`, `TestV11FillsAreMarkedInOneBatchBeforeTheirPagesClaimThem`, `TestV11EvictSurvivesARestart` (`core/storage/chunk_record_v11_test.go`); `TestV11CloseDuringTheUpgradeRefusesTheAttach`, `TestV11EvictWithoutItsAbsentPageClearsNothing`, `TestV11ParkedFillBatchCannotOverwriteAnEvict`, `TestV11MalformedLeftoverPresenceDoesNotRefuseTheAttach`, `TestV11FinalPageFailureIsTheCloseResult` (`core/storage/chunk_record_v11_review_test.go`); `TestV11PartialFillWaitsForTheDurableMark`, `TestV11WriteAfterAHeldFillKeepsTheHold`, `TestV11EvictRetryStillWritesItsAbsentPage` (`core/storage/chunk_record_v11_hold_test.go`); `TestV11AbsentChunkSurvivesALostHeader`, `TestV11LogOnlyWriteSurvivesTheUpgrade` (`core/storage/chunk_record_v11_upgrade_test.go`) | chunk-kernel/2; CoverageDurable row 199 (the WAL is durable through a published position) (not in this repository) | DORMANT |
|
||||
| `INV-CHUNK-FORMAT-LEVEL-001` | An attach raises a volume to v1.1 only at the assigned format level 1 (absent = 0); at level 0 it runs v1.1 only over a version-1 HEAD (reported), refuses a v1.1 store over a version-0 HEAD, and a v1.1 attach refuses a remote without the HEAD format. | M-format gate (holder) | `core/storage/chunk_v11_format.go` `attachLevelV11`, `levelZeroFormat`; `core/storage/chunk_layer.go` `attachChunkLayerImpl`; `core/frontend/chunkstore/layout/format_level.go` `checkFormatLevel` (in `runTransition`); `core/frontend/chunkstore/layout_remote.go` `SetHeadFormat`, `HeadV11`; `core/host/volume/host.go` `applyFact`; `core/frontend/durable/provider_chunk.go` `attachFormatLevel` | `TestAttachFormatFollowsTheAssignedLevel`, `TestAttachAtLevelZeroOfAnUpgradedStore`, `TestAttachAtLevelZeroOfAV11HeadOverAnUnmarkedStore`, `TestAV11AttachRefusesARemoteWithoutTheHeadFormat`, `TestALevelOneCrashBeforeTheFirstCutReattachesAsV11`, `TestAV11AttachRefusesARemoteThatDeclinesTheHeadFormat` (`core/storage/chunk_format_level_test.go`); `TestLayoutRemoteHeadFormatFollowsItsLayer`, `TestALevelZeroCommitCannotRaiseHeadToVersionOne` (`core/frontend/chunkstore/layout_manifest_size_test.go`); `TestNoHeadWriteRaisesTheVersionBelowFormatLevelOne` (`core/frontend/chunkstore/layout/format_level_test.go`); `TestTheWrappedRemoteForwardsTheHeadFormatBothWays`, `TestAttachFormatLevelFromTheAssignment` (`core/frontend/durable/format_level_test.go`); `TestTheAssignedLevelDecidesTheStoredHeadAcrossARestart` (`core/frontend/durable/format_level_layout_test.go`); `TestTheSelfAssignmentsFormatLevelReachesTheProjection` (`core/host/volume/format_level_test.go`) | none | ACTIVE |
|
||||
| `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE |
|
||||
@@ -1220,6 +1222,7 @@ Notes:
|
||||
| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated Cleaner.removePlanned and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 10 snapshots (`MaxSnapshots`) 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-HEAD-V11-VERSION-001` | Any HEAD carrying a v1.1-only field (a manifest size, ext) is version 1, and a v1.1 commit writes version 1 whether or not it knows the manifest size; a version-0 HEAD with one is refused. | M-snapshot commit | `core/frontend/chunkstore/layout/commit.go` `withManifestBytes`; `core/frontend/chunkstore/layout/head.go` `check`, `checkExt`; `core/frontend/chunkstore/layout_remote.go` (`CommitRequest.V11`) | `TestCommitRecordsTheManifestSize` (`core/frontend/chunkstore/layout/head_version_test.go`); `TestACommitByChangeKeepsAnUnknownSizeUnknown` (`core/frontend/chunkstore/layout_manifest_size_test.go`) | none | ACTIVE |
|
||||
| `INV-SNAPK-HEAD-V11-STAMP-001` | Every write that leaves a version-1 HEAD stamps each snapshot that has no publishing generation with that write's generation; a version-1 HEAD write with an unstamped snapshot is refused, reads stay tolerant. | M-snapshot commit | `core/frontend/chunkstore/layout/head.go` `runTransition`; `core/frontend/chunkstore/layout/snapshot_generation.go` `stampedForWrite`, `checkWrite` | `TestV11CutPublishesASnapshotThatCanBeDeletedByItsTarget`, `TestV11FirstCutStampsTheLegacySnapshots`, `TestVersion1UnstampedSnapshotIsRefusedOnWriteOnly` (`core/frontend/chunkstore/layout/snapshot_stamp_write_test.go`) | none | ACTIVE |
|
||||
| `INV-SNAPK-HEAD-FORMAT-LEVEL-001` | No HEAD write raises HEAD from version 0 to version 1 below format level 1 (a writer's level absent = 0), whichever writer tries; a HEAD already at version 1 stays writable at any level. | M-snapshot commit | `core/frontend/chunkstore/layout/format_level.go` `checkFormatLevel`, `WithFormatLevel`; `core/frontend/chunkstore/layout/head.go` `runTransition`; `core/frontend/chunkstore/layout_remote.go` `atFormatLevel` | `TestNoHeadWriteRaisesTheVersionBelowFormatLevelOne` (`core/frontend/chunkstore/layout/format_level_test.go`); `TestALevelZeroCommitCannotRaiseHeadToVersionOne` (`core/frontend/chunkstore/layout_manifest_size_test.go`) | none | 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 |
|
||||
|
||||
@@ -24,6 +24,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
|
||||
the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one
|
||||
`level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An
|
||||
explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses.
|
||||
- A cut's barrier no longer walks every chunk to find its candidates: its candidate work is the chunks that
|
||||
changed plus one summary word per 4,096 chunks, so an idle cut's pause does not grow with the volume's size. The
|
||||
cut also syncs the store once right before its barrier, outside the guest pause (reported as `PreSyncNs`), so the
|
||||
pause's own sync has only what was written after it.
|
||||
|
||||
## Upgrade
|
||||
- With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was
|
||||
|
||||
@@ -274,6 +274,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
|
||||
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock |
|
||||
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable |
|
||||
| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion |
|
||||
| `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. |
|
||||
| `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. |
|
||||
| `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. |
|
||||
| `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. |
|
||||
| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. |
|
||||
| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. |
|
||||
|
||||
Reference in new issue
Block a user