mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Merge main into fix/precopy-rate-floor
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
409e7cb522
60 files changed
+2615
-245
No files matched your search
+9
-2
@@ -37,6 +37,10 @@ expect() { # expect pass|fail name
|
||||
}
|
||||
repo; expect pass "the real recipes, unchanged"
|
||||
repo; printf '// %s\npackage x\n' "$tag" > "$r/core/x/x.go"; gadd; expect fail "the tag outside the allowlist"
|
||||
repo; printf '// swblock_v11_format
|
||||
package x
|
||||
' > "$r/core/x/x.go"; gadd; expect fail "the format tag outside the allowlist"
|
||||
repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags swblock_v11_format -o /out/blockvolume#"; expect fail "the format tag in a real recipe's build"
|
||||
repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags $tag -o /out/blockvolume#"; expect fail "the tag in a real recipe's build"
|
||||
repo; edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the real recipe's RUN guard deleted, its comment kept"
|
||||
repo; edit "$csi" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the CSI recipe's RUN guard deleted, its comment kept"
|
||||
@@ -55,12 +59,15 @@ r="$t/notgit"; mkdir -p "$r"; expect fail "a directory the scan cannot read as a
|
||||
b="$t/bin"; mkdir -p "$b"
|
||||
printf '#!/bin/sh\necho "b revision=1 modified=false"\n' > "$b/release"
|
||||
printf '#!/bin/sh\necho "b revision=1 modified=false LAB BUILD(%s)"\n' "$tag" > "$b/lab"
|
||||
printf '#!/bin/sh
|
||||
echo "b revision=1 modified=false LAB BUILD(swblock_v11_format)"
|
||||
' > "$b/draft"
|
||||
printf '#!/bin/sh\nexit 3\n' > "$b/broken"
|
||||
printf '#!/bin/sh\nexit 0\n' > "$b/silent"
|
||||
chmod +x "$b"/*
|
||||
bash "$refuse" "$b/release" >/dev/null || { echo "FAIL: refuse-lab-binary refused a release binary"; exit 1; }
|
||||
for x in lab broken silent; do
|
||||
for x in lab draft broken silent; do
|
||||
if bash "$refuse" "$b/release" "$b/$x" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed a $x binary"; exit 1; fi
|
||||
done
|
||||
if bash "$refuse" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed with no binary"; exit 1; fi
|
||||
echo "lab-tag-check controls: OK ($n repositories, 4 binaries)"
|
||||
echo "lab-tag-check controls: OK ($n repositories, 5 binaries)"
|
||||
+27
-21
@@ -1,8 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# The lab-only build tag swblock_lab_bigvol lifts the 256 GiB create cap and
|
||||
# the local headroom refusal for scale rehearsals. It must never reach an
|
||||
# image or a release build. Two checks, both failing closed:
|
||||
# 1. Allowlist: only the files below may name the tag (git grep over the
|
||||
# The lab-only build tags must never reach an image or a release build:
|
||||
# swblock_lab_bigvol lifts the 256 GiB create cap and the local headroom
|
||||
# refusal for scale rehearsals; swblock_v11_format turns on the draft v1.1
|
||||
# store format. Two checks, both failing closed:
|
||||
# 1. Allowlist: only the files below may name either tag (git grep over the
|
||||
# tracked tree; a scan that cannot run is a failure, never "clean").
|
||||
# 2. Wiring: every image Dockerfile under deploy/ that runs go build also runs
|
||||
# scripts/refuse-lab-binary.sh after its last go build, and the publish
|
||||
@@ -12,7 +13,7 @@
|
||||
# unreadable input (printed).
|
||||
set -euo pipefail
|
||||
root=${1:-.}
|
||||
tag=swblock_lab_bigvol
|
||||
tags='swblock_lab_bigvol swblock_v11_format'
|
||||
allowed='.github/scripts/lab-tag-check-test.sh
|
||||
.github/scripts/lab-tag-check.sh
|
||||
.github/workflows/test.yml
|
||||
@@ -20,8 +21,9 @@ core/host/volume/status_heap_lab.go
|
||||
core/host/volume/status_heap_lab_test.go
|
||||
core/host/volume/status_heap_release.go
|
||||
core/host/volume/status_heap_release_test.go
|
||||
core/storage/chunk_v11_format_lab.go
|
||||
core/storage/chunk_v11_format_draft.go
|
||||
core/storage/chunk_v11_format_release.go
|
||||
core/storage/chunk_v11_format_tag_test.go
|
||||
core/frontend/durable/headroom.go
|
||||
core/frontend/durable/headroom_lab_test.go
|
||||
core/geometry/volume_size.go
|
||||
@@ -32,24 +34,28 @@ core/geometry/volume_size_release_test.go
|
||||
docs/design/invariants.md
|
||||
docs/lab-heap-profiles.md
|
||||
internal/buildinfo/buildinfo.go
|
||||
internal/buildinfo/v11_format_draft.go
|
||||
internal/buildinfo/v11_format_release.go
|
||||
scripts/refuse-lab-binary.sh'
|
||||
fail() { echo "lab-tag: $*" >&2; exit 1; }
|
||||
[ -d "$root" ] || fail "no repository at $root"
|
||||
set +e
|
||||
hits=$(git -C "$root" grep -l -- "$tag")
|
||||
rc=$?
|
||||
set -e
|
||||
case $rc in
|
||||
0) ;;
|
||||
1) hits="" ;;
|
||||
*) fail "git grep failed (rc=$rc): the scan did not run" ;;
|
||||
esac
|
||||
bad=""
|
||||
while IFS= read -r f; do
|
||||
[ -n "$f" ] || continue
|
||||
printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f"
|
||||
done <<< "$hits"
|
||||
[ -z "$bad" ] || fail "$tag named outside the allowlist:$bad"
|
||||
for tag in $tags; do
|
||||
set +e
|
||||
hits=$(git -C "$root" grep -l -- "$tag")
|
||||
rc=$?
|
||||
set -e
|
||||
case $rc in
|
||||
0) ;;
|
||||
1) hits="" ;;
|
||||
*) fail "git grep failed (rc=$rc): the scan did not run" ;;
|
||||
esac
|
||||
bad=""
|
||||
while IFS= read -r f; do
|
||||
[ -n "$f" ] || continue
|
||||
printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f"
|
||||
done <<< "$hits"
|
||||
[ -z "$bad" ] || fail "$tag named outside the allowlist:$bad"
|
||||
done
|
||||
|
||||
# read FILE: its whole content, once; a read that fails is a failure, never
|
||||
# "no match".
|
||||
|
||||
+12
-8
@@ -100,20 +100,24 @@ jobs:
|
||||
if: matrix.suite == 'unit'
|
||||
run: go vet ./...
|
||||
|
||||
- name: Lab build tag stays out of images and releases
|
||||
- name: Lab build tags stay out of images and releases
|
||||
if: matrix.suite == 'unit'
|
||||
# swblock_lab_bigvol lifts the 256 GiB create cap and the local
|
||||
# headroom refusal for scale rehearsals only. The default test run
|
||||
# pins the release cap (TestReleaseBuildKeepsTheCreateCap). This step
|
||||
# checks the tag allowlist and that every image Dockerfile refuses a
|
||||
# lab binary (scripts/refuse-lab-binary.sh) after its build, with
|
||||
# controls, then tests the lab build.
|
||||
# headroom refusal for scale rehearsals only; swblock_v11_format turns
|
||||
# on the draft v1.1 store format. The default test run pins the
|
||||
# release cap (TestReleaseBuildKeepsTheCreateCap) and the release
|
||||
# format. This step checks the tags' allowlist and that every image
|
||||
# Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after
|
||||
# its build, with controls, then tests each tag alone and both.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash .github/scripts/lab-tag-check.sh .
|
||||
bash .github/scripts/lab-tag-check-test.sh
|
||||
go vet -tags swblock_lab_bigvol ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/
|
||||
go test -count=1 -tags swblock_lab_bigvol -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/
|
||||
for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do
|
||||
go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/
|
||||
go test -count=1 -tags "$tags" -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/
|
||||
go test -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/
|
||||
done
|
||||
|
||||
- name: Test default configuration
|
||||
if: matrix.suite == 'unit'
|
||||
|
||||
@@ -403,13 +403,19 @@ func (env *handoffEnv) start(t *testing.T, name, id string) *daemon {
|
||||
return env.h.start(t, name, env.h.volume, env.volArgs(id)...)
|
||||
}
|
||||
|
||||
// adopt waits for the process to adopt v1 as primary and its host to report
|
||||
// it healthy, and returns the epoch.
|
||||
// adopt waits for the process to adopt v1 as primary, its host to report it
|
||||
// a healthy primary, and its frontend to admit guest I/O
|
||||
// (FrontendPrimaryReady), and returns the epoch. Healthy alone is not
|
||||
// enough: until the frontend admits I/O, a write is answered "namespace not
|
||||
// ready" (retryable), which the test's initiator does not retry.
|
||||
func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 {
|
||||
t.Helper()
|
||||
_, mustU := fatalOn(t)
|
||||
e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@")))
|
||||
env.h.waitPrimaryAt(t, env.hosts[id].status, e)
|
||||
poll(t, 60*time.Second, fmt.Sprintf("%s: the holder adopted epoch %d but never reported its frontend ready", id, e), func() bool {
|
||||
return env.frontendReadyAt(id)
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,9 @@ type Publisher struct {
|
||||
// (SetIncarnationSource); its own lock, never taken under mu.
|
||||
incarnationMu sync.RWMutex
|
||||
incarnationOf func(volumeID, replicaID, dataAddr, ctrlAddr string) string
|
||||
// lineChanged is told the volume of every published line (the
|
||||
// observation build reads lines, and no heartbeat carries them).
|
||||
lineChanged func(volumeID string)
|
||||
|
||||
mu sync.Mutex
|
||||
state map[subKey]assignmentState
|
||||
@@ -479,6 +482,14 @@ func (p *Publisher) SetIncarnationSource(of func(volumeID, replicaID, dataAddr,
|
||||
p.incarnationMu.Unlock()
|
||||
}
|
||||
|
||||
// SetLineChangeHook registers fn, told the volume of every published line
|
||||
// after the publication (outside the publisher's lock). nil removes it.
|
||||
func (p *Publisher) SetLineChangeHook(fn func(volumeID string)) {
|
||||
p.incarnationMu.Lock()
|
||||
p.lineChanged = fn
|
||||
p.incarnationMu.Unlock()
|
||||
}
|
||||
|
||||
func (p *Publisher) apply(ask AssignmentAsk) error {
|
||||
if p.publicationAdmission != nil {
|
||||
return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) })
|
||||
@@ -750,6 +761,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
if p.observer != nil {
|
||||
safeInvokePublishObserver(p.observer, PublishEvent{Info: next, Ask: ask})
|
||||
}
|
||||
p.incarnationMu.RLock()
|
||||
changed := p.lineChanged
|
||||
p.incarnationMu.RUnlock()
|
||||
if changed != nil {
|
||||
changed(ask.VolumeID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
// What a snapshot build reads changes only by a heartbeat that changes it,
|
||||
// by time (a server's or a slot's expiry, the pending grace's end), by a
|
||||
// published line, or by the topology. A heartbeat that refreshes only
|
||||
// timestamps changes none of these, so it wakes no rebuild; the time each
|
||||
// such fact changes is kept as a deadline, and the host wakes then.
|
||||
|
||||
// buildReadsChangedLocked says whether storing next for its server (prev the
|
||||
// observation it replaces) can change a snapshot build at now: a new server;
|
||||
// a change of the server's facts or freshness; a slot added, removed, or
|
||||
// changed in anything but its timestamps; a slot whose expiry state flips;
|
||||
// or any slot of a volume that another server also reports (a build orders
|
||||
// such slots by their timestamps, so a refresh can change it). s.mu held.
|
||||
func (s *ObservationStore) buildReadsChangedLocked(prev Observation, hadPrev bool, next Observation, now time.Time) bool {
|
||||
if !hadPrev || prev.Server != next.Server || now.After(prev.ExpiresAt) != now.After(next.ExpiresAt) || len(prev.Slots) != len(next.Slots) {
|
||||
return true
|
||||
}
|
||||
before := make(map[string]SlotFact, len(prev.Slots))
|
||||
for _, sl := range prev.Slots {
|
||||
before[slotKey(sl)] = sl
|
||||
}
|
||||
for _, sl := range next.Slots {
|
||||
p, ok := before[slotKey(sl)]
|
||||
if !ok || !sameSlotContent(p, sl) || slotExpired(p, prev, now) != slotExpired(sl, next, now) {
|
||||
return true
|
||||
}
|
||||
if len(s.volServers[sl.VolumeID]) > 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sameSlotContent compares two slot facts but for their timestamps.
|
||||
func sameSlotContent(a, b SlotFact) bool {
|
||||
a.ObservedAt, a.ExpiresAt, b.ObservedAt, b.ExpiresAt = time.Time{}, time.Time{}, time.Time{}, time.Time{}
|
||||
return reflect.DeepEqual(a, b)
|
||||
}
|
||||
|
||||
// indexServerLocked records which volumes server id reports (prev's slots
|
||||
// out, next's in). s.mu held.
|
||||
func (s *ObservationStore) indexServerLocked(id string, prev []SlotFact, next []SlotFact) {
|
||||
if s.volServers == nil {
|
||||
s.volServers = map[string]map[string]struct{}{}
|
||||
}
|
||||
for _, sl := range prev {
|
||||
if m := s.volServers[sl.VolumeID]; m != nil {
|
||||
delete(m, id)
|
||||
if len(m) == 0 {
|
||||
delete(s.volServers, sl.VolumeID)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, sl := range next {
|
||||
m := s.volServers[sl.VolumeID]
|
||||
if m == nil {
|
||||
m = map[string]struct{}{}
|
||||
s.volServers[sl.VolumeID] = m
|
||||
}
|
||||
m[id] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// nextExpiry is the earliest expiry of obs (its own, or a slot's) not yet
|
||||
// passed at now; zero when none is ahead. A fact expires once now is after
|
||||
// its expiry (observation_store.go), so an expiry equal to now is still
|
||||
// ahead.
|
||||
func nextExpiry(obs Observation, now time.Time) time.Time {
|
||||
var at time.Time
|
||||
consider := func(t time.Time) {
|
||||
if !t.IsZero() && !now.After(t) && (at.IsZero() || t.Before(at)) {
|
||||
at = t
|
||||
}
|
||||
}
|
||||
consider(obs.ExpiresAt)
|
||||
for _, sl := range obs.Slots {
|
||||
consider(sl.ExpiresAt)
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// deadlineEntry is one server's next expiry; seq tells a current entry from
|
||||
// one a later heartbeat replaced (lazy deletion).
|
||||
type deadlineEntry struct {
|
||||
at time.Time
|
||||
server string
|
||||
seq uint64
|
||||
}
|
||||
|
||||
type deadlineHeap []deadlineEntry
|
||||
|
||||
func (h deadlineHeap) Len() int { return len(h) }
|
||||
func (h deadlineHeap) Less(i, j int) bool { return h[i].at.Before(h[j].at) }
|
||||
func (h deadlineHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
func (h *deadlineHeap) Push(x any) { *h = append(*h, x.(deadlineEntry)) }
|
||||
func (h *deadlineHeap) Pop() any {
|
||||
old := *h
|
||||
e := old[len(old)-1]
|
||||
*h = old[:len(old)-1]
|
||||
return e
|
||||
}
|
||||
|
||||
// scheduleLocked records server id's next expiry after now. s.mu held.
|
||||
func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.Time) {
|
||||
if s.deadlineSeq == nil {
|
||||
s.deadlineSeq = map[string]uint64{}
|
||||
}
|
||||
s.deadlineSeq[id]++
|
||||
if at := nextExpiry(obs, now); !at.IsZero() {
|
||||
heap.Push(&s.deadlines, deadlineEntry{at: at, server: id, seq: s.deadlineSeq[id]})
|
||||
}
|
||||
}
|
||||
|
||||
// NextDeadline is the earliest time a build's input changes with no
|
||||
// heartbeat and ExpireDue has not reported yet: a server's or slot's expiry,
|
||||
// or the pending grace's end (possibly already past); zero when none is
|
||||
// left.
|
||||
func (s *ObservationStore) NextDeadline() time.Time {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for s.deadlines.Len() > 0 {
|
||||
e := s.deadlines[0]
|
||||
if e.seq == s.deadlineSeq[e.server] {
|
||||
break
|
||||
}
|
||||
heap.Pop(&s.deadlines) // replaced by a later heartbeat
|
||||
}
|
||||
var at time.Time
|
||||
if s.deadlines.Len() > 0 {
|
||||
at = s.deadlines[0].at
|
||||
}
|
||||
// The grace's end stays a deadline until ExpireDue reports it, even once
|
||||
// past: a build taken just before it, with the host's next look just
|
||||
// after it, must still be rebuilt.
|
||||
if g := s.startedAt.Add(s.config.PendingGrace); !s.graceSeen && (at.IsZero() || g.Before(at)) {
|
||||
at = g
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// ExpireDue reports whether a deadline has passed since the last call (an
|
||||
// expiry or the pending grace's end: a build's input changed), and moves
|
||||
// each such server to its next deadline.
|
||||
func (s *ObservationStore) ExpireDue() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.expireDueLocked(s.now())
|
||||
}
|
||||
|
||||
// expireDueLocked is ExpireDue with s.mu held.
|
||||
func (s *ObservationStore) expireDueLocked(now time.Time) bool {
|
||||
due := false
|
||||
for s.deadlines.Len() > 0 && now.After(s.deadlines[0].at) {
|
||||
e := heap.Pop(&s.deadlines).(deadlineEntry)
|
||||
if e.seq != s.deadlineSeq[e.server] {
|
||||
continue
|
||||
}
|
||||
due = true
|
||||
if obs, ok := s.observations[e.server]; ok {
|
||||
s.scheduleLocked(e.server, obs, now)
|
||||
}
|
||||
}
|
||||
if !s.graceSeen {
|
||||
if g := s.startedAt.Add(s.config.PendingGrace); !g.After(now) {
|
||||
s.graceSeen = true
|
||||
due = true
|
||||
}
|
||||
}
|
||||
return due
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func countingStore(t *testing.T, clk *fakeClock, window time.Duration) (*ObservationStore, *atomic.Int64) {
|
||||
t.Helper()
|
||||
s := NewObservationStore(FreshnessConfig{FreshnessWindow: window}, clk.Now)
|
||||
var wakes atomic.Int64
|
||||
s.SetOnMutation(func() { wakes.Add(1) })
|
||||
return s, &wakes
|
||||
}
|
||||
|
||||
func oneSlotObs(server string, at time.Time, slots ...SlotFact) Observation {
|
||||
return Observation{ServerID: server, ObservedAt: at, Server: ServerFact{Reachable: true, Eligible: true}, Slots: slots}
|
||||
}
|
||||
|
||||
// A heartbeat that refreshes only timestamps (every volume process sends one
|
||||
// every 2 s) wakes no rebuild; a changed slot, a new server, or a refresh of
|
||||
// a volume two servers report does. On main every heartbeat woke a full
|
||||
// rebuild.
|
||||
func TestObservationStoreTimestampOnlyRefreshWakesNothing(t *testing.T) {
|
||||
start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
clk := newFakeClock(start)
|
||||
s, wakes := countingStore(t, clk, 30*time.Second)
|
||||
const servers = 200
|
||||
for i := 0; i < servers; i++ {
|
||||
if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), start, healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if wakes.Load() != servers {
|
||||
t.Fatalf("%d wakes for %d new servers", wakes.Load(), servers)
|
||||
}
|
||||
wakes.Store(0)
|
||||
clk.Advance(2 * time.Second)
|
||||
for round := 0; round < 3; round++ {
|
||||
for i := 0; i < 100; i++ {
|
||||
if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), clk.Now(), healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
clk.Advance(2 * time.Second)
|
||||
}
|
||||
if n := wakes.Load(); n != 0 {
|
||||
t.Fatalf("300 timestamp-only heartbeats woke %d rebuilds, want 0", n)
|
||||
}
|
||||
changed := healthySlot("v007", "r1")
|
||||
changed.ReadyForPrimary = false
|
||||
if err := s.Ingest(oneSlotObs("s007", clk.Now(), changed)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := wakes.Load(); n != 1 {
|
||||
t.Fatalf("a changed slot woke %d rebuilds, want 1", n)
|
||||
}
|
||||
// A volume two servers report: a refresh of either wakes.
|
||||
if err := s.Ingest(oneSlotObs("s900", clk.Now(), healthySlot("v008", "r2"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wakes.Store(0)
|
||||
if err := s.Ingest(oneSlotObs("s008", clk.Now(), healthySlot("v008", "r1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := wakes.Load(); n != 1 {
|
||||
t.Fatalf("a refresh of a volume two servers report woke %d rebuilds, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// What changes with time wakes the host at its deadline, with no heartbeat:
|
||||
// a server whose heartbeats stop is seen expired once its freshness window
|
||||
// passes.
|
||||
func TestObservationHostRebuildsAtAnExpiryWithNoHeartbeat(t *testing.T) {
|
||||
start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
clk := newFakeClock(start)
|
||||
host := NewObservationHost(ObservationHostConfig{
|
||||
Freshness: FreshnessConfig{FreshnessWindow: 100 * time.Millisecond},
|
||||
Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}},
|
||||
Now: clk.Now,
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
host.Start(ctx)
|
||||
defer host.Stop()
|
||||
_ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1")))
|
||||
waitFor := func(what string, ok func(BuildResult) bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if b, have := host.LastBuild(); have && ok(b) {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
b, _ := host.LastBuild()
|
||||
t.Fatalf("%s: last build at %v with %d servers", what, b.BuiltAt, len(b.Snapshot.Servers))
|
||||
}
|
||||
waitFor("the heartbeat's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 1 })
|
||||
clk.Advance(time.Second) // past s1's freshness; no heartbeat follows
|
||||
waitFor("the expiry's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) })
|
||||
}
|
||||
|
||||
// normalizedBuild is a build with its stamps cleared: when it was built, the
|
||||
// store revision, and the timestamps the evidence carries.
|
||||
func normalizedBuild(b BuildResult) BuildResult {
|
||||
b.BuiltAt, b.InputRev = time.Time{}, 0
|
||||
b.Snapshot.CollectedAt, b.Snapshot.CollectedRevision = time.Time{}, 0
|
||||
vols := make([]VolumeTopologySnapshot, len(b.Snapshot.Volumes))
|
||||
for i, v := range b.Snapshot.Volumes {
|
||||
v.Slots = append([]ReplicaCandidate(nil), v.Slots...)
|
||||
for j := range v.Slots {
|
||||
v.Slots[j].ObservedAt = time.Time{}
|
||||
}
|
||||
vols[i] = v
|
||||
}
|
||||
b.Snapshot.Volumes = vols
|
||||
pend := map[string]VolumePendingStatus{}
|
||||
for k, v := range b.Report.Pending {
|
||||
v.EvaluatedAt = time.Time{}
|
||||
pend[k] = v
|
||||
}
|
||||
b.Report.Pending = pend
|
||||
uns := map[string]VolumeUnsupportedEvidence{}
|
||||
for k, v := range b.Report.Unsupported {
|
||||
v.EvaluatedAt, v.SnapshotRevision = time.Time{}, 0
|
||||
facts := make([]Observation, len(v.OffendingFacts))
|
||||
for i, o := range v.OffendingFacts {
|
||||
o.ObservedAt, o.ExpiresAt = time.Time{}, time.Time{}
|
||||
o.Slots = append([]SlotFact(nil), o.Slots...)
|
||||
for j := range o.Slots {
|
||||
o.Slots[j].ObservedAt, o.Slots[j].ExpiresAt = time.Time{}, time.Time{}
|
||||
}
|
||||
facts[i] = o
|
||||
}
|
||||
v.OffendingFacts = facts
|
||||
uns[k] = v
|
||||
}
|
||||
b.Report.Unsupported = uns
|
||||
return b
|
||||
}
|
||||
|
||||
// Whenever the store reports no change (no wake, no passed deadline), a
|
||||
// build now equals the last build, but for its stamps: random heartbeats
|
||||
// (new, changed, timestamp-only, of a shared volume), time steps past
|
||||
// freshness windows and the pending grace, and GC.
|
||||
func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) {
|
||||
topo := AcceptedTopology{Volumes: []VolumeExpected{
|
||||
{VolumeID: "va", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}},
|
||||
{VolumeID: "vb", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s2"}}},
|
||||
threeSlotVolume("vc"),
|
||||
}}
|
||||
for seed := int64(1); seed <= 300; seed++ {
|
||||
rng := rand.New(rand.NewSource(seed))
|
||||
start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
clk := newFakeClock(start)
|
||||
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second, PendingGrace: 7 * time.Second}, clk.Now)
|
||||
var woke bool
|
||||
s.SetOnMutation(func() { woke = true })
|
||||
last := BuildSnapshot(s.Snapshot(), topo, nil)
|
||||
s.ExpireDue()
|
||||
reports := map[string][]SlotFact{
|
||||
"s1": {healthySlot("va", "r1"), healthySlot("vc", "r1")},
|
||||
"s2": {healthySlot("vb", "r1"), healthySlot("vc", "r2")},
|
||||
"s3": {healthySlot("vc", "r3")},
|
||||
"s4": {healthySlot("vx", "r1")},
|
||||
}
|
||||
names := []string{"s1", "s2", "s3", "s4"}
|
||||
for step := 0; step < 300; step++ {
|
||||
woke = false
|
||||
switch rng.Intn(7) {
|
||||
case 0, 1, 2: // a heartbeat, maybe with a change
|
||||
srv := names[rng.Intn(len(names))]
|
||||
slots := append([]SlotFact(nil), reports[srv]...)
|
||||
if rng.Intn(4) == 0 {
|
||||
i := rng.Intn(len(slots))
|
||||
slots[i].ReadyForPrimary = !slots[i].ReadyForPrimary
|
||||
reports[srv] = slots
|
||||
}
|
||||
obs := oneSlotObs(srv, clk.Now(), slots...)
|
||||
if rng.Intn(8) == 0 {
|
||||
obs.Server.Eligible = false
|
||||
}
|
||||
_ = s.Ingest(obs)
|
||||
case 3: // time passes
|
||||
clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond)
|
||||
case 4: // time passes to the next deadline the host would wake at
|
||||
if at := s.NextDeadline(); !at.IsZero() {
|
||||
clk.Set(at.Add(time.Millisecond))
|
||||
}
|
||||
case 5:
|
||||
s.GC(time.Duration(rng.Intn(20)) * time.Second)
|
||||
case 6: // exactly at the next deadline, or just past it
|
||||
if at := s.NextDeadline(); !at.IsZero() {
|
||||
clk.Set(at.Add(time.Duration(rng.Intn(2))))
|
||||
}
|
||||
}
|
||||
// The host's timer: it fires at NextDeadline (a deadline NextDeadline
|
||||
// leaves out never fires).
|
||||
if at := s.NextDeadline(); !at.IsZero() && !at.After(clk.Now()) && s.ExpireDue() {
|
||||
woke = true
|
||||
}
|
||||
now := BuildSnapshot(s.Snapshot(), topo, nil)
|
||||
if woke {
|
||||
last = now
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(normalizedBuild(now), normalizedBuild(last)) {
|
||||
t.Fatalf("seed %d step %d: the store reported no change, but the build changed:\nlast %+v\nnow %+v", seed, step, normalizedBuild(last), normalizedBuild(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A published line wakes the observation build (no heartbeat carries it):
|
||||
// the publisher tells its line-change hook the volume of every publication,
|
||||
// and only of a publication.
|
||||
func TestPublisherTellsItsLineChangeHook(t *testing.T) {
|
||||
var told []string
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
pub.SetLineChangeHook(func(v string) { told = append(told, v) })
|
||||
ask := AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}
|
||||
if err := pub.apply(ask); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(told) != 1 || told[0] != "v1" {
|
||||
t.Fatalf("hook told %v after one publication, want [v1]", told)
|
||||
}
|
||||
if err := pub.apply(ask); err == nil {
|
||||
t.Fatal("a second bind was accepted")
|
||||
}
|
||||
if len(told) != 1 {
|
||||
t.Fatalf("hook told %v after a refused ask", told)
|
||||
}
|
||||
}
|
||||
|
||||
// submitHook is a sink that runs a function at each submission (the
|
||||
// submission is where a real build can cross a deadline).
|
||||
type submitHook struct {
|
||||
recordingSink
|
||||
on func(n int)
|
||||
n int
|
||||
}
|
||||
|
||||
func (s *submitHook) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
|
||||
s.n++
|
||||
if s.on != nil {
|
||||
s.on(s.n)
|
||||
}
|
||||
return s.recordingSink.SubmitObservedState(snap, report)
|
||||
}
|
||||
|
||||
// The pending grace's end is rebuilt even when a build taken just before it
|
||||
// is submitted just after it, with no heartbeat ever arriving: the deadline
|
||||
// stays until it is consumed.
|
||||
func TestObservationHostRebuildsAfterTheGraceCrossedDuringASubmission(t *testing.T) {
|
||||
start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
clk := newFakeClock(start)
|
||||
grace := 100 * time.Millisecond
|
||||
sink := &submitHook{}
|
||||
sink.on = func(n int) {
|
||||
if n == 1 {
|
||||
clk.Set(start.Add(grace + time.Millisecond)) // the first build crosses the grace's end
|
||||
}
|
||||
}
|
||||
host := NewObservationHost(ObservationHostConfig{
|
||||
Freshness: FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: grace},
|
||||
Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}},
|
||||
Sink: sink,
|
||||
Now: clk.Now,
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
host.Start(ctx)
|
||||
defer host.Stop()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if b, ok := host.LastBuild(); ok {
|
||||
if _, pending := b.Report.Pending["v1"]; !pending {
|
||||
if _, unsupported := b.Report.Unsupported["v1"]; unsupported {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
b, _ := host.LastBuild()
|
||||
t.Fatalf("v1 is still pending past the grace with no heartbeat: pending %v, unsupported %v", b.Report.Pending, b.Report.Unsupported)
|
||||
}
|
||||
@@ -16,9 +16,11 @@ import (
|
||||
// Institution logic lives here, not in cmd/sparrow. The cmd
|
||||
// layer is only allowed to construct, start, and stop the host.
|
||||
//
|
||||
// Default operation is build-on-change (sketch §11): every
|
||||
// successful Ingest fires a non-blocking signal that wakes the
|
||||
// rebuild goroutine. The goroutine drains the signal, takes one
|
||||
// Default operation is build-on-change (sketch §11): an Ingest
|
||||
// that changes what a build reads (observation_changes.go), a
|
||||
// deadline passing (an expiry, the pending grace's end) or Wake (a
|
||||
// published line) wakes the rebuild goroutine; a heartbeat that
|
||||
// refreshes only timestamps does not. The goroutine drains the signal, takes one
|
||||
// store snapshot, runs BuildSnapshot, and hands the
|
||||
// ClusterSnapshot to the controller's SubmitClusterSnapshot.
|
||||
// Pending / Unsupported volumes are surfaced via the last
|
||||
@@ -55,9 +57,14 @@ type ObservationHost struct {
|
||||
sink ControllerSink
|
||||
reader AuthorityBasisReader
|
||||
|
||||
mu sync.Mutex
|
||||
lastBuild *BuildResult
|
||||
sinkErrors []error
|
||||
mu sync.Mutex
|
||||
lastBuild *BuildResult
|
||||
// buildsStarted counts rebuilds the loop took (in the step that takes
|
||||
// their wake), buildsDone the rebuilds finished, timerAt when the armed deadline
|
||||
// timer fires (zero: none); all under mu (BuildsForTest).
|
||||
buildsStarted, buildsDone uint64
|
||||
timerAt time.Time
|
||||
sinkErrors []error
|
||||
|
||||
wake chan struct{}
|
||||
stop chan struct{}
|
||||
@@ -116,6 +123,29 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost {
|
||||
return h
|
||||
}
|
||||
|
||||
// BuildsForTest reports, under one lock, the rebuilds the loop took and
|
||||
// finished, whether a wake is buffered, and when the armed deadline timer
|
||||
// fires (zero: none), so a test can order a change after every earlier
|
||||
// build. Production code MUST NOT call this.
|
||||
func (h *ObservationHost) BuildsForTest() (started, done uint64, wakeBuffered bool, timerAt time.Time) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.buildsStarted, h.buildsDone, len(h.wake) > 0, h.timerAt
|
||||
}
|
||||
|
||||
// takeBuild counts a rebuild the loop takes, in the step that takes it.
|
||||
func (h *ObservationHost) takeBuild() {
|
||||
h.mu.Lock()
|
||||
h.buildsStarted++
|
||||
h.timerAt = time.Time{}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// Wake asks for a rebuild: a change a build reads that no heartbeat
|
||||
// carries (a published authority line, a topology change). Non-blocking;
|
||||
// wakes coalesce.
|
||||
func (h *ObservationHost) Wake() { h.signalRebuild() }
|
||||
|
||||
// Store returns the underlying store. Exposed for tests and for
|
||||
// downstream diagnosis; the host does not expect external code
|
||||
// to manipulate it beyond Ingest.
|
||||
@@ -218,17 +248,53 @@ func (h *ObservationHost) run(ctx context.Context) {
|
||||
|
||||
// First build on start — so consumers see an initial empty
|
||||
// snapshot rather than waiting for the first ingest.
|
||||
h.takeBuild()
|
||||
h.rebuildOnce()
|
||||
|
||||
for {
|
||||
// A heartbeat that refreshes only timestamps wakes nothing; what
|
||||
// changes with time (an expiry, the pending grace's end) wakes the
|
||||
// loop at its deadline.
|
||||
var deadlineC <-chan time.Time
|
||||
var timer *time.Timer
|
||||
if at := h.store.NextDeadline(); !at.IsZero() {
|
||||
d := at.Sub(h.store.now())
|
||||
if d < 10*time.Millisecond {
|
||||
d = 10 * time.Millisecond
|
||||
}
|
||||
timer = time.NewTimer(d)
|
||||
deadlineC = timer.C
|
||||
h.mu.Lock()
|
||||
h.timerAt = time.Now().Add(d)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
stopTimer := func() {
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
stopTimer()
|
||||
return
|
||||
case <-h.stop:
|
||||
stopTimer()
|
||||
return
|
||||
case <-h.wake:
|
||||
stopTimer()
|
||||
h.takeBuild()
|
||||
h.rebuildOnce()
|
||||
case <-deadlineC:
|
||||
if h.store.ExpireDue() {
|
||||
h.takeBuild()
|
||||
h.rebuildOnce()
|
||||
} else {
|
||||
h.mu.Lock()
|
||||
h.timerAt = time.Time{}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
case <-gcC:
|
||||
stopTimer()
|
||||
h.store.GC(h.gcRetain)
|
||||
// GC may have set the mutation flag; that is OK — the
|
||||
// next iteration will pick up the wake.
|
||||
@@ -248,6 +314,11 @@ func (h *ObservationHost) run(ctx context.Context) {
|
||||
// AND no report entries is a genuine no-op (e.g. start-up
|
||||
// before any ingest) and is skipped.
|
||||
func (h *ObservationHost) rebuildOnce() {
|
||||
defer func() {
|
||||
h.mu.Lock()
|
||||
h.buildsDone++
|
||||
h.mu.Unlock()
|
||||
}()
|
||||
snap := h.store.Snapshot()
|
||||
result := BuildSnapshot(snap, h.topology, h.reader)
|
||||
|
||||
|
||||
@@ -36,6 +36,15 @@ type ObservationStore struct {
|
||||
revision uint64
|
||||
onMutation func()
|
||||
|
||||
// volServers: the servers reporting a slot of each volume (a volume
|
||||
// two servers report is ordered by timestamps in a build).
|
||||
volServers map[string]map[string]struct{}
|
||||
// deadlines: each server's next expiry (lazily replaced: deadlineSeq);
|
||||
// graceSeen: the pending grace's end was reported (observation_changes.go).
|
||||
deadlines deadlineHeap
|
||||
deadlineSeq map[string]uint64
|
||||
graceSeen bool
|
||||
|
||||
// supersededCount counts slot reports that were dropped because a
|
||||
// newer ObservedAt was stored for that server/volume/replica slot.
|
||||
// Diagnostic only — PCDD-DELAYED-HB-001 evidence
|
||||
@@ -237,7 +246,9 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat
|
||||
}
|
||||
|
||||
// SetOnMutation registers a callback that fires whenever a
|
||||
// successful ingest changes store contents. The callback must
|
||||
// successful ingest changes what a snapshot build reads (not on a
|
||||
// heartbeat that refreshes only timestamps; GC removing an entry fires it
|
||||
// too). The callback must
|
||||
// NOT block; typical use is a non-blocking signal into the host's
|
||||
// rebuild goroutine.
|
||||
//
|
||||
@@ -377,9 +388,22 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro
|
||||
obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server
|
||||
}
|
||||
}
|
||||
now := s.now()
|
||||
// A deadline passed since the last build is a change too (the build a
|
||||
// heartbeat wakes then sees the expiry, as before).
|
||||
changed := s.expireDueLocked(now)
|
||||
if s.buildReadsChangedLocked(prev, hadPrev, obs, now) {
|
||||
changed = true
|
||||
}
|
||||
s.indexServerLocked(obs.ServerID, prev.Slots, obs.Slots)
|
||||
s.scheduleLocked(obs.ServerID, obs, now)
|
||||
s.observations[obs.ServerID] = obs
|
||||
s.revision++
|
||||
fn = s.onMutation
|
||||
if changed {
|
||||
// A heartbeat that refreshes only timestamps wakes no rebuild: its
|
||||
// expiry is a deadline (NextDeadline) the host wakes at.
|
||||
fn = s.onMutation
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
if fn != nil {
|
||||
@@ -561,6 +585,10 @@ func (s *ObservationStore) GC(retain time.Duration) int {
|
||||
for id, obs := range s.observations {
|
||||
if now.Sub(obs.ObservedAt) > retain {
|
||||
delete(s.observations, id)
|
||||
s.indexServerLocked(id, obs.Slots, nil)
|
||||
if s.deadlineSeq != nil {
|
||||
s.deadlineSeq[id]++ // its pending deadline is void
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,12 +64,13 @@ var headReaders = map[string]string{
|
||||
"cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)",
|
||||
"cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)",
|
||||
"core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
|
||||
"core/frontend/durable/provider_chunk.go EachSegment -> GetHead": "a remote without a segment read: ErrHeadAbsent from its GetHead, as GetHead (probe LayoutRemote)",
|
||||
"core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
|
||||
"core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)",
|
||||
"core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)",
|
||||
"core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
|
||||
"core/storage/chunk_head_belt.go readChunkHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
|
||||
"core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
|
||||
"core/storage/chunk_layer.go readAttachHead -> GetHead": "ErrHeadAbsent from the layout remote; its segment read (EachSegment) reads HEAD as GetHead does (headIdentityLocked) (probe LayoutRemote)",
|
||||
}
|
||||
|
||||
// TestHeadReaders_Enumeration lists every HEAD reader in core/ and cmd/ from
|
||||
|
||||
@@ -62,6 +62,10 @@ type CommitRequest struct {
|
||||
// (the root and every segment it names): HEAD's CurrentBytes after the
|
||||
// commit, and the named snapshot's size. nil writes neither (unknown).
|
||||
ManifestBytes *uint64
|
||||
// V11: the commit writes a v1.1 HEAD. HEAD is then version 1 whether or
|
||||
// not ManifestBytes is known (an upgraded volume's first commit by change
|
||||
// does not know it).
|
||||
V11 bool
|
||||
}
|
||||
|
||||
// CommitDelta is a commit by change (cost table K3): HEAD's current root,
|
||||
@@ -453,18 +457,19 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H
|
||||
}
|
||||
next, changed, err := h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State)
|
||||
if err == nil && changed {
|
||||
next = next.withManifestBytes(req.Snapshot, req.ManifestBytes)
|
||||
next = next.withManifestBytes(req.Snapshot, req.ManifestBytes, req.V11)
|
||||
}
|
||||
return next, changed, err
|
||||
}
|
||||
|
||||
// withManifestBytes records the committed root's manifest size: HEAD's
|
||||
// CurrentBytes (nil: unknown, also when an earlier commit knew it), and the
|
||||
// size of the snapshot this commit named, written once.
|
||||
func (h Head) withManifestBytes(snapshot string, size *uint64) Head {
|
||||
// size of the snapshot this commit named, written once. A v1.1 commit (v11)
|
||||
// writes HEAD version 1, the size known or not; a size is a v1.1 field.
|
||||
func (h Head) withManifestBytes(snapshot string, size *uint64, v11 bool) Head {
|
||||
h = h.clone() // the snapshot map is shared with the HEAD it came from
|
||||
if size != nil && h.Version < HeadVersion1 {
|
||||
h.Version = HeadVersion1 // the sizes are v1.1 fields
|
||||
if (v11 || size != nil) && h.Version < HeadVersion1 {
|
||||
h.Version = HeadVersion1
|
||||
}
|
||||
h.CurrentBytes = cloneSize(size)
|
||||
if s, ok := h.Snapshots[snapshot]; snapshot != "" && ok && s.ManifestBytes == nil {
|
||||
|
||||
@@ -249,6 +249,20 @@ func checkExt(version int, ext json.RawMessage) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// carriesManifestSizes reports whether h carries a v1.1 manifest size: its
|
||||
// CurrentBytes or any snapshot's ManifestBytes.
|
||||
func (h Head) carriesManifestSizes() bool {
|
||||
if h.CurrentBytes != nil {
|
||||
return true
|
||||
}
|
||||
for _, s := range h.Snapshots {
|
||||
if s.ManifestBytes != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ErrNoNextPosition: a HEAD position with no room for a next LSN. No
|
||||
// commit produces it (Commit refuses); a HEAD that already carries one (an
|
||||
// older or broken writer) is still read, written by every other
|
||||
@@ -262,6 +276,9 @@ func (h Head) check() error {
|
||||
if err := checkExt(h.Version, h.Ext); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Version == 0 && h.carriesManifestSizes() {
|
||||
return fmt.Errorf("%w: a v1.0 HEAD carries v1.1 manifest sizes", ErrMalformed)
|
||||
}
|
||||
switch h.State {
|
||||
case StateLive, StateDetached, StateDeleting, StateDeleted:
|
||||
default:
|
||||
|
||||
@@ -102,19 +102,38 @@ func TestCommitRecordsTheManifestSize(t *testing.T) {
|
||||
if err != nil || !changed {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sized := next.withManifestBytes("snap", u64(777))
|
||||
sized := next.withManifestBytes("snap", u64(777), true)
|
||||
if sized.Version != HeadVersion1 || sized.CurrentBytes == nil || *sized.CurrentBytes != 777 {
|
||||
t.Fatalf("sized commit: %+v", sized)
|
||||
}
|
||||
if s := sized.Snapshots["snap"]; s.ManifestBytes == nil || *s.ManifestBytes != 777 {
|
||||
t.Fatalf("the named snapshot's size: %+v", s)
|
||||
}
|
||||
unsized := next.withManifestBytes("snap", nil)
|
||||
unsized := next.withManifestBytes("snap", nil, false)
|
||||
if unsized.Version != 0 || unsized.CurrentBytes != nil || unsized.Snapshots["snap"].ManifestBytes != nil {
|
||||
t.Fatalf("a commit that does not know the size: %+v", unsized)
|
||||
t.Fatalf("a v1.0 commit, which writes no size: %+v", unsized)
|
||||
}
|
||||
// A v1.1 commit that does not know the size (an upgraded volume's first
|
||||
// commit by change) is still version 1, with the size unknown.
|
||||
unknown := next.withManifestBytes("snap", nil, true)
|
||||
if unknown.Version != HeadVersion1 || unknown.CurrentBytes != nil || unknown.Snapshots["snap"].ManifestBytes != nil {
|
||||
t.Fatalf("a v1.1 commit without a size: %+v", unknown)
|
||||
}
|
||||
// A v1.0 HEAD never carries a v1.1 size: Encode refuses one.
|
||||
bad := unsized.clone()
|
||||
bad.CurrentBytes = u64(5)
|
||||
if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) {
|
||||
t.Fatalf("a version-0 HEAD with a manifest size encoded: %v", err)
|
||||
}
|
||||
badSnap := unsized.clone()
|
||||
sn := badSnap.Snapshots["snap"]
|
||||
sn.ManifestBytes = u64(5)
|
||||
badSnap.Snapshots["snap"] = sn
|
||||
if _, err := badSnap.Encode(); !errors.Is(err, ErrMalformed) {
|
||||
t.Fatalf("a version-0 HEAD with a snapshot size encoded: %v", err)
|
||||
}
|
||||
// Written once: a later size never rewrites a snapshot's.
|
||||
again := sized.withManifestBytes("snap", u64(999))
|
||||
again := sized.withManifestBytes("snap", u64(999), true)
|
||||
if s := again.Snapshots["snap"]; *s.ManifestBytes != 777 {
|
||||
t.Fatalf("a snapshot's size was rewritten: %d", *s.ManifestBytes)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// EachSegment is GetHead one segment at a time: one call per segment HEAD's
|
||||
// root names, each with its shard's range and exactly the references GetHead
|
||||
// lists in that range, and HEAD's identity with no chunk listed. It reads the
|
||||
// root once and each segment once, and holds one segment at a time.
|
||||
func TestEachSegmentIsGetHeadOneSegmentAtATime(t *testing.T) {
|
||||
ctx, _, r, _ := threeShardVolume(t)
|
||||
full, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type call struct{ first, end uint64 }
|
||||
var calls []call
|
||||
got := map[uint64]storage.ChunkRef{}
|
||||
octx, count := storage.ObserveCutWork(ctx)
|
||||
id, err := r.EachSegment(octx, func(first, end uint64, refs map[uint64]storage.ChunkRef) error {
|
||||
calls = append(calls, call{first, end})
|
||||
for i, ref := range refs {
|
||||
if i < first || i >= end {
|
||||
t.Errorf("chunk %d delivered outside its range [%d, %d)", i, first, end)
|
||||
}
|
||||
got[i] = ref
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []call{{0, layout.ShardSize}, {layout.ShardSize, 2 * layout.ShardSize}, {2 * layout.ShardSize, 3 * layout.ShardSize}}
|
||||
if !reflect.DeepEqual(calls, want) {
|
||||
t.Fatalf("calls %v, want %v", calls, want)
|
||||
}
|
||||
if !reflect.DeepEqual(got, full.Chunks) {
|
||||
t.Fatalf("EachSegment's references differ from GetHead's: %d vs %d", len(got), len(full.Chunks))
|
||||
}
|
||||
if id.Chunks != nil || id.Gen != full.Gen || id.Epoch != full.Epoch || id.Holder != full.Holder || id.RemoteLSN != full.RemoteLSN {
|
||||
t.Fatalf("identity %+v, GetHead %+v", id, full)
|
||||
}
|
||||
if roots, segs := count(storage.CountRootReads), count(storage.CountSegmentReads); roots != 1 || segs != 3 {
|
||||
t.Fatalf("%d root reads, %d segment reads; want 1 and 3", roots, segs)
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func TestTheConfirmationAfterAHeadWriteReadsNoManifest(t *testing.T) {
|
||||
// already holds, it reads HEAD only and keeps its chunk list: no root and no
|
||||
// segment.
|
||||
func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) {
|
||||
_, _, l, counting, reads := manifestReads(t)
|
||||
_, remote, l, counting, reads := manifestReads(t)
|
||||
if _, err := l.Cut(context.Background()); err != nil { // publish the written chunks
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -104,7 +104,19 @@ func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) {
|
||||
if n := reads.Load(); n != 0 {
|
||||
t.Fatalf("a no-op cut over an unchanged HEAD read %d roots or segments; want 0", n)
|
||||
}
|
||||
if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks {
|
||||
if res.Head.Chunks == nil {
|
||||
// The v1.1 format: a cut's result reports HEAD's identity only. HEAD
|
||||
// itself, read once the cut's reads are counted, still names every
|
||||
// chunk at the result's generation.
|
||||
counting.Store(false)
|
||||
h, err := remote.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Gen != res.Head.Gen || len(h.Chunks) != lrBlocks/lrChunkBlocks {
|
||||
t.Fatalf("after the no-op cut HEAD is gen %d with %d chunks; want the result's gen %d with the %d it already held", h.Gen, len(h.Chunks), res.Head.Gen, lrBlocks/lrChunkBlocks)
|
||||
}
|
||||
} else if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks {
|
||||
t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +96,10 @@ func TestCommitsKeepTheManifestSizeExact(t *testing.T) {
|
||||
}
|
||||
|
||||
// A HEAD with no recorded size (a v1.0 HEAD) stays unknown through commits
|
||||
// by change: they cannot know the objects they did not replace.
|
||||
// by change: they cannot know the objects they did not replace. The first
|
||||
// v1.1 commit still writes HEAD at version 1: the version follows the
|
||||
// format, never whether a size is known (an upgraded volume's first cut is a
|
||||
// commit by change, and a v1.0 binary must refuse what it wrote).
|
||||
func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) {
|
||||
withManifestSizes(t, false)
|
||||
ctx, _, r, h1 := threeShardVolume(t) // a v1.0 HEAD: no size
|
||||
@@ -118,6 +121,9 @@ func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) {
|
||||
if h.CurrentBytes != nil {
|
||||
t.Fatalf("a commit by change over an unknown size wrote %d", *h.CurrentBytes)
|
||||
}
|
||||
if h.Version != layout.HeadVersion1 {
|
||||
t.Fatalf("the first v1.1 commit (a commit by change, size unknown) wrote HEAD version %d, want %d", h.Version, layout.HeadVersion1)
|
||||
}
|
||||
}
|
||||
|
||||
// A commit by change that touches a shard but leaves its segment unchanged
|
||||
|
||||
@@ -412,30 +412,97 @@ func (l *LayoutRemote) headIdentityLocked(ctx context.Context) (layout.Head, sto
|
||||
// no bound on the read as a whole (the segment count grows with the volume).
|
||||
func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[uint64]layout.Ref, error) {
|
||||
defer storage.MeasureCutWork(ctx, storage.CutManifestRead)()
|
||||
if af, ok := storage.AttachFetchFrom(ctx); ok {
|
||||
m, err := boundedManifest(ctx, l.r, rn, af)
|
||||
if err != nil {
|
||||
return nil, layoutRemoteErr(err)
|
||||
m := map[uint64]layout.Ref{}
|
||||
err := walkSegments(ctx, l.r, rn, func(_ uint64, seg map[uint64]layout.Ref) error {
|
||||
for idx, ref := range seg {
|
||||
m[idx] = ref
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
img, err := l.r.Open(ctx, rn)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, layoutRemoteErr(err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// walkSegments reads root rn and then each segment it names, one at a time,
|
||||
// handing each to fn (its shard and its references by chunk index): the
|
||||
// root and every segment, each read counted; within an attach each fetch is
|
||||
// bounded by the attach's fetch bound and the completed references are
|
||||
// reported. Only one segment is held at a time.
|
||||
func walkSegments(ctx context.Context, r *layout.Reader, rn layout.RootName, fn func(shard uint64, seg map[uint64]layout.Ref) error) error {
|
||||
af, attach := storage.AttachFetchFrom(ctx)
|
||||
fetchCtx := func() (context.Context, context.CancelFunc) {
|
||||
if attach && af.Bound > 0 {
|
||||
return context.WithTimeout(ctx, af.Bound)
|
||||
}
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
c, cancel := fetchCtx()
|
||||
img, err := r.Open(c, rn)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
storage.CountCutWork(ctx, storage.CountRootReads, 1)
|
||||
m := map[uint64]layout.Ref{}
|
||||
for _, sh := range img.Shards() {
|
||||
seg, _, err := img.Segment(ctx, sh)
|
||||
c, cancel := fetchCtx()
|
||||
seg, _, err := img.Segment(c, sh)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, layoutRemoteErr(err)
|
||||
return err
|
||||
}
|
||||
storage.CountCutWork(ctx, storage.CountSegmentReads, 1)
|
||||
for idx, ref := range seg.Chunks {
|
||||
m[idx] = ref
|
||||
if err := fn(sh, seg.Chunks); err != nil {
|
||||
return err
|
||||
}
|
||||
if attach && af.Done != nil {
|
||||
af.Done(uint64(len(seg.Chunks)))
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// boundedManifest is the whole manifest of rn read under an attach's fetch
|
||||
// bound af (walkSegments within that attach).
|
||||
func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, af storage.AttachFetch) (map[uint64]layout.Ref, error) {
|
||||
m := map[uint64]layout.Ref{}
|
||||
err := walkSegments(storage.WithAttachFetch(ctx, af), r, rn, func(_ uint64, seg map[uint64]layout.Ref) error {
|
||||
for idx, ref := range seg {
|
||||
m[idx] = ref
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return m, err
|
||||
}
|
||||
|
||||
// The layer's v1.1 attach reads HEAD through it segment by segment.
|
||||
var _ storage.ChunkSegmentReader = (*LayoutRemote)(nil)
|
||||
|
||||
// EachSegment is GetHead one segment at a time (storage.ChunkSegmentReader):
|
||||
// HEAD's identity as GetHead returns it (no chunk listed), and fn called for
|
||||
// each segment HEAD's root names with its chunk range [first, end) (a
|
||||
// shard's range: the caller clamps it to its volume) and its references.
|
||||
// Only one segment is held at a time. A HEAD with no image calls fn never.
|
||||
func (l *LayoutRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]storage.ChunkRef) error) (storage.ChunkHead, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
h, out, err := l.headIdentityLocked(ctx)
|
||||
out.Chunks = nil
|
||||
if err != nil || h.Current == nil {
|
||||
return out, err
|
||||
}
|
||||
err = walkSegments(ctx, l.r, *h.Current, func(shard uint64, seg map[uint64]layout.Ref) error {
|
||||
refs := make(map[uint64]storage.ChunkRef, len(seg))
|
||||
for idx, ref := range seg {
|
||||
refs[idx] = storage.ChunkRef{Key: LayoutKey(ref), SHA256: ref.Chunk.Hash, Encoding: "full"}
|
||||
}
|
||||
return fn(shard*layout.ShardSize, (shard+1)*layout.ShardSize, refs)
|
||||
})
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, layoutRemoteErr(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// attachFetchBound bounds one object call of an attach's manifest read by
|
||||
@@ -447,43 +514,6 @@ func attachFetchBound(ctx context.Context) (context.Context, context.CancelFunc)
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
|
||||
// boundedManifest reads root rn's chunk map one fetch at a time: the root,
|
||||
// then each segment, every fetch under af.Bound on its own, reporting each
|
||||
// completed segment's entries to af.Done. A fetch that cannot finish within
|
||||
// its bound fails the read (never a partial map).
|
||||
func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, af storage.AttachFetch) (map[uint64]layout.Ref, error) {
|
||||
fetchCtx := func() (context.Context, context.CancelFunc) {
|
||||
if af.Bound > 0 {
|
||||
return context.WithTimeout(ctx, af.Bound)
|
||||
}
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
c, cancel := fetchCtx()
|
||||
img, err := r.Open(c, rn)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage.CountCutWork(ctx, storage.CountRootReads, 1)
|
||||
m := map[uint64]layout.Ref{}
|
||||
for _, sh := range img.Shards() {
|
||||
c, cancel := fetchCtx()
|
||||
seg, _, err := img.Segment(c, sh)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage.CountCutWork(ctx, storage.CountSegmentReads, 1)
|
||||
for idx, ref := range seg.Chunks {
|
||||
m[idx] = ref
|
||||
}
|
||||
if af.Done != nil {
|
||||
af.Done(uint64(len(seg.Chunks)))
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// CASHead commits next as this cut's session: the root of next's chunk
|
||||
// map, position next.RemoteLSN, detached when next is, and the pending
|
||||
// snapshot name. It uses the engine view from before this session's Begin.
|
||||
@@ -535,7 +565,7 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage
|
||||
return layout.Head{}, layout.CommitRequest{}, false, err
|
||||
}
|
||||
}
|
||||
req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive}
|
||||
req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive, V11: manifestSizesV11()}
|
||||
if delta {
|
||||
plan, err := layout.PlanCommit(l.vol.Name, layout.CommitRequest{Delta: &d}, true)
|
||||
if err != nil {
|
||||
@@ -1085,7 +1115,7 @@ func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta}
|
||||
req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta, V11: manifestSizesV11()}
|
||||
if manifestSizesV11() {
|
||||
req.ManifestBytes = &size
|
||||
}
|
||||
|
||||
@@ -111,8 +111,9 @@ func TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces(t *testing
|
||||
b, ok := r.(storage.ChunkHeadStepBounder)
|
||||
return ok && b.BoundsHeadStep()
|
||||
},
|
||||
"ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok },
|
||||
"ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok },
|
||||
"ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok },
|
||||
"ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok },
|
||||
"ChunkSegmentReader": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkSegmentReader); return ok },
|
||||
}
|
||||
for name, has := range checks {
|
||||
if has(lr) && !has(wrapped) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -727,6 +728,28 @@ func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, erro
|
||||
return r.ChunkRemote.GetHead(c)
|
||||
}
|
||||
|
||||
// EachSegment forwards HEAD's read one segment at a time
|
||||
// (storage.ChunkSegmentReader) with GetHead's binding. A remote without it
|
||||
// is read whole and handed over as one segment.
|
||||
func (r *closeBoundRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]storage.ChunkRef) error) (storage.ChunkHead, error) {
|
||||
c, end := r.bindManifest(ctx)
|
||||
defer end()
|
||||
if sr, ok := r.ChunkRemote.(storage.ChunkSegmentReader); ok {
|
||||
return sr.EachSegment(c, fn)
|
||||
}
|
||||
h, err := r.ChunkRemote.GetHead(c)
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
if len(h.Chunks) > 0 {
|
||||
if err := fn(0, math.MaxUint64, h.Chunks); err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
}
|
||||
h.Chunks = nil
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
|
||||
c, end := r.bindManifest(ctx)
|
||||
defer end()
|
||||
|
||||
@@ -309,6 +309,9 @@ func New(cfg Config) (*Host, error) {
|
||||
Sink: sink,
|
||||
Reader: boot.Publisher,
|
||||
})
|
||||
// A published line changes what the observation build reads, and no
|
||||
// heartbeat carries it: it wakes the build.
|
||||
boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() })
|
||||
// An ask built outside the controller (a heal, a planned or workspace
|
||||
// move, an operator's request) is issued for the process its target
|
||||
// reports now.
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
// A published line wakes the observation build, through the master's
|
||||
// wiring of the publisher's line-change hook. The publication is the
|
||||
// product tick's bind of a created and placed volume, run by the test (the
|
||||
// master runs no tick by itself), and the order leaves nothing else to wake
|
||||
// the build:
|
||||
// - the master starts; its initial build (#1) and the 1 ms grace's
|
||||
// rebuild (#2) finish; the volume is created and placed and its holder's
|
||||
// heartbeat ingested; the observation host settles (every build taken
|
||||
// has finished, no wake is buffered, no deadline is due within the test:
|
||||
// a one-hour freshness window, no GC tick), all read under its lock: N
|
||||
// builds done;
|
||||
// - the test runs the product tick, which binds the volume;
|
||||
// - a build N+1 must follow: nothing but the hook can take it.
|
||||
func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the lifecycle stores need directory fsync")
|
||||
}
|
||||
h, err := New(Config{
|
||||
Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(),
|
||||
WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume,
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{}, nil
|
||||
},
|
||||
Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() { closeTestMaster(t, h) })
|
||||
c, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// settle waits, under the host's lock, until every build taken has
|
||||
// finished, no wake is buffered and no deadline timer fires within a
|
||||
// minute, with at least atLeast builds done; it returns the builds done.
|
||||
settle := func(what string, atLeast uint64) uint64 {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
started, done, buffered, timerAt := h.obs.BuildsForTest()
|
||||
if started == done && done >= atLeast && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) {
|
||||
return done
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s: the observation host did not settle", what)
|
||||
return 0
|
||||
}
|
||||
settle("startup", 2)
|
||||
reviewCreate(t, c, ctx, "v1")
|
||||
if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v1", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reviewHeartbeat(t, c, ctx, "v1", "node-a", "127.0.0.1:10000", "127.0.0.1:10001")
|
||||
n := settle("after the heartbeat", 3)
|
||||
if _, ok := h.Publisher().VolumeAuthorityLine("v1"); ok {
|
||||
t.Fatal("v1 was bound before the product tick: the publication under test is not the test's")
|
||||
}
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if line := waitAuthorityLine(t, h.Publisher(), "v1"); line.Epoch != 1 {
|
||||
t.Fatalf("the product tick bound %+v", line)
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, done, _, _ := h.obs.BuildsForTest(); done > n {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("no observation build followed the publication (still %d builds): the line-change hook did not wake it", n)
|
||||
}
|
||||
@@ -56,9 +56,13 @@ func TestAttachReportsItsVolumeSizedLocalWork(t *testing.T) {
|
||||
// On the v1.1 format the presence save feeds the store's upgrade,
|
||||
// then the record's pages (one entry per chunk of the volume) are
|
||||
// written by the upgrade and judged at the open.
|
||||
// The ref table holds the volume's chunks only: this HEAD names more
|
||||
// than the store's, which the absent marking and the presence save
|
||||
// then count per volume chunk.
|
||||
want := uint64(4 * n)
|
||||
if chunkV11Format {
|
||||
want = 4*n + 2*uint64(s.NumBlocks())
|
||||
vol := uint64(s.NumBlocks())
|
||||
want = n + 3*min(n, vol) + 2*vol
|
||||
}
|
||||
if c.total != want {
|
||||
t.Fatalf("reported %d entries, want %d (the HEAD copy, the absent marking, then the presence save's keys and lines, or the record's pages written and judged)", c.total, want)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// segmentRemote reads HEAD one segment at a time (ChunkSegmentReader), in
|
||||
// segments of seg chunks, counting the segments it hands out and every
|
||||
// whole read (GetHead) made through it.
|
||||
type segmentRemote struct {
|
||||
*fakeChunkRemote
|
||||
seg uint64
|
||||
segments, wholeReads int
|
||||
}
|
||||
|
||||
func (r *segmentRemote) GetHead(ctx context.Context) (chunkHead, error) {
|
||||
r.wholeReads++
|
||||
return r.fakeChunkRemote.GetHead(ctx)
|
||||
}
|
||||
|
||||
func (r *segmentRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error) {
|
||||
h, err := r.fakeChunkRemote.GetHead(ctx) // the remote's own read: the layer sees segments
|
||||
if err != nil {
|
||||
return chunkHead{}, err
|
||||
}
|
||||
shards := map[uint64]map[uint64]chunkRef{}
|
||||
for idx, ref := range h.Chunks {
|
||||
sh := idx / r.seg
|
||||
if shards[sh] == nil {
|
||||
shards[sh] = map[uint64]chunkRef{}
|
||||
}
|
||||
shards[sh][idx] = ref
|
||||
}
|
||||
order := make([]uint64, 0, len(shards))
|
||||
for sh := range shards {
|
||||
order = append(order, sh)
|
||||
}
|
||||
sort.Slice(order, func(i, j int) bool { return order[i] < order[j] })
|
||||
for _, sh := range order {
|
||||
r.segments++
|
||||
if err := fn(sh*r.seg, (sh+1)*r.seg, shards[sh]); err != nil {
|
||||
return chunkHead{}, err
|
||||
}
|
||||
}
|
||||
h.Chunks = nil
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// On the v1.1 format a layer attaches to a remote that reads HEAD by segment
|
||||
// one segment at a time: no whole read of HEAD, no flat map kept, and the
|
||||
// ref table names exactly HEAD's chunks. A segment naming a chunk beyond
|
||||
// the volume is refused (a malformed HEAD), as the whole read's install
|
||||
// cannot tell.
|
||||
func TestV11AttachReadsHeadOneSegmentAtATime(t *testing.T) {
|
||||
withV11Format(t)
|
||||
head := func(extra bool) chunkHead {
|
||||
h := chunkHead{Gen: 3, Epoch: 1, Holder: "old", RemoteLSN: 0, Chunks: map[uint64]chunkRef{}}
|
||||
for i := uint64(0); i < 16; i += 2 { // every other chunk of the 16-chunk store
|
||||
h.Chunks[i] = chunkRef{Key: fmt.Sprintf("c%d", i), Encoding: "full"}
|
||||
}
|
||||
if extra {
|
||||
h.Chunks[17] = chunkRef{Key: "beyond", Encoding: "full"}
|
||||
}
|
||||
return h
|
||||
}
|
||||
attach := func(t *testing.T, h chunkHead) (*segmentRemote, *chunkLayerImpl, error) {
|
||||
s, _ := v11Store(t)
|
||||
f := newFakeChunkRemote()
|
||||
f.head = h
|
||||
r := &segmentRemote{fakeChunkRemote: f, seg: 4}
|
||||
cfg := ctConfig(1)
|
||||
cfg.Bitmap, cfg.Epoch, cfg.FreshFromHead = nil, 2, true
|
||||
l, err := attachChunkLayer(s, r, cfg)
|
||||
if err != nil {
|
||||
return r, nil, err
|
||||
}
|
||||
t.Cleanup(func() { _ = l.Close() })
|
||||
return r, l.(*chunkLayerImpl), nil
|
||||
}
|
||||
r, l, err := attach(t, head(false))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
flat, whole := l.head.Chunks, l.wholeHeadLocked()
|
||||
l.stMu.Unlock()
|
||||
if r.wholeReads != 0 || r.segments != 4 {
|
||||
t.Fatalf("attach read HEAD whole %d times and %d segments, want none and 4", r.wholeReads, r.segments)
|
||||
}
|
||||
if flat != nil {
|
||||
t.Fatalf("the attached layer keeps a flat map of %d chunks", len(flat))
|
||||
}
|
||||
if want := head(false).Chunks; !reflect.DeepEqual(whole.Chunks, want) {
|
||||
t.Fatalf("the ref table names %d chunks, HEAD %d", len(whole.Chunks), len(want))
|
||||
}
|
||||
if _, _, err := attach(t, head(true)); err == nil {
|
||||
t.Fatal("a segment naming a chunk beyond the volume was attached")
|
||||
}
|
||||
}
|
||||
@@ -505,7 +505,7 @@ func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte)
|
||||
idx := l.chunkOf(lba)
|
||||
l.stMu.Lock()
|
||||
absent := l.absent[idx] && !l.localBlocks[lba]
|
||||
_, inHead := l.head.Chunks[idx]
|
||||
_, inHead := l.headRef(idx)
|
||||
l.stMu.Unlock()
|
||||
if absent && inHead {
|
||||
return nil, false, nil
|
||||
@@ -536,7 +536,7 @@ func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkR
|
||||
var gen, version uint64
|
||||
if fill {
|
||||
l.stMu.Lock()
|
||||
fill = l.absent[idx] && l.head.Chunks[idx] == ref
|
||||
fill = l.absent[idx] && l.headChunk(idx) == ref
|
||||
gen, version = l.absentGen[idx], l.chunkVersion(idx)
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
|
||||
@@ -356,9 +356,10 @@ func TestCutCOWV3_RecentChunkUploadsFirst(t *testing.T) {
|
||||
if len(puts) != len(want) {
|
||||
t.Fatalf("PUTs=%v, want three uploads", puts)
|
||||
}
|
||||
installed := f.headOf(t, result.Head)
|
||||
for i, idx := range want {
|
||||
if puts[i] != result.Head.Chunks[idx].Key {
|
||||
t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, result.Head.Chunks[idx].Key)
|
||||
if puts[i] != installed.Chunks[idx].Key {
|
||||
t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, installed.Chunks[idx].Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y {
|
||||
if f.headOf(t, first.Head).Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y {
|
||||
t.Fatalf("first cut: %+v, want position %d", first.Head, y)
|
||||
}
|
||||
_, err = s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44))
|
||||
@@ -100,7 +100,8 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1] == first.Head.Chunks[1] {
|
||||
h1, h2 := f.headOf(t, first.Head), f.headOf(t, second.Head)
|
||||
if h2.Chunks[0] != h1.Chunks[0] || h2.Chunks[1] == h1.Chunks[1] {
|
||||
t.Fatal("rewrite changed a cold chunk or did not publish the changed one")
|
||||
}
|
||||
for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// On the v1.1 format a cut's result reports HEAD's identity only (its Chunks
|
||||
// nil): no production code may read a cut or detach result's chunks. Every
|
||||
// non-test Go file of the module is scanned for a read of .Head.Chunks or
|
||||
// .Head.Segments; a reader added later fails here. The control: the pattern
|
||||
// finds such a read.
|
||||
func TestNoProductionReaderOfACutResultsChunks(t *testing.T) {
|
||||
re := regexp.MustCompile(`\.Head\.(Chunks|Segments)\b`)
|
||||
if !re.MatchString("ref := res.Head.Chunks[3]") || re.MatchString("gen := res.Head.Gen") {
|
||||
t.Fatal("control: the scan's pattern does not tell a chunk read from an identity read")
|
||||
}
|
||||
root := filepath.Join("..", "..")
|
||||
if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil {
|
||||
t.Fatalf("module root not found from the package: %v", err)
|
||||
}
|
||||
var found []string
|
||||
files := 0
|
||||
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
switch d.Name() {
|
||||
case ".git", "vendor", "testdata", "node_modules":
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files++
|
||||
for i, line := range strings.Split(string(b), "\n") {
|
||||
if re.MatchString(line) {
|
||||
found = append(found, fmt.Sprintf("%s:%d", p, i+1))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if files < 100 {
|
||||
t.Fatalf("scanned only %d Go files: the walk did not cover the module", files)
|
||||
}
|
||||
if len(found) > 0 {
|
||||
t.Fatalf("production code reads a cut result's chunks, which the v1.1 format does not report: %v", found)
|
||||
}
|
||||
}
|
||||
@@ -389,6 +389,9 @@ func (f *fakeChunkRemote) imageOf(t *testing.T, h chunkHead) []byte {
|
||||
t.Helper()
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if h.Chunks == nil && h.Gen != 0 {
|
||||
h = f.installedLocked(t, h)
|
||||
}
|
||||
img := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
for idx, ref := range h.Chunks {
|
||||
b, ok := f.objs[ref.Key]
|
||||
@@ -1178,3 +1181,30 @@ func deltaMatchesNext(h chunkHead, next chunkHead, changes map[uint64]*chunkRef)
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// headOf is h whole: h itself, or the HEAD this remote installed with h's
|
||||
// identity when h reports identity only (a v1.1 cut's result).
|
||||
func (f *fakeChunkRemote) headOf(t *testing.T, h chunkHead) chunkHead {
|
||||
t.Helper()
|
||||
if h.Chunks != nil || h.Gen == 0 {
|
||||
return h
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.installedLocked(t, h)
|
||||
}
|
||||
|
||||
// installedLocked is the HEAD this remote installed with id's generation,
|
||||
// epoch and holder: what a cut's result names when it reports identity only
|
||||
// (the v1.1 format), read from the remote, the source of truth. Caller
|
||||
// holds mu.
|
||||
func (f *fakeChunkRemote) installedLocked(t *testing.T, id chunkHead) chunkHead {
|
||||
t.Helper()
|
||||
for i := len(f.heads) - 1; i >= 0; i-- {
|
||||
if h := f.heads[i]; h.Gen == id.Gen && h.Epoch == id.Epoch && h.Holder == id.Holder {
|
||||
return h
|
||||
}
|
||||
}
|
||||
t.Fatalf("no installed HEAD has gen %d epoch %d holder %q", id.Gen, id.Epoch, id.Holder)
|
||||
return chunkHead{}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import "log"
|
||||
// THEN the marking is made durable, THEN the volume serves. A crash between
|
||||
// the first two leaves no marker and every chunk UNKNOWN (one scan); a
|
||||
// failed map publication leaves them UNKNOWN on disk (conservative).
|
||||
func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 {
|
||||
func (l *chunkLayerImpl) freshKnownZeroCandidates() map[uint64]uint64 {
|
||||
s := l.s
|
||||
if s.v3 == nil || s.v3.ownedMap == nil {
|
||||
return nil
|
||||
@@ -32,7 +32,7 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin
|
||||
out := map[uint64]uint64{}
|
||||
for idx := uint64(0); idx < l.numChunks && idx < uint64(s.v3.mapEntries.len()); idx++ {
|
||||
l.attachProgress.add(1) // attach only (its one caller): every inspected entry, candidate or not
|
||||
if _, named := head.Chunks[idx]; named {
|
||||
if _, named := l.headRef(idx); named {
|
||||
continue
|
||||
}
|
||||
if e := s.v3.mapEntries.at(int(idx)); e.LSN != 0 || !e.Unknown {
|
||||
|
||||
@@ -229,7 +229,7 @@ func TestACleanFillRecordEndsWithItsHeadRef(t *testing.T) {
|
||||
ref.Key += "-replaced"
|
||||
ref.SHA256[0] ^= 0xFF
|
||||
h.Chunks[idx] = ref
|
||||
l.head = h
|
||||
l.setHeadLocked(h)
|
||||
l.stMu.Unlock()
|
||||
if !l.captureCandidates()[idx] {
|
||||
t.Fatal("a chunk whose HEAD ref changed after its fill is not a candidate")
|
||||
|
||||
@@ -196,7 +196,7 @@ func (l *chunkLayerImpl) fencePublication(cur chunkHead) {
|
||||
if cur.Gen != 0 {
|
||||
// Preserve the existing hydration identity invalidation. This is not
|
||||
// settlement of our cut: remoteLSN and captured-map dirt stay unchanged.
|
||||
l.head = copyHead(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
log.Printf("ALARM: chunk publisher fenced: local epoch=%d holder=%q, observed gen=%d epoch=%d holder=%q; keeping local data and intents", l.cfg.Epoch, l.cfg.Holder, cur.Gen, cur.Epoch, cur.Holder)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package storage
|
||||
|
||||
// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as
|
||||
// a HEAD install would: in the ref table on the v1.1 format, else the map.
|
||||
func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) {
|
||||
if l.refs != nil {
|
||||
_ = l.refs.Set(idx, ref)
|
||||
return
|
||||
}
|
||||
l.head.Chunks[idx] = ref
|
||||
}
|
||||
@@ -143,7 +143,7 @@ func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64)
|
||||
return quit(errChunkLayerClosed)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref
|
||||
changed := l.absentGen[f.idx] != f.gen || l.headChunk(f.idx) != f.ref
|
||||
ferr := f.err
|
||||
l.stMu.Unlock()
|
||||
switch {
|
||||
@@ -175,7 +175,7 @@ func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydr
|
||||
release()
|
||||
return nil, errChunkLayerClosed
|
||||
}
|
||||
ref, named := l.head.Chunks[idx]
|
||||
ref, named := l.headRef(idx)
|
||||
if !l.absent[idx] || l.localBlocks[lba] || !named {
|
||||
release()
|
||||
return nil, nil
|
||||
@@ -238,7 +238,7 @@ func (l *chunkLayerImpl) absentHydratable() int {
|
||||
// hydratableBlockLocked returns a block of chunk idx that is not written
|
||||
// locally, if HEAD names the chunk. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) {
|
||||
if _, named := l.head.Chunks[idx]; !named {
|
||||
if _, named := l.headRef(idx); !named {
|
||||
return 0, false
|
||||
}
|
||||
first := idx * l.chunkBlocks
|
||||
|
||||
@@ -63,7 +63,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b
|
||||
l.stMu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
ref, ok := l.head.Chunks[idx]
|
||||
ref, ok := l.headRef(idx)
|
||||
if !ok {
|
||||
l.stMu.Unlock()
|
||||
return make([]byte, l.blockSize), nil
|
||||
@@ -114,7 +114,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b
|
||||
l.stMu.Lock()
|
||||
f.waiters--
|
||||
closed := l.closed
|
||||
changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref
|
||||
changed := l.absentGen[idx] != f.gen || l.headChunk(idx) != f.ref
|
||||
err = f.err
|
||||
if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) {
|
||||
l.stats.Hydration.WaitRefusals++
|
||||
|
||||
@@ -310,7 +310,7 @@ func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, err
|
||||
func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 2, 64)
|
||||
layer.stMu.Lock()
|
||||
oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3]
|
||||
oldRef, newRef := layer.headChunk(2), layer.headChunk(3)
|
||||
layer.stMu.Unlock()
|
||||
r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
layer.remote = r
|
||||
@@ -327,7 +327,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) {
|
||||
t.Fatal("old Get not entered")
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
layer.head.Chunks[2] = newRef
|
||||
setHeadChunkForTest(layer, 2, newRef)
|
||||
layer.absentGen[2]++
|
||||
layer.stMu.Unlock()
|
||||
newer := startHydrationRead(t, s, ctx, 8)
|
||||
@@ -350,7 +350,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) {
|
||||
func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 2, 64)
|
||||
layer.stMu.Lock()
|
||||
oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3]
|
||||
oldRef, newRef := layer.headChunk(2), layer.headChunk(3)
|
||||
layer.stMu.Unlock()
|
||||
r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})}
|
||||
layer.remote = r
|
||||
@@ -368,7 +368,7 @@ func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) {
|
||||
t.Fatal("old Get not entered")
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
layer.head.Chunks[2] = newRef
|
||||
setHeadChunkForTest(layer, 2, newRef)
|
||||
layer.absentGen[2]++
|
||||
layer.stMu.Unlock()
|
||||
newer := startHydrationRead(t, s, ctx, 8)
|
||||
|
||||
@@ -140,9 +140,12 @@ type chunkLayerImpl struct {
|
||||
stMu sync.Mutex
|
||||
closed bool
|
||||
head chunkHead
|
||||
pending *chunkHead // a proposal whose CAS outcome is unresolved
|
||||
fenced bool
|
||||
detached *chunkCutResult // set by a successful Detach
|
||||
// refs is the ref table of head on the v1.1 format (nil on v1.0): headRef
|
||||
// reads it; setHeadLocked and setHeadChangedLocked keep it head's.
|
||||
refs *refTable
|
||||
pending *chunkHead // a proposal whose CAS outcome is unresolved
|
||||
fenced bool
|
||||
detached *chunkCutResult // set by a successful Detach
|
||||
// pendingDetach says the unresolved proposal in pending is a Detach;
|
||||
// pendingCut is its cut result, installed as the detach result if the
|
||||
// re-read shows it applied.
|
||||
@@ -159,7 +162,10 @@ type chunkLayerImpl struct {
|
||||
// SAME changes at the same base, never a recomputed set. Owned: nothing
|
||||
// writes it after the commit that made it.
|
||||
pendingChanges map[uint64]*chunkRef
|
||||
pendingCut chunkCutResult
|
||||
// pendingMarked is that commit's equal-marked set (commitMarks): with
|
||||
// pendingChanges, what a settlement compares to decide it landed.
|
||||
pendingMarked map[uint64]*chunkRef
|
||||
pendingCut chunkCutResult
|
||||
// pendingBase is the version the unresolved CAS expected. While HEAD is
|
||||
// still at it, that CAS may still land, so a read alone never settles it.
|
||||
pendingBase chunkHeadVersion
|
||||
@@ -328,12 +334,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
l.nonce = hex.EncodeToString(nb8[:])
|
||||
l.ctx, l.cancel = context.WithCancel(context.Background())
|
||||
|
||||
head, err := remote.GetHead(l.ctx)
|
||||
head, err := l.readAttachHead(remote)
|
||||
if err != nil {
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err)
|
||||
}
|
||||
l.head = copyHeadEach(head, l.attachProgress.add) // reports as it copies
|
||||
l.remoteLSN = head.RemoteLSN
|
||||
// A HEAD that already belongs to a newer epoch or a competing holder is
|
||||
// never used as this holder's publication guard.
|
||||
@@ -357,14 +362,14 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch}
|
||||
l.dirty = map[uint64]bool{}
|
||||
|
||||
for idx := range head.Chunks {
|
||||
l.eachHeadChunkLocked(func(idx uint64) {
|
||||
l.absent[idx] = true
|
||||
l.absentGen[idx]++
|
||||
l.attachProgress.add(1)
|
||||
}
|
||||
})
|
||||
l.presenceVer++
|
||||
if cfg.CreatedThisStart {
|
||||
l.freshKnownZero = l.freshKnownZeroCandidates(head)
|
||||
l.freshKnownZero = l.freshKnownZeroCandidates()
|
||||
}
|
||||
} else if marked, _ := s.ChunkStateMarker(); chunkV11Format && marked {
|
||||
// The v1.1 record and the store's bits hold presence: a leftover
|
||||
@@ -441,6 +446,117 @@ func copyHeadEach(h chunkHead, each func(uint64)) chunkHead {
|
||||
|
||||
func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks }
|
||||
|
||||
// headRef is the reference HEAD names at chunk idx, and whether it names one:
|
||||
// every single-chunk reader of HEAD goes through it (and headChunk), so the
|
||||
// flat map behind it can be replaced (V4-B PR 4). Caller holds stMu.
|
||||
func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) {
|
||||
if l.refs != nil {
|
||||
return l.refs.Get(idx)
|
||||
}
|
||||
r, ok := l.head.Chunks[idx]
|
||||
return r, ok
|
||||
}
|
||||
|
||||
// setHeadLocked installs h as the layer's HEAD. On the v1.1 format HEAD's
|
||||
// chunks live in the ref table only: it is refilled from h whole (a HEAD
|
||||
// read whole: settlement, adoption, a fence) and the layer keeps h's
|
||||
// identity, no flat map (V4-B PR 4). Caller holds stMu or owns the layer.
|
||||
func (l *chunkLayerImpl) setHeadLocked(h chunkHead) {
|
||||
if !chunkV11Format {
|
||||
l.head, l.refs = h, nil
|
||||
return
|
||||
}
|
||||
if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks {
|
||||
l.refs = newRefTable(l.numChunks)
|
||||
}
|
||||
l.refs.fillAll(h.Chunks)
|
||||
h.Chunks = nil
|
||||
l.head = h
|
||||
}
|
||||
|
||||
// readAttachHead reads HEAD at attach and installs it. On the v1.1 format,
|
||||
// from a remote that reads HEAD one segment at a time (ChunkSegmentReader),
|
||||
// each segment's references go to the ref table as it is read: no flat map
|
||||
// is built, here or in the remote. Otherwise HEAD is read whole and
|
||||
// installed (setHeadLocked). Every reference is reported as attach progress.
|
||||
// It returns HEAD as installed (identity only on the v1.1 format).
|
||||
func (l *chunkLayerImpl) readAttachHead(remote chunkRemote) (chunkHead, error) {
|
||||
sr, segmented := remote.(ChunkSegmentReader)
|
||||
if !chunkV11Format || !segmented {
|
||||
head, err := remote.GetHead(l.ctx)
|
||||
if err != nil {
|
||||
return chunkHead{}, err
|
||||
}
|
||||
l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies
|
||||
return l.head, nil
|
||||
}
|
||||
refs := newRefTable(l.numChunks)
|
||||
head, err := sr.EachSegment(l.ctx, func(first, end uint64, seg map[uint64]ChunkRef) error {
|
||||
if first >= l.numChunks && len(seg) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := refs.FillSegment(first, min(end, l.numChunks), seg); err != nil {
|
||||
return err
|
||||
}
|
||||
l.attachProgress.add(uint64(len(seg)))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return chunkHead{}, err
|
||||
}
|
||||
head.Chunks = nil
|
||||
l.head, l.refs = head, refs
|
||||
return head, nil
|
||||
}
|
||||
|
||||
// ChunkSegmentReader is a remote that reads HEAD one segment at a time:
|
||||
// HEAD's identity (no chunk listed), and fn called for each segment its
|
||||
// root names with the segment's chunk range [first, end) and its
|
||||
// references. A HEAD with no image calls fn never.
|
||||
type ChunkSegmentReader interface {
|
||||
EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error)
|
||||
}
|
||||
|
||||
// eachHeadChunkLocked calls f for every chunk HEAD names (O(S): whole-volume
|
||||
// paths only). Caller holds stMu or owns the layer.
|
||||
func (l *chunkLayerImpl) eachHeadChunkLocked(f func(idx uint64)) {
|
||||
if l.refs != nil {
|
||||
l.refs.each(func(i uint64, _ chunkRef) { f(i) })
|
||||
return
|
||||
}
|
||||
for idx := range l.head.Chunks {
|
||||
f(idx)
|
||||
}
|
||||
}
|
||||
|
||||
// wholeHeadLocked is a copy of HEAD with every chunk listed: from the ref
|
||||
// table on the v1.1 format (O(S): for the rare paths that need the whole
|
||||
// image), else the flat map. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) wholeHeadLocked() chunkHead {
|
||||
h := copyHead(l.head)
|
||||
if l.refs != nil {
|
||||
l.refs.each(func(i uint64, r chunkRef) { h.Chunks[i] = r })
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// headChunksLocked is HEAD's chunks as a map: the flat map itself, or on
|
||||
// the v1.1 format a map built from the ref table (O(S)). Caller holds stMu.
|
||||
func (l *chunkLayerImpl) headChunksLocked() map[uint64]chunkRef {
|
||||
if l.refs == nil {
|
||||
return l.head.Chunks
|
||||
}
|
||||
return l.wholeHeadLocked().Chunks
|
||||
}
|
||||
|
||||
// headChunk is headRef's reference alone: the zero reference when HEAD names
|
||||
// none (a comparison with a named reference then fails, as a map read's
|
||||
// zero value did). Caller holds stMu.
|
||||
func (l *chunkLayerImpl) headChunk(idx uint64) chunkRef {
|
||||
r, _ := l.headRef(idx)
|
||||
return r
|
||||
}
|
||||
|
||||
// chunkHasLocalLocked reports whether any block of an absent chunk was
|
||||
// written locally since it became absent. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool {
|
||||
@@ -646,7 +762,7 @@ type filledMark struct {
|
||||
// Caller holds stMu.
|
||||
func (l *chunkLayerImpl) knownEqualToHeadLocked(idx uint64) bool {
|
||||
m, ok := l.filledClean[idx]
|
||||
return ok && !l.own[idx] && l.chunkVersion(idx) == m.version && l.head.Chunks[idx] == m.ref
|
||||
return ok && !l.own[idx] && l.chunkVersion(idx) == m.version && l.headChunk(idx) == m.ref
|
||||
}
|
||||
|
||||
// chunkVersion is chunk idx's mutation count.
|
||||
@@ -732,7 +848,7 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat
|
||||
// current reports whether this fill still belongs to the chunk's present
|
||||
// absence: same generation, same HEAD ref. Caller holds stMu.
|
||||
current := func() bool {
|
||||
return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref
|
||||
return l.absent[idx] && l.absentGen[idx] == gen && l.headChunk(idx) == ref
|
||||
}
|
||||
first := idx * l.chunkBlocks
|
||||
for i := uint64(0); i < l.chunkBlocks; i++ {
|
||||
@@ -960,7 +1076,7 @@ func (l *chunkLayerImpl) shadowExemptLocked(idx uint64) bool {
|
||||
}
|
||||
v, ok := l.shadow.recoverKilled(idx)
|
||||
m, marked := l.filledClean[idx]
|
||||
return ok && marked && v == l.chunkVersion(idx) && l.head.Chunks[idx] == m.ref
|
||||
return ok && marked && v == l.chunkVersion(idx) && l.headChunk(idx) == m.ref
|
||||
}
|
||||
|
||||
// shadowCommit is the record's E6: the HEAD just installed names every
|
||||
@@ -1041,9 +1157,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
st.HeadReadbackNs += time.Since(start).Nanoseconds()
|
||||
return head, ok, err
|
||||
}
|
||||
finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) {
|
||||
finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string, inPlace bool) {
|
||||
start := time.Now()
|
||||
l.finishCut(head, h, changed, keys)
|
||||
l.finishCut(head, h, changed, keys, inPlace)
|
||||
st.CommitStateNs += time.Since(start).Nanoseconds()
|
||||
}
|
||||
var pauseStart time.Time
|
||||
@@ -1270,7 +1386,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.dirty = map[uint64]bool{}
|
||||
l.allDirty = false
|
||||
l.cutLSN = h
|
||||
baseHead := copyHead(l.head)
|
||||
baseHead := l.cutBaseLocked(candidates)
|
||||
l.stMu.Unlock()
|
||||
l.cutPhase("compare")
|
||||
// Candidates, mutation versions and the copy-order hint belong to the same barrier.
|
||||
@@ -1432,7 +1548,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
|
||||
// A no-op cut still observes authority: a fresh host may have
|
||||
// claimed HEAD without uploading a single chunk since our last cut.
|
||||
cur, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead)
|
||||
cur, fromBase, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead)
|
||||
if err != nil {
|
||||
l.requeueCut(all)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err)
|
||||
@@ -1441,27 +1557,44 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
// the CAS path does. Its generation alone may move without either
|
||||
// (a settlement that aborts this holder's session rewrites HEAD as
|
||||
// it was): the cut then completes on the newer generation.
|
||||
if !sameProposal(cur, baseHead) {
|
||||
// On the v1.1 format the image compared is the cut's: its captured
|
||||
// chunks, every one equal to its base (the proposal by change).
|
||||
byChange := l.commitByChange()
|
||||
same := sameProposal(cur, baseHead)
|
||||
if byChange {
|
||||
same = sameByChange(cur, baseHead, headLookup(cur), nil, commitMarks(baseHead, captured, capturedVersions, map[uint64]*chunkRef{}))
|
||||
if same && !fromBase {
|
||||
// HEAD read whole: its chunk root must be the one the layer
|
||||
// holds (the ref table), as the full comparison required; a
|
||||
// HEAD moved at this identity to another root is fenced.
|
||||
l.stMu.Lock()
|
||||
same = sameChunkRoot(l.headChunksLocked(), cur.Chunks)
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
}
|
||||
if !same {
|
||||
l.requeueCut(all)
|
||||
l.fencePublication(cur)
|
||||
return chunkCutResult{}, errChunkLayerFenced
|
||||
}
|
||||
finishCapturedCut(cur, h, nil, nil) // nothing new: no CAS
|
||||
inPlace := byChange && fromBase // cur is the cut's base: its candidates only
|
||||
finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS
|
||||
persistCapturedMap(capturedVersions)
|
||||
return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil
|
||||
return chunkCutResult{H: h, Head: resultHead(cur), Noop: true, FullHash: all}, nil
|
||||
}
|
||||
expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch}
|
||||
// On the v1.1 format the commit goes by change: one owned change set,
|
||||
// built once from the captured chunks, for the check, the CAS and an
|
||||
// unresolved commit's settlement alike (nil: the full commit).
|
||||
changes := l.commitChanges(next, changed)
|
||||
marked := commitMarks(next, captured, capturedVersions, changes)
|
||||
// A lookup failure writes nothing and leaves the session open; the dirty
|
||||
// set returns for the next cut.
|
||||
// ManifestNs is the manifest work of the commit check only: the check
|
||||
// runs outside every other measured part, while a HEAD re-read (a
|
||||
// settlement) reads the manifest inside HeadReadbackNs.
|
||||
manifestBefore := work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load()
|
||||
checkErr := l.checkCommitFirstBy(ctx, expected, next, changes)
|
||||
checkErr := l.checkCommitFirstBy(ctx, expected, proposalOf(next, changes), changes)
|
||||
st.ManifestNs += work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - manifestBefore
|
||||
if err := checkErr; err != nil {
|
||||
l.requeueCut(all)
|
||||
@@ -1481,7 +1614,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
l.cutPhase("commit")
|
||||
casStart := time.Now()
|
||||
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, next, changes, &st)
|
||||
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, proposalOf(next, changes), changes, &st)
|
||||
st.CASNs = time.Since(casStart).Nanoseconds()
|
||||
st.CASResult = "ok"
|
||||
if errors.Is(casErr, errChunkHeadPrecondition) {
|
||||
@@ -1492,10 +1625,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
if casErr == nil {
|
||||
l.cutPhase("settle")
|
||||
next.Gen = gen
|
||||
finishCapturedCut(next, h, changed, newKeys)
|
||||
finishCapturedCut(next, h, changed, newKeys, changes != nil)
|
||||
l.shadowCommit(captured, capturedVersions)
|
||||
persistCapturedMap(capturedVersions)
|
||||
return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil
|
||||
return l.cutDone(chunkCutResult{H: h, Head: resultHead(next), FullHash: all}, detach), nil
|
||||
}
|
||||
// Precondition or unknown outcome: resolve by re-reading HEAD, never by
|
||||
// a blind retry.
|
||||
@@ -1505,7 +1638,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.pending = &p
|
||||
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = detach, chunkCutResult{H: h, FullHash: all}, expected, false
|
||||
l.pendingCaptured = pendingCapture(captured, capturedVersions)
|
||||
l.pendingChanges = changes
|
||||
l.pendingChanges, l.pendingMarked = changes, marked
|
||||
l.stMu.Unlock()
|
||||
// The session stays open: the commit may still land, and the
|
||||
// settlement replays it in the same session (resolvePending).
|
||||
@@ -1521,24 +1654,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
keepPending()
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr)
|
||||
}
|
||||
if !sameProposal(cur, next) && l.publicationOwnerChanged(cur) {
|
||||
landedNext := proposalLanded(cur, next, expected.Gen, changes, marked)
|
||||
if !landedNext && l.publicationOwnerChanged(cur) {
|
||||
keepPending() // Close must keep these roots as well.
|
||||
l.fencePublication(cur)
|
||||
return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr)
|
||||
}
|
||||
if !errors.Is(casErr, errChunkHeadPrecondition) && !sameProposal(cur, next) && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch {
|
||||
if !errors.Is(casErr, errChunkHeadPrecondition) && !landedNext && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch {
|
||||
// HEAD is still the CAS's base and the server gave no definite
|
||||
// refusal: the CAS may still land. Settle it before any later
|
||||
// capture or durability point (resolvePending re-proposes it).
|
||||
keepPending()
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
|
||||
}
|
||||
if sameProposal(cur, next) {
|
||||
if landedNext {
|
||||
st.CASResult = "resolved-by-reread"
|
||||
finishCapturedCut(cur, h, changed, newKeys)
|
||||
finishCapturedCut(cur, h, changed, newKeys, false) // cur is HEAD as read: whole
|
||||
l.shadowCommit(captured, capturedVersions)
|
||||
persistCapturedMap(capturedVersions)
|
||||
return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil
|
||||
return l.cutDone(chunkCutResult{H: h, Head: resultHead(cur), FullHash: all}, detach), nil
|
||||
}
|
||||
// HEAD moved past the CAS's base without it: it can never land, and
|
||||
// what it staged was compared against a HEAD that is gone.
|
||||
@@ -1547,7 +1681,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
if l.supersededBy(cur) {
|
||||
l.stMu.Lock()
|
||||
l.fenced = true
|
||||
l.head = copyHead(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
l.stMu.Unlock()
|
||||
l.abortCOW(errChunkLayerFenced)
|
||||
return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr)
|
||||
@@ -1597,11 +1731,14 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
|
||||
}
|
||||
l.stMu.Lock()
|
||||
fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase
|
||||
baseHead := copyHead(l.head)
|
||||
changes, marked := l.pendingChanges, l.pendingMarked
|
||||
baseHead := l.cutBaseLocked(nil) // the cancel's base: identity only on the v1.1 format, whole before
|
||||
l.stMu.Unlock()
|
||||
if fenced {
|
||||
return detachFenced, chunkCutResult{}, nil
|
||||
}
|
||||
// cancelled: this settlement's cancel CAS landed; cur is that cancel.
|
||||
cancelled := false
|
||||
if pending == nil || !isDetach {
|
||||
// Nothing of this detach can land: it failed before its CAS or was
|
||||
// definitely refused (an unresolved ordinary cut settles as usual).
|
||||
@@ -1611,30 +1748,38 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
|
||||
if err != nil {
|
||||
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
if err := l.admit(); err != nil {
|
||||
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
cancel := copyHead(baseHead)
|
||||
cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder
|
||||
cancel.State, cancel.DetachedBy = chunkHeadActive, nil
|
||||
if err := l.checkCommitFirst(ctx, base, cancel); err != nil {
|
||||
// On the v1.1 format the cancel is a commit by change with no
|
||||
// change: the base's chunks stay as HEAD has them; only the identity
|
||||
// and the state move (nil changes: the whole base image, before).
|
||||
var none map[uint64]*chunkRef
|
||||
if changes != nil {
|
||||
none = map[uint64]*chunkRef{}
|
||||
}
|
||||
if err := l.checkCommitFirstBy(ctx, base, proposalOf(cancel, none), none); err != nil {
|
||||
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel check failed: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, cancel)
|
||||
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, proposalOf(cancel, none), none, nil)
|
||||
if casErr == nil {
|
||||
cancel.Gen = gen
|
||||
cur = cancel
|
||||
cancelled = none != nil
|
||||
} else if errors.Is(casErr, errChunkLayerFenced) {
|
||||
l.fencePublication(chunkHead{})
|
||||
return detachFenced, chunkCutResult{}, nil
|
||||
} else if cur, err = readChunkHead(ctx, l.remote); err != nil {
|
||||
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err)
|
||||
} else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
} else if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
|
||||
}
|
||||
}
|
||||
if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) {
|
||||
if !proposalLanded(cur, *pending, base.Gen, changes, marked) && l.publicationOwnerChanged(cur) {
|
||||
l.fencePublication(cur)
|
||||
return detachFenced, chunkCutResult{}, nil
|
||||
}
|
||||
@@ -1646,21 +1791,28 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle
|
||||
l.pending = nil
|
||||
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false
|
||||
landed := l.pendingCaptured
|
||||
l.pendingCaptured, l.pendingChanges = nil, nil
|
||||
l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil
|
||||
switch {
|
||||
case sameProposal(cur, *pending):
|
||||
l.noteSettled(l.head, cur)
|
||||
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
|
||||
case proposalLanded(cur, *pending, base.Gen, changes, marked):
|
||||
l.noteSettledFromHeadLocked(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
l.remoteLSN = cur.RemoteLSN
|
||||
l.shadowCommitCaptured(landed, true)
|
||||
cut.Head = copyHead(cur)
|
||||
cut.Head = resultHead(cur)
|
||||
l.detached = &cut
|
||||
r := cut
|
||||
r.Head = copyHead(cur)
|
||||
r.Head = resultHead(cur)
|
||||
return detachApplied, r, nil
|
||||
case l.supersededBy(cur):
|
||||
l.fenced = true
|
||||
l.head = copyHead(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
return detachFenced, chunkCutResult{}, nil
|
||||
case cancelled:
|
||||
// The cancel by change landed: HEAD is the base's chunks at this
|
||||
// holder's identity, active. Installed in place (identity only); its
|
||||
// chunks are the table's already.
|
||||
l.applyCommitLocked(cur, nil)
|
||||
return detachNotPublished, chunkCutResult{}, nil
|
||||
default:
|
||||
if l.adoptHeadLocked(cur) != nil {
|
||||
return detachFenced, chunkCutResult{}, nil
|
||||
@@ -1692,7 +1844,7 @@ func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) {
|
||||
defer l.stMu.Unlock()
|
||||
if d := l.detached; d != nil {
|
||||
r := *d
|
||||
r.Head = copyHead(d.Head)
|
||||
r.Head = copyResultHead(d.Head)
|
||||
return r, true
|
||||
}
|
||||
return chunkCutResult{}, false
|
||||
@@ -1703,7 +1855,7 @@ func (l *chunkLayerImpl) cutDone(r chunkCutResult, detach bool) chunkCutResult {
|
||||
if detach {
|
||||
l.stMu.Lock()
|
||||
keep := r
|
||||
keep.Head = copyHead(r.Head)
|
||||
keep.Head = copyResultHead(r.Head)
|
||||
l.detached = &keep
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
@@ -1724,17 +1876,19 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool {
|
||||
// identity alone (a ChunkHeadRootReader remote) and HEAD is still the image baseHead
|
||||
// names (the same generation token, epoch, holder, position and detach
|
||||
// state; the token changes whenever HEAD's root does), it is baseHead with
|
||||
// its chunks, and no manifest is read. Otherwise it is the whole HEAD (full).
|
||||
func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (chunkHead, error) {
|
||||
// its chunks, and no manifest is read (fromBase). Otherwise it is the whole
|
||||
// HEAD (full).
|
||||
func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (head chunkHead, fromBase bool, err error) {
|
||||
root, ok, err := rootRead()
|
||||
if err != nil {
|
||||
return chunkHead{}, err
|
||||
return chunkHead{}, false, err
|
||||
}
|
||||
if ok && root.Gen == baseHead.Gen && root.Epoch == baseHead.Epoch && root.Holder == baseHead.Holder &&
|
||||
root.RemoteLSN == baseHead.RemoteLSN && chunkHeadIsDetached(root) == chunkHeadIsDetached(baseHead) {
|
||||
return copyHead(baseHead), nil
|
||||
return copyHead(baseHead), true, nil
|
||||
}
|
||||
return full()
|
||||
head, err = full()
|
||||
return head, false, err
|
||||
}
|
||||
|
||||
func sameProposal(cur, next chunkHead) bool {
|
||||
@@ -1823,6 +1977,163 @@ func (l *chunkLayerImpl) commitChanges(next chunkHead, changed []uint64) map[uin
|
||||
return out
|
||||
}
|
||||
|
||||
// commitMarks is a commit by change's equal-marked set: each captured chunk
|
||||
// the change leaves as it was, with the reference the proposal names there
|
||||
// (nil: nothing, a zero chunk equal to an absent base). nil when the layer
|
||||
// commits in full (changes nil). Every index in it is one the full
|
||||
// comparison also compares.
|
||||
func commitMarks(next chunkHead, captured []capturedChunk, versions map[uint64]uint64, changes map[uint64]*chunkRef) map[uint64]*chunkRef {
|
||||
if changes == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[uint64]*chunkRef)
|
||||
for _, c := range captured {
|
||||
if _, ok := versions[c.idx]; !ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := changes[c.idx]; ok {
|
||||
continue
|
||||
}
|
||||
if ref, ok := next.Chunks[c.idx]; ok {
|
||||
r := ref
|
||||
out[c.idx] = &r
|
||||
} else {
|
||||
out[c.idx] = nil
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// proposalLanded reports whether HEAD cur is the proposal next made at base
|
||||
// generation baseGen: by change (sameProposalByChange, O(changed + marked))
|
||||
// when the commit went by change, else the full comparison.
|
||||
func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uint64]*chunkRef) bool {
|
||||
if changes == nil {
|
||||
return sameProposal(cur, next)
|
||||
}
|
||||
return sameProposalByChange(cur, next, baseGen, headLookup(cur), changes, marked)
|
||||
}
|
||||
|
||||
// cutBaseLocked is a cut's base: HEAD's identity, and its chunks: on the
|
||||
// v1.1 format only the candidates' references (O(C): the commit by change,
|
||||
// its marks and the COW window read no other chunk), else a copy of all.
|
||||
// Caller holds stMu.
|
||||
func (l *chunkLayerImpl) cutBaseLocked(candidates map[uint64]bool) chunkHead {
|
||||
if !l.commitByChange() {
|
||||
return l.wholeHeadLocked()
|
||||
}
|
||||
b := l.head
|
||||
b.Chunks, b.Segments = nil, nil
|
||||
b = copyHead(b)
|
||||
b.Segments = l.head.Segments // shared, never written: every install replaces the map
|
||||
for idx := range candidates {
|
||||
if r, ok := l.headRef(idx); ok {
|
||||
b.Chunks[idx] = r
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// proposalOf is the HEAD a commit sends: by change (changes not nil) its
|
||||
// identity alone, the remote applying the changes to its own chunks; else
|
||||
// next whole.
|
||||
func proposalOf(next chunkHead, changes map[uint64]*chunkRef) chunkHead {
|
||||
if changes != nil {
|
||||
next.Chunks = nil
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
// cutResultHead is the HEAD a cut reports: h whole, or on the v1.1 format
|
||||
// (byChange, h naming the cut's chunks only) HEAD's identity alone, Chunks
|
||||
// nil: a cut's result is read for its generation, epoch and holder, and a
|
||||
// whole copy per cut is the map the ref table replaces
|
||||
// (TestNoProductionReaderOfACutResultsChunks).
|
||||
func cutResultHead(h chunkHead, byChange bool) chunkHead {
|
||||
out := copyHead(h)
|
||||
if byChange {
|
||||
out.Chunks, out.Segments = nil, nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resultHead is the HEAD every cut, settlement and detach outcome reports and
|
||||
// keeps: identity only on the v1.1 format, on every path (a whole read's,
|
||||
// a re-proposal's, a no-op's), so no result holds a chunk map; whole before.
|
||||
func resultHead(h chunkHead) chunkHead { return cutResultHead(h, chunkV11Format) }
|
||||
|
||||
// noteSettledFromHeadLocked records the publication from the layer's HEAD,
|
||||
// whole (the ref table's image on the v1.1 format), to next, before next is
|
||||
// installed. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) noteSettledFromHeadLocked(next chunkHead) {
|
||||
if l.cfg.OnPublishSettled == nil {
|
||||
return
|
||||
}
|
||||
l.noteSettled(l.wholeHeadLocked(), next) // it drops a report of an unchanged generation
|
||||
}
|
||||
|
||||
// copyResultHead copies a cut's reported HEAD as it was reported: a result
|
||||
// that reports identity only (Chunks nil) stays so.
|
||||
func copyResultHead(h chunkHead) chunkHead {
|
||||
return cutResultHead(h, h.Chunks == nil)
|
||||
}
|
||||
|
||||
// changedIndices is a change set's indices.
|
||||
func changedIndices(changes map[uint64]*chunkRef) []uint64 {
|
||||
out := make([]uint64, 0, len(changes))
|
||||
for idx := range changes {
|
||||
out = append(out, idx)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// headLookup reads h's chunks as sameProposalByChange's ref.
|
||||
func headLookup(h chunkHead) func(uint64) (chunkRef, bool) {
|
||||
return func(i uint64) (chunkRef, bool) { r, ok := h.Chunks[i]; return r, ok }
|
||||
}
|
||||
|
||||
// applyCommitLocked installs a landed commit by change onto HEAD in place
|
||||
// (O(C)): id's identity (generation, epoch, holder, position, state, who
|
||||
// detached, chunk size and count) and each changed chunk's reference from
|
||||
// id (none: zeros); every other chunk is HEAD's already, as the commit left
|
||||
// it. The publication report, when one is wanted, gets whole HEADs. Caller
|
||||
// holds stMu.
|
||||
func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) {
|
||||
report := l.cfg.OnPublishSettled != nil // noteSettled drops an unchanged generation
|
||||
var prev chunkHead
|
||||
if report {
|
||||
prev = l.wholeHeadLocked()
|
||||
}
|
||||
h := l.head
|
||||
h.Gen, h.Epoch, h.Holder, h.RemoteLSN, h.State = id.Gen, id.Epoch, id.Holder, id.RemoteLSN, id.State
|
||||
h.ChunkBytes, h.ManifestChunkCount = id.ChunkBytes, id.ManifestChunkCount
|
||||
h.DetachedBy = nil
|
||||
if id.DetachedBy != nil {
|
||||
d := *id.DetachedBy
|
||||
h.DetachedBy = &d
|
||||
}
|
||||
for _, idx := range changed {
|
||||
r, ok := id.Chunks[idx]
|
||||
switch {
|
||||
case l.refs != nil && ok:
|
||||
_ = l.refs.Set(idx, r)
|
||||
case l.refs != nil:
|
||||
l.refs.Delete(idx)
|
||||
case ok:
|
||||
if h.Chunks == nil {
|
||||
h.Chunks = map[uint64]chunkRef{}
|
||||
}
|
||||
h.Chunks[idx] = r
|
||||
default:
|
||||
delete(h.Chunks, idx)
|
||||
}
|
||||
}
|
||||
l.head = h
|
||||
if report {
|
||||
l.noteSettled(prev, l.wholeHeadLocked())
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
|
||||
// Registered before the state unlock, so invalidation runs without stMu.
|
||||
defer func() {
|
||||
@@ -1831,16 +2142,19 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
|
||||
}
|
||||
}()
|
||||
l.stMu.Lock()
|
||||
pending, base, aborted, changes := l.pending, l.pendingBase, l.pendingAborted, l.pendingChanges
|
||||
pending, base, aborted, changes, marked := l.pending, l.pendingBase, l.pendingAborted, l.pendingChanges, l.pendingMarked
|
||||
l.stMu.Unlock()
|
||||
if pending == nil {
|
||||
return nil
|
||||
}
|
||||
// reproposed: cur is the re-proposal this settlement landed, not HEAD
|
||||
// as read; by change it names the cut's chunks only.
|
||||
reproposed := false
|
||||
cur, err := readChunkHead(ctx, l.remote)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
if !aborted && !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
if !aborted && !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
// HEAD is still the unresolved CAS's base, so that CAS may still
|
||||
// land. Settle it by issuing the same proposal at the same base:
|
||||
// whichever lands first, HEAD ends at this proposal and the other
|
||||
@@ -1851,23 +2165,24 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
|
||||
if err := l.admit(); err != nil {
|
||||
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
if err := l.checkCommitFirstBy(ctx, base, *pending, changes); err != nil {
|
||||
if err := l.checkCommitFirstBy(ctx, base, proposalOf(*pending, changes), changes); err != nil {
|
||||
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal check failed: %w", errChunkCASOutcomeUnknown, err)
|
||||
}
|
||||
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, copyHead(*pending), changes, nil)
|
||||
gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, proposalOf(copyHead(*pending), changes), changes, nil)
|
||||
if casErr == nil {
|
||||
cur = copyHead(*pending)
|
||||
cur.Gen = gen
|
||||
reproposed = true
|
||||
} else if errors.Is(casErr, errChunkLayerFenced) {
|
||||
l.fencePublication(chunkHead{})
|
||||
return errChunkLayerFenced
|
||||
} else if cur, err = readChunkHead(ctx, l.remote); err != nil {
|
||||
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, err)
|
||||
} else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
} else if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
|
||||
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
|
||||
}
|
||||
}
|
||||
if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) {
|
||||
if !proposalLanded(cur, *pending, base.Gen, changes, marked) && l.publicationOwnerChanged(cur) {
|
||||
l.fencePublication(cur)
|
||||
return errChunkLayerFenced
|
||||
}
|
||||
@@ -1882,20 +2197,26 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) {
|
||||
wasDetach, cut := l.pendingDetach, l.pendingCut
|
||||
l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false
|
||||
landed := l.pendingCaptured
|
||||
l.pendingCaptured, l.pendingChanges = nil, nil
|
||||
l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil
|
||||
switch {
|
||||
case sameProposal(cur, *pending):
|
||||
l.noteSettled(l.head, cur)
|
||||
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
|
||||
case proposalLanded(cur, *pending, base.Gen, changes, marked):
|
||||
inPlace := reproposed && changes != nil
|
||||
if inPlace {
|
||||
l.applyCommitLocked(cur, changedIndices(changes))
|
||||
} else {
|
||||
l.noteSettledFromHeadLocked(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
}
|
||||
l.remoteLSN = cur.RemoteLSN
|
||||
l.shadowCommitCaptured(landed, true)
|
||||
if wasDetach {
|
||||
cut.Head = copyHead(cur)
|
||||
cut.Head = resultHead(cur)
|
||||
l.detached = &cut
|
||||
return errChunkLayerDetached
|
||||
}
|
||||
case l.supersededBy(cur):
|
||||
l.fenced = true
|
||||
l.head = copyHead(cur)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
return errChunkLayerFenced
|
||||
default:
|
||||
// HEAD moved past the unresolved CAS's base without it: that CAS
|
||||
@@ -1919,8 +2240,8 @@ var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder
|
||||
// the one the layer holds; otherwise the layer is fenced
|
||||
// (errChunkForeignRoot). Caller holds stMu.
|
||||
func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error {
|
||||
same := sameChunkRoot(l.head.Chunks, cur.Chunks)
|
||||
l.head = copyHead(cur)
|
||||
same := sameChunkRoot(l.headChunksLocked(), cur.Chunks)
|
||||
l.setHeadLocked(copyHead(cur))
|
||||
if !same {
|
||||
l.fenced = true
|
||||
log.Printf("level=WARN storage: chunk layer fenced: HEAD gen %d moved the chunk root without superseding holder %q epoch %d", cur.Gen, l.cfg.Holder, l.cfg.Epoch)
|
||||
@@ -2172,7 +2493,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap
|
||||
for _, idx := range batch {
|
||||
vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it
|
||||
}
|
||||
head := copyHead(l.head)
|
||||
inBatch := make(map[uint64]bool, len(batch))
|
||||
for _, idx := range batch {
|
||||
inBatch[idx] = true
|
||||
}
|
||||
head := l.cutBaseLocked(inBatch)
|
||||
l.stMu.Unlock()
|
||||
st.StageRounds++
|
||||
st.CandidateChunks = max(st.CandidateChunks, len(batch))
|
||||
@@ -2228,12 +2553,17 @@ func (l *chunkLayerImpl) requeueCut(all bool) {
|
||||
|
||||
// finishCut installs HEAD in memory and rolls the bitmap over: only chunks
|
||||
// dirtied after the cut (and WAL entries above it) stay set.
|
||||
func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) {
|
||||
func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string, inPlace bool) {
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
l.noteSettled(l.head, head)
|
||||
l.head, l.remoteLSN, l.pending = copyHead(head), h, nil
|
||||
l.pendingCaptured, l.pendingChanges = nil, nil
|
||||
if inPlace {
|
||||
l.applyCommitLocked(head, changed)
|
||||
} else {
|
||||
l.noteSettledFromHeadLocked(head)
|
||||
l.setHeadLocked(copyHead(head))
|
||||
}
|
||||
l.remoteLSN, l.pending = h, nil
|
||||
l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil
|
||||
l.reusable = nil
|
||||
l.inflight = map[uint64]bool{}
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
|
||||
@@ -2302,7 +2632,7 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error {
|
||||
l.stMu.Unlock()
|
||||
return fmt.Errorf("%w: chunk %d is dirty since HEAD or HEAD is unknown", errChunkEvictRefused, idx)
|
||||
}
|
||||
if _, inHead := l.head.Chunks[idx]; !inHead {
|
||||
if _, inHead := l.headRef(idx); !inHead {
|
||||
l.stMu.Unlock()
|
||||
return nil // ZERO in HEAD: nothing to make absent
|
||||
}
|
||||
|
||||
@@ -6,7 +6,13 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A cut's result on the v1.1 format reports HEAD's identity only (Chunks
|
||||
// nil): it is the same HEAD when that identity is b's.
|
||||
func sameHead(a, b chunkHead) bool {
|
||||
if a.Chunks == nil && a.Gen != 0 {
|
||||
return a.Gen == b.Gen && a.Epoch == b.Epoch && a.Holder == b.Holder && a.RemoteLSN == b.RemoteLSN &&
|
||||
a.State == b.State && (a.DetachedBy == nil) == (b.DetachedBy == nil) && (a.DetachedBy == nil || *a.DetachedBy == *b.DetachedBy)
|
||||
}
|
||||
if a.Gen != b.Gen || a.Epoch != b.Epoch || a.Holder != b.Holder || a.RemoteLSN != b.RemoteLSN || len(a.Chunks) != len(b.Chunks) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) {
|
||||
// share one flight, so two guest reads cannot create this overlap.
|
||||
impl := layer.(*chunkLayerImpl)
|
||||
impl.stMu.Lock()
|
||||
oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2]
|
||||
oldGen, oldRef := impl.absentGen[2], impl.headChunk(2)
|
||||
impl.stMu.Unlock()
|
||||
readA := make(chan error, 1)
|
||||
joinedA := make(chan struct{})
|
||||
|
||||
@@ -30,7 +30,7 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s
|
||||
defer l.capMu.Unlock()
|
||||
l.stMu.Lock()
|
||||
var picked []uint64
|
||||
for _, idx := range sortedForeign(l.head.Chunks, foreign) {
|
||||
for _, idx := range sortedForeign(l.headChunksLocked(), foreign) {
|
||||
if len(picked) < n && l.chunkLocalLocked(idx) {
|
||||
picked = append(picked, idx)
|
||||
}
|
||||
@@ -73,8 +73,8 @@ type ownCount struct {
|
||||
|
||||
// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu.
|
||||
func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount {
|
||||
c := ownCount{head: l.head.Chunks}
|
||||
for _, idx := range sortedForeign(l.head.Chunks, foreign) {
|
||||
c := ownCount{head: l.headChunksLocked()}
|
||||
for _, idx := range sortedForeign(c.head, foreign) {
|
||||
c.Remaining++
|
||||
if !l.chunkLocalLocked(idx) {
|
||||
c.NotLocal++
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package storage
|
||||
|
||||
// sameProposalByChange decides whether a commit by change landed in cur,
|
||||
// without comparing whole chunk maps (V4-B PR 4; the rule is SegCut's
|
||||
// "proposal landed" decision, the model's existing row): O(C) in the cut's
|
||||
// changed and equal-marked chunks. The proposal landed iff
|
||||
//
|
||||
// 1. cur's generation is past the base the CAS expected (baseGen);
|
||||
// 2. every identity field the full comparison has is equal: epoch, holder,
|
||||
// position, the detached state and who detached, the chunk size and the
|
||||
// manifest's chunk count;
|
||||
// 3. for every changed index cur names exactly the new reference (nothing,
|
||||
// for a chunk the change made zeros);
|
||||
// 4. for every candidate the cut marked equal to its base reference, cur
|
||||
// names that base reference, or nothing when the base named nothing (a
|
||||
// zero chunk marked equal to an absent base); a mark assumes it, and
|
||||
// without the check an index another writer changed would be marked
|
||||
// published under a hash HEAD does not name.
|
||||
//
|
||||
// Indices the cut neither changed nor marked carry marks set by earlier
|
||||
// landings and are not compared. cur's chunks are read through ref (a lookup
|
||||
// in whatever representation the caller has: a map, the ref table).
|
||||
func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uint64) (chunkRef, bool),
|
||||
changes, marked map[uint64]*chunkRef) bool {
|
||||
return cur.Gen > baseGen && sameByChange(cur, ident, ref, changes, marked)
|
||||
}
|
||||
|
||||
// sameByChange is sameProposalByChange without the generation (conditions
|
||||
// 2-4): a no-op cut, which commits nothing, compares HEAD with its base so.
|
||||
func sameByChange(cur, ident chunkHead, ref func(idx uint64) (chunkRef, bool), changes, marked map[uint64]*chunkRef) bool {
|
||||
if cur.Epoch != ident.Epoch || cur.Holder != ident.Holder || cur.RemoteLSN != ident.RemoteLSN ||
|
||||
cur.ChunkBytes != ident.ChunkBytes || cur.ManifestChunkCount != ident.ManifestChunkCount {
|
||||
return false
|
||||
}
|
||||
if chunkHeadIsDetached(cur) != chunkHeadIsDetached(ident) || (cur.DetachedBy == nil) != (ident.DetachedBy == nil) ||
|
||||
(cur.DetachedBy != nil && (cur.DetachedBy.Holder != ident.DetachedBy.Holder || cur.DetachedBy.Epoch != ident.DetachedBy.Epoch)) {
|
||||
return false
|
||||
}
|
||||
same := func(a, b chunkRef) bool { return a.Key == b.Key && a.SHA256 == b.SHA256 && a.Encoding == b.Encoding }
|
||||
// names reports whether cur names exactly want at idx (nil: nothing).
|
||||
names := func(idx uint64, want *chunkRef) bool {
|
||||
got, ok := ref(idx)
|
||||
if want == nil {
|
||||
return !ok
|
||||
}
|
||||
return ok && same(got, *want)
|
||||
}
|
||||
for idx, want := range changes {
|
||||
if !names(idx, want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for idx, base := range marked {
|
||||
if !names(idx, base) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sameProposalByChange is landed iff the generation advanced past the base,
|
||||
// every identity field equals, every changed index names the new reference
|
||||
// (nothing for a zeroing) and every equal-marked candidate names the base
|
||||
// reference its mark assumed; unchanged, unmarked indices are not compared.
|
||||
// Each condition broken alone is not landed; a replay of the identical
|
||||
// proposal is landed whichever copy won.
|
||||
func TestSameProposalByChange(t *testing.T) {
|
||||
r := func(tag string) chunkRef {
|
||||
s := sha256.Sum256([]byte(tag))
|
||||
return chunkRef{Key: fmt.Sprintf("k-%s", tag), SHA256: s, Encoding: "full"}
|
||||
}
|
||||
newRef, base5, other := r("new"), r("base5"), r("other")
|
||||
ident := chunkHead{Epoch: 3, Holder: "a", RemoteLSN: 90, ChunkBytes: 4096, ManifestChunkCount: 64, State: chunkHeadActive}
|
||||
changes := map[uint64]*chunkRef{2: &newRef, 4: nil} // chunk 2 rewritten, chunk 4 zeroed
|
||||
marked := map[uint64]*chunkRef{5: &base5, 6: nil} // chunk 5 equal to its base ref; chunk 6 a zero chunk equal to an absent base
|
||||
landedHead := func() (chunkHead, map[uint64]chunkRef) {
|
||||
h := ident
|
||||
h.Gen = 8
|
||||
return h, map[uint64]chunkRef{2: newRef, 5: base5, 7: other} // 7: neither changed nor marked
|
||||
}
|
||||
check := func(h chunkHead, m map[uint64]chunkRef) bool {
|
||||
return sameProposalByChange(h, ident, 7, func(i uint64) (chunkRef, bool) { r, ok := m[i]; return r, ok }, changes, marked)
|
||||
}
|
||||
h, m := landedHead()
|
||||
if !check(h, m) {
|
||||
t.Fatal("the landed proposal is not found landed")
|
||||
}
|
||||
m[7] = r("elsewhere") // an index the cut neither changed nor marked: not compared
|
||||
if !check(h, m) {
|
||||
t.Fatal("an unchanged, unmarked index decided the outcome")
|
||||
}
|
||||
for name, mutate := range map[string]func(h *chunkHead, m map[uint64]chunkRef){
|
||||
"generation not past the base": func(h *chunkHead, _ map[uint64]chunkRef) { h.Gen = 7 },
|
||||
"another epoch": func(h *chunkHead, _ map[uint64]chunkRef) { h.Epoch = 4 },
|
||||
"another holder": func(h *chunkHead, _ map[uint64]chunkRef) { h.Holder = "b" },
|
||||
"another position": func(h *chunkHead, _ map[uint64]chunkRef) { h.RemoteLSN = 91 },
|
||||
"another chunk size": func(h *chunkHead, _ map[uint64]chunkRef) { h.ChunkBytes = 8192 },
|
||||
"another manifest count": func(h *chunkHead, _ map[uint64]chunkRef) { h.ManifestChunkCount = 65 },
|
||||
"detached": func(h *chunkHead, _ map[uint64]chunkRef) {
|
||||
h.State = chunkHeadDetached
|
||||
h.DetachedBy = &chunkDetachedBy{Holder: "a", Epoch: 3}
|
||||
},
|
||||
"a changed index not written": func(_ *chunkHead, m map[uint64]chunkRef) { m[2] = other },
|
||||
"a changed index missing": func(_ *chunkHead, m map[uint64]chunkRef) { delete(m, 2) },
|
||||
"a zeroed index still named": func(_ *chunkHead, m map[uint64]chunkRef) { m[4] = other },
|
||||
"an equal-marked index changed": func(_ *chunkHead, m map[uint64]chunkRef) { m[5] = other },
|
||||
"an equal-marked index now nothing": func(_ *chunkHead, m map[uint64]chunkRef) { delete(m, 5) },
|
||||
} {
|
||||
h, m := landedHead()
|
||||
mutate(&h, m)
|
||||
if check(h, m) {
|
||||
t.Errorf("%s: found landed", name)
|
||||
}
|
||||
}
|
||||
// A replay of the identical proposal: whichever copy won, cur is the same.
|
||||
h1, m1 := landedHead()
|
||||
h1.Gen = 9 // the re-proposal landed one generation later
|
||||
if !check(h1, m1) {
|
||||
t.Fatal("a replay of the identical proposal is not found landed")
|
||||
}
|
||||
// A zero chunk marked equal to an absent base: cur naming nothing there
|
||||
// is landed; cur naming a reference there is not.
|
||||
h2, m2 := landedHead()
|
||||
if _, named := m2[6]; named || !check(h2, m2) {
|
||||
t.Fatal("a zero chunk marked equal to an absent base: cur absent is not found landed")
|
||||
}
|
||||
m2[6] = other
|
||||
if check(h2, m2) {
|
||||
t.Fatal("a zero chunk marked equal to an absent base: cur naming a reference is found landed")
|
||||
}
|
||||
}
|
||||
|
||||
// On the v1.1 format a commit whose reply was lost settles by change: HEAD
|
||||
// names the cut's change and its marks, so it landed, although an index the
|
||||
// cut neither changed nor captured names something else there (that index
|
||||
// is not part of this proposal). The full comparison would call it a HEAD
|
||||
// that moved past the commit and refuse the cut.
|
||||
func TestV11LostCommitReplySettlesByChange(t *testing.T) {
|
||||
withV11Format(t)
|
||||
s, _ := v11Store(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := v11Attach(t, s, f)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
w.write(t, s, 9*ctChunkBlocks, 0x99)
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !l.commitByChange() {
|
||||
t.Fatal("setup: the layer does not commit by change")
|
||||
}
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x23)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casAppliedLost}
|
||||
f.afterCAS = func(f *fakeChunkRemote) { f.head.Chunks[9] = f.head.Chunks[2] }
|
||||
f.mu.Unlock()
|
||||
res, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatalf("a landed commit by change whose reply was lost: %v", err)
|
||||
}
|
||||
cur, err := f.GetHead(ctTimeout(t)) // HEAD as read back (the hook changed it after the install)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Head.Gen != cur.Gen || cur.Chunks[9] != cur.Chunks[2] {
|
||||
t.Fatal("the settled HEAD is not the one read back")
|
||||
}
|
||||
l.stMu.Lock()
|
||||
got9 := l.headChunk(9)
|
||||
l.stMu.Unlock()
|
||||
if got9 != cur.Chunks[9] {
|
||||
t.Fatal("the layer did not install the HEAD it read back")
|
||||
}
|
||||
}
|
||||
|
||||
// On the v1.1 format a cut copies HEAD's chunks for its candidates only: its
|
||||
// base names those (at S and at S/16 chunks alike), and a landed commit
|
||||
// changes HEAD in place, its changed chunks only (a mark planted at an
|
||||
// unchanged index survives it, where a whole install would replace it), with
|
||||
// no flat map: the ref table is HEAD's chunks and equals the remote's.
|
||||
func TestV11CutCopiesOnlyItsCandidates(t *testing.T) {
|
||||
withV11Format(t)
|
||||
s, _ := v11Store(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := v11Attach(t, s, f)
|
||||
w := newWriteLog()
|
||||
for c := uint32(0); c < 4; c++ {
|
||||
w.write(t, s, c*ctChunkBlocks, byte(0x40+c))
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
planted := chunkRef{Key: "planted", Encoding: "full"}
|
||||
l.stMu.Lock()
|
||||
real3, _ := l.headRef(3)
|
||||
setHeadChunkForTest(l, 3, planted) // chunk 3 is not in the next cut
|
||||
l.stMu.Unlock()
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x77)
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
got3, _ := l.headRef(3)
|
||||
setHeadChunkForTest(l, 3, real3)
|
||||
whole, flat := l.wholeHeadLocked(), l.head.Chunks
|
||||
l.stMu.Unlock()
|
||||
if got3 != planted {
|
||||
t.Fatal("a landed commit by change reinstalled HEAD whole instead of changing its changed chunks")
|
||||
}
|
||||
if flat != nil {
|
||||
t.Fatalf("the layer keeps a flat map of %d chunks beside the ref table", len(flat))
|
||||
}
|
||||
remote, err := f.GetHead(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(whole.Chunks, remote.Chunks) {
|
||||
t.Fatalf("HEAD changed in place is not the remote's: %d chunks, remote %d", len(whole.Chunks), len(remote.Chunks))
|
||||
}
|
||||
for _, s := range []uint64{16384, 16384 / 16} {
|
||||
h := chunkHead{Gen: 5, Epoch: 1, Holder: "h", Chunks: make(map[uint64]chunkRef, s)}
|
||||
for i := uint64(0); i < s; i++ {
|
||||
h.Chunks[i] = chunkRef{Key: fmt.Sprintf("k%d", i), Encoding: "full"}
|
||||
}
|
||||
l.stMu.Lock()
|
||||
saved := l.head
|
||||
l.setHeadLocked(h)
|
||||
base := l.cutBaseLocked(map[uint64]bool{3: true, 9: true, s + 1: true}) // s+1: a candidate HEAD names nothing at
|
||||
l.setHeadLocked(saved)
|
||||
l.stMu.Unlock()
|
||||
if len(base.Chunks) != 2 || base.Chunks[3] != h.Chunks[3] || base.Chunks[9] != h.Chunks[9] || base.Gen != 5 || base.Holder != "h" {
|
||||
t.Fatalf("S=%d: the cut's base holds %d chunks (want its 2 named candidates) and identity gen %d holder %q", s, len(base.Chunks), base.Gen, base.Holder)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (l *chunkLayerImpl) openChunkRecordV11() (*chunkRecordShadow, error) {
|
||||
// the pages are valid through it).
|
||||
_, err := s.Sync()
|
||||
if err == nil {
|
||||
seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, zero: l.zeroChunkSum()}
|
||||
seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, ref: l.headRef, zero: l.zeroChunkSum()}
|
||||
err = upgradeChunkRecordSeeded(l.ctx, s, epoch, seed, l.attachProgress.add)
|
||||
}
|
||||
if h := testAfterChunkRecordUpgrade; h != nil {
|
||||
|
||||
@@ -26,6 +26,11 @@ func chunkRecordStateCode(k chunkkernel.Kind) (uint8, error) {
|
||||
return 0, fmt.Errorf("storage: chunk record: no code for kernel state %q", k)
|
||||
}
|
||||
|
||||
// kindByCode is chunkRecordKind for a code the runtime itself stored (every
|
||||
// one valid): the record keeps each chunk's state as its one-byte page code,
|
||||
// not the kernel's string (16 B a chunk; r2.735).
|
||||
var kindByCode = [6]chunkkernel.Kind{1: chunkkernel.Absent, 2: chunkkernel.Partial, 3: chunkkernel.Unknown, 4: chunkkernel.HashUnpublished, 5: chunkkernel.HashPublished}
|
||||
|
||||
func chunkRecordKind(code uint8) (chunkkernel.Kind, error) {
|
||||
switch code {
|
||||
case 1:
|
||||
@@ -124,7 +129,7 @@ type chunkRecordRuntime struct {
|
||||
|
||||
pubMu sync.Mutex // see PAGES ARE PUBLISHED IN ORDER
|
||||
mu sync.Mutex
|
||||
kinds []chunkkernel.Kind
|
||||
kinds []uint8 // each chunk's state as its page code (kindByCode)
|
||||
hashes [][32]byte
|
||||
// per segment
|
||||
valid []uint64 // the position its page was last written valid through
|
||||
@@ -148,10 +153,17 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u
|
||||
}
|
||||
r := &chunkRecordRuntime{dir: dir, chunks: chunks, epoch: epoch, appliedPos: appliedPos,
|
||||
maxEntries: 1000, maxAge: time.Minute,
|
||||
kinds: append([]chunkkernel.Kind(nil), kinds...), hashes: append([][32]byte(nil), hashes...),
|
||||
kinds: make([]uint8, chunks), hashes: append([][32]byte(nil), hashes...),
|
||||
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}
|
||||
for c, k := range kinds {
|
||||
code, err := chunkRecordStateCode(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.kinds[c] = code
|
||||
}
|
||||
now := time.Now()
|
||||
for seg, changed := range changedAtOpen {
|
||||
if changed {
|
||||
@@ -165,7 +177,7 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u
|
||||
func (r *chunkRecordRuntime) Kind(chunk uint64) chunkkernel.Kind {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.kinds[chunk]
|
||||
return kindByCode[r.kinds[chunk]]
|
||||
}
|
||||
|
||||
// Apply runs one kernel event on a chunk. hash is the evidence the event
|
||||
@@ -190,17 +202,18 @@ func (r *chunkRecordRuntime) ApplyIf(chunk uint64, ev chunkkernel.Event, argFor
|
||||
r.mu.Unlock()
|
||||
return chunkkernel.None, false, fmt.Errorf("storage: chunk record: chunk %d out of range", chunk)
|
||||
}
|
||||
if cond != nil && !cond(r.kinds[chunk]) {
|
||||
if cond != nil && !cond(kindByCode[r.kinds[chunk]]) {
|
||||
r.mu.Unlock()
|
||||
return chunkkernel.None, false, nil
|
||||
}
|
||||
eff, err = r.applyLocked(chunk, ev, argFor(r.kinds[chunk]), hash)
|
||||
eff, err = r.applyLocked(chunk, ev, argFor(kindByCode[r.kinds[chunk]]), hash)
|
||||
return eff, err == nil, err
|
||||
}
|
||||
|
||||
// applyLocked steps the kernel with r.mu held and releases it.
|
||||
func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg chunkkernel.Arg, hash *[32]byte) (chunkkernel.Effect, error) {
|
||||
res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: r.kinds[chunk]}, ev, arg)
|
||||
cur := kindByCode[r.kinds[chunk]]
|
||||
res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: cur}, ev, arg)
|
||||
if err != nil {
|
||||
r.mu.Unlock()
|
||||
return chunkkernel.None, err
|
||||
@@ -232,13 +245,18 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg
|
||||
if r.unmarked == nil {
|
||||
r.unmarked = map[uint64]chunkkernel.Kind{}
|
||||
}
|
||||
r.unmarked[chunk] = r.kinds[chunk] // A or P
|
||||
r.unmarked[chunk] = cur // A or P
|
||||
} else if held && res.State.Kind == chunkkernel.Absent {
|
||||
delete(r.unmarked, chunk) // an evict: nothing local is claimed
|
||||
}
|
||||
}
|
||||
if res.State.Kind != r.kinds[chunk] || newHash != r.hashes[chunk] {
|
||||
r.kinds[chunk], r.hashes[chunk] = res.State.Kind, newHash
|
||||
if res.State.Kind != cur || newHash != r.hashes[chunk] {
|
||||
code, err := chunkRecordStateCode(res.State.Kind)
|
||||
if err != nil {
|
||||
r.mu.Unlock()
|
||||
return chunkkernel.None, err
|
||||
}
|
||||
r.kinds[chunk], r.hashes[chunk] = code, newHash
|
||||
if r.dirtyVer[seg] == r.writtenVer[seg] {
|
||||
r.since[seg], r.firstDirty[seg] = r.appliedPos(), time.Now()
|
||||
}
|
||||
@@ -401,7 +419,7 @@ func (r *chunkRecordRuntime) writeSegmentLocked(seg uint64) error {
|
||||
p := &chunkRecordPage{Segment: seg, ValidThrough: pos, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(r.chunks, seg))}
|
||||
for i := range p.Entries {
|
||||
c := seg*chunkRecordSegment + uint64(i)
|
||||
k, h := r.kinds[c], r.hashes[c]
|
||||
k, h := kindByCode[r.kinds[c]], r.hashes[c]
|
||||
if held, ok := r.unmarked[c]; ok { // a fill not yet durable in the store's bits
|
||||
if held == chunkkernel.Absent && k != chunkkernel.HashPublished {
|
||||
held = chunkkernel.Partial // written since the fill: some blocks are local
|
||||
|
||||
@@ -127,7 +127,7 @@ func newChunkRecordShadow(l *chunkLayerImpl) (*chunkRecordShadow, error) {
|
||||
default:
|
||||
kinds[i] = chunkkernel.HashPublished
|
||||
hashes[i] = zero
|
||||
if ref, ok := l.head.Chunks[i]; ok {
|
||||
if ref, ok := l.headRef(i); ok {
|
||||
hashes[i] = ref.SHA256
|
||||
}
|
||||
}
|
||||
@@ -346,7 +346,7 @@ func (s *chunkRecordShadow) openedChangedLocked(chunk uint64, k chunkkernel.Kind
|
||||
// again; the record remembers it (an exemption the checker names). The
|
||||
// caller (the barrier check's skip) holds the record's lock.
|
||||
func (s *chunkRecordShadow) openedCleanRecLocked(chunk uint64) bool {
|
||||
return s.v11 && s.version != nil && s.version(chunk) == 0 && s.rec.kinds[chunk] == chunkkernel.HashPublished
|
||||
return s.v11 && s.version != nil && s.version(chunk) == 0 && kindByCode[s.rec.kinds[chunk]] == chunkkernel.HashPublished
|
||||
}
|
||||
|
||||
// scratchHoldsLocked reports whether a P chunk's scratch-cut exemption
|
||||
@@ -367,14 +367,15 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat
|
||||
func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) {
|
||||
s.rec.mu.Lock()
|
||||
for idx := range engine {
|
||||
if !isRecordCandidate(s.rec.kinds[idx]) && !skip(idx) {
|
||||
if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) {
|
||||
miss = append(miss, idx)
|
||||
}
|
||||
}
|
||||
if withExtra || (shadowFindings != nil && proceeds) { // tests only: O(chunks), never at a production barrier
|
||||
s.mu.Lock()
|
||||
s.fullScans++
|
||||
for idx, k := range s.rec.kinds {
|
||||
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) {
|
||||
extra = append(extra, uint64(idx))
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) {
|
||||
t.Fatalf("an unraced fill: %s, want HP", k)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
want := l.head.Chunks[3].SHA256
|
||||
want := l.headChunk(3).SHA256
|
||||
l.stMu.Unlock()
|
||||
l.shadow.rec.mu.Lock()
|
||||
got := l.shadow.rec.hashes[3]
|
||||
@@ -426,7 +426,7 @@ func TestShadowRecoverChangesOnlyTheRecoveredChunks(t *testing.T) {
|
||||
// Forget the write in the record only, as if its event were lost: only
|
||||
// Recover's event can bring the chunk back.
|
||||
l.shadow.rec.mu.Lock()
|
||||
l.shadow.rec.kinds[1] = chunkkernel.HashPublished
|
||||
l.shadow.rec.kinds[1] = 5 // HP
|
||||
l.shadow.rec.mu.Unlock()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -195,7 +195,10 @@ type ChunkCleanStop struct {
|
||||
type upgradeSeed struct {
|
||||
proof *ChunkCleanStop
|
||||
head chunkHead
|
||||
zero [32]byte
|
||||
// ref reads HEAD's chunks (the layer's ref table on the v1.1 format,
|
||||
// where head lists none); nil: head.Chunks.
|
||||
ref func(idx uint64) (chunkRef, bool)
|
||||
zero [32]byte
|
||||
}
|
||||
|
||||
// seedsLineage is the seed's lineage condition (the model's SameEpoch, by
|
||||
@@ -232,9 +235,12 @@ func cleanStopHashes(seed *upgradeSeed, pos uint64) func(uint64) [32]byte {
|
||||
return nil
|
||||
}
|
||||
log.Printf("level=INFO storage: chunk record upgrade: clean-stop seed at %d: whole local chunks take HEAD's hash", pos)
|
||||
head, zero := seed.head, seed.zero
|
||||
ref, zero := seed.ref, seed.zero
|
||||
if ref == nil {
|
||||
ref = headLookup(seed.head)
|
||||
}
|
||||
return func(chunk uint64) [32]byte {
|
||||
if ref, ok := head.Chunks[chunk]; ok {
|
||||
if ref, ok := ref(chunk); ok {
|
||||
return ref.SHA256
|
||||
}
|
||||
return zero
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// errRefBeyondVolume refuses a reference at an index the volume does not
|
||||
// have: a malformed HEAD, which the attach refuses, never trims.
|
||||
var errRefBeyondVolume = errors.New("storage: chunk reference beyond the volume")
|
||||
|
||||
// refTable is the holder's copy of the references HEAD names, one entry a
|
||||
// chunk, in fixed width (r2.777): what the flat chunk map held, without a
|
||||
// per-entry key string or map overhead. It sits behind a narrow interface
|
||||
// (Get, Set, Delete, FillSegment, Len) so that a paged form can replace it
|
||||
// without touching its readers.
|
||||
//
|
||||
// An entry is the chunk's identity as the layout names it: its index (the
|
||||
// position), its full SHA-256, and its owner. A canonical reference's key is
|
||||
// "<owner prefix><index>-<hex sha256>" (the layout remote's form: the prefix
|
||||
// is "layout:<owner>:<owner id>:"), so the entry keeps only the SHA-256 and
|
||||
// an index into the interned owner prefixes, and Get derives the key. A
|
||||
// reference of any other shape (another remote's opaque key, an encoding
|
||||
// other than "full") is kept whole in a side map, so nothing is lost: the
|
||||
// table is exact for every remote, and compact for the layout's.
|
||||
type refTable struct {
|
||||
sums [][32]byte
|
||||
prefix []uint16 // 0: absent; prefixOther: kept in other; else 1 + index into prefixes
|
||||
prefixes []string
|
||||
byPrefix map[string]uint16
|
||||
other map[uint64]chunkRef
|
||||
n int
|
||||
}
|
||||
|
||||
const prefixOther = ^uint16(0)
|
||||
|
||||
// chunkRefs is the narrow interface the layer reads HEAD's references
|
||||
// through (r2.777): a paged form can replace refTable behind it without
|
||||
// touching a reader. Get, Set and Delete are O(1); FillSegment is O(its
|
||||
// range); Len is O(1).
|
||||
type chunkRefs interface {
|
||||
Get(i uint64) (chunkRef, bool)
|
||||
Set(i uint64, ref chunkRef) error
|
||||
Delete(i uint64)
|
||||
FillSegment(first, end uint64, refs map[uint64]chunkRef) error
|
||||
Len() int
|
||||
}
|
||||
|
||||
var _ chunkRefs = (*refTable)(nil)
|
||||
|
||||
func newRefTable(chunks uint64) *refTable {
|
||||
return &refTable{sums: make([][32]byte, chunks), prefix: make([]uint16, chunks), byPrefix: map[string]uint16{}}
|
||||
}
|
||||
|
||||
// Len is the number of chunks the table names.
|
||||
func (t *refTable) Len() int { return t.n }
|
||||
|
||||
// Get returns the reference HEAD names at chunk index i.
|
||||
func (t *refTable) Get(i uint64) (chunkRef, bool) {
|
||||
if i >= uint64(len(t.prefix)) {
|
||||
return chunkRef{}, false
|
||||
}
|
||||
switch p := t.prefix[i]; p {
|
||||
case 0:
|
||||
return chunkRef{}, false
|
||||
case prefixOther:
|
||||
r, ok := t.other[i]
|
||||
return r, ok
|
||||
default:
|
||||
sum := t.sums[i]
|
||||
return chunkRef{Key: t.prefixes[p-1] + strconv.FormatUint(i, 10) + "-" + hex.EncodeToString(sum[:]), SHA256: sum, Encoding: "full"}, true
|
||||
}
|
||||
}
|
||||
|
||||
// canonicalSplit returns the owner prefix of a reference at index i whose key
|
||||
// is "<prefix><i>-<hex sha256>" with the "full" encoding, or false.
|
||||
func canonicalSplit(i uint64, ref chunkRef) (string, bool) {
|
||||
if ref.Encoding != "full" {
|
||||
return "", false
|
||||
}
|
||||
suffix := strconv.FormatUint(i, 10) + "-" + hex.EncodeToString(ref.SHA256[:])
|
||||
if len(ref.Key) <= len(suffix) || ref.Key[len(ref.Key)-len(suffix):] != suffix {
|
||||
return "", false
|
||||
}
|
||||
return ref.Key[:len(ref.Key)-len(suffix)], true
|
||||
}
|
||||
|
||||
// Set names ref at chunk index i; an index beyond the volume is refused.
|
||||
func (t *refTable) Set(i uint64, ref chunkRef) error {
|
||||
if i >= uint64(len(t.prefix)) {
|
||||
return fmt.Errorf("%w: index %d, the volume has %d chunks", errRefBeyondVolume, i, len(t.prefix))
|
||||
}
|
||||
if t.prefix[i] == 0 {
|
||||
t.n++
|
||||
}
|
||||
if p, ok := canonicalSplit(i, ref); ok && len(t.prefixes) < int(prefixOther)-1 {
|
||||
id, seen := t.byPrefix[p]
|
||||
if !seen {
|
||||
t.prefixes = append(t.prefixes, p)
|
||||
id = uint16(len(t.prefixes))
|
||||
t.byPrefix[p] = id
|
||||
}
|
||||
if t.prefix[i] == prefixOther {
|
||||
delete(t.other, i)
|
||||
}
|
||||
t.prefix[i], t.sums[i] = id, ref.SHA256
|
||||
return nil
|
||||
}
|
||||
if t.other == nil {
|
||||
t.other = map[uint64]chunkRef{}
|
||||
}
|
||||
t.prefix[i], t.sums[i] = prefixOther, [32]byte{}
|
||||
t.other[i] = ref
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete makes chunk index i named by nothing (HEAD reads it as zeros).
|
||||
func (t *refTable) Delete(i uint64) {
|
||||
if i >= uint64(len(t.prefix)) || t.prefix[i] == 0 {
|
||||
return
|
||||
}
|
||||
if t.prefix[i] == prefixOther {
|
||||
delete(t.other, i)
|
||||
}
|
||||
t.prefix[i], t.sums[i] = 0, [32]byte{}
|
||||
t.n--
|
||||
}
|
||||
|
||||
// FillSegment makes the chunk range [first, end) of one segment of HEAD
|
||||
// exactly refs (the attach's fill, one segment at a time): an index of the
|
||||
// range refs does not name reads as zeros afterwards, even if an earlier fill
|
||||
// named it (a re-fill never keeps a reference HEAD dropped). A reference
|
||||
// outside the range, or a range beyond the volume, is refused and changes
|
||||
// nothing. O(end - first).
|
||||
func (t *refTable) FillSegment(first, end uint64, refs map[uint64]chunkRef) error {
|
||||
if first > end || end > uint64(len(t.prefix)) {
|
||||
return fmt.Errorf("%w: segment range [%d, %d), the volume has %d chunks", errRefBeyondVolume, first, end, len(t.prefix))
|
||||
}
|
||||
for i := range refs {
|
||||
if i < first || i >= end {
|
||||
return fmt.Errorf("%w: index %d is outside its segment's range [%d, %d)", errRefBeyondVolume, i, first, end)
|
||||
}
|
||||
}
|
||||
for i := first; i < end; i++ {
|
||||
if r, ok := refs[i]; ok {
|
||||
if err := t.Set(i, r); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
t.Delete(i)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fillAll makes the table exactly m (a whole HEAD's references): O(S).
|
||||
// References beyond the volume are dropped here; the attach refuses them
|
||||
// before (a malformed HEAD).
|
||||
func (t *refTable) fillAll(m map[uint64]chunkRef) {
|
||||
for i := range t.prefix {
|
||||
if t.prefix[i] != 0 {
|
||||
t.Delete(uint64(i))
|
||||
}
|
||||
}
|
||||
for i, r := range m {
|
||||
_ = t.Set(i, r)
|
||||
}
|
||||
}
|
||||
|
||||
// each calls f for every named chunk, in index order: O(S), the whole
|
||||
// volume (for the paths that need the whole set, never for a lookup).
|
||||
func (t *refTable) each(f func(i uint64, ref chunkRef)) {
|
||||
for i := range t.prefix {
|
||||
if t.prefix[i] != 0 {
|
||||
r, _ := t.Get(uint64(i))
|
||||
f(uint64(i), r)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The ref table returns exactly the reference it was given, for canonical
|
||||
// layout keys (kept as owner prefix + SHA-256, key derived) and for any other
|
||||
// shape (kept whole): another remote's key, another encoding, a key whose
|
||||
// suffix names another index or hash. Delete and Len follow.
|
||||
func TestRefTableIsExactForEveryReferenceShape(t *testing.T) {
|
||||
tab := newRefTable(16)
|
||||
sum := func(s string) [32]byte { return sha256.Sum256([]byte(s)) }
|
||||
canon := func(owner string, i uint64, s [32]byte) chunkRef {
|
||||
return chunkRef{Key: fmt.Sprintf("layout:%s:309016fbc5b31531e1e7c44585851c7d:%d-%x", owner, i, s), SHA256: s, Encoding: "full"}
|
||||
}
|
||||
refs := map[uint64]chunkRef{
|
||||
0: canon("v1", 0, sum("a")),
|
||||
1: canon("v1", 1, sum("b")),
|
||||
2: canon("src", 2, sum("c")), // a restore source: a second owner prefix
|
||||
3: {Key: "chunks/e1/c3/opaque-1", SHA256: sum("d"), Encoding: "full"},
|
||||
4: {Key: canon("v1", 4, sum("e")).Key, SHA256: sum("e"), Encoding: "zstd"},
|
||||
5: canon("v1", 6, sum("f")), // the key names another index
|
||||
6: {Key: canon("v1", 6, sum("g")).Key, SHA256: sum("h"), Encoding: "full"}, // the key names another hash
|
||||
15: canon("v1", 15, sum("z")),
|
||||
}
|
||||
for i, r := range refs {
|
||||
if err := tab.Set(i, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if tab.Len() != len(refs) {
|
||||
t.Fatalf("Len %d, want %d", tab.Len(), len(refs))
|
||||
}
|
||||
for i := uint64(0); i < 16; i++ {
|
||||
got, ok := tab.Get(i)
|
||||
want, named := refs[i]
|
||||
if ok != named || !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("chunk %d: %+v %v, want %+v %v", i, got, ok, want, named)
|
||||
}
|
||||
}
|
||||
if len(tab.prefixes) != 2 || len(tab.other) != 4 {
|
||||
t.Fatalf("%d owner prefixes, %d whole refs; want 2 and 4 (only the non-canonical kept whole)", len(tab.prefixes), len(tab.other))
|
||||
}
|
||||
// Replacing a whole ref by a canonical one, and the reverse, keeps one entry.
|
||||
_ = tab.Set(3, canon("v1", 3, sum("d2")))
|
||||
_ = tab.Set(0, chunkRef{Key: "opaque", SHA256: sum("x"), Encoding: "full"})
|
||||
if r, _ := tab.Get(3); r != canon("v1", 3, sum("d2")) {
|
||||
t.Fatalf("chunk 3 after a canonical replacement: %+v", r)
|
||||
}
|
||||
if r, _ := tab.Get(0); r.Key != "opaque" {
|
||||
t.Fatalf("chunk 0 after an opaque replacement: %+v", r)
|
||||
}
|
||||
if tab.Len() != len(refs) || len(tab.other) != 4 {
|
||||
t.Fatalf("after replacements: Len %d, %d whole refs; want %d and 4", tab.Len(), len(tab.other), len(refs))
|
||||
}
|
||||
tab.Delete(15)
|
||||
tab.Delete(3)
|
||||
tab.Delete(9) // never named
|
||||
if _, ok := tab.Get(15); ok || tab.Len() != len(refs)-2 {
|
||||
t.Fatalf("after deletes: Len %d", tab.Len())
|
||||
}
|
||||
if _, ok := tab.Get(99); ok {
|
||||
t.Fatal("an index beyond the volume is named")
|
||||
}
|
||||
}
|
||||
|
||||
// heldAfterSourceDropped is the heap per chunk that build's result holds
|
||||
// once the HEAD it was built from is gone: the source is allocated after the
|
||||
// first reading and dropped before the second, so whatever the result still
|
||||
// references of it (an aliased key string) is charged to the result.
|
||||
func heldAfterSourceDropped(chunks uint64, build func(chunkHead) any) float64 {
|
||||
before := heapNow()
|
||||
src := fullHead(chunks, "v1")
|
||||
held := build(src)
|
||||
src = chunkHead{}
|
||||
per := float64(int64(heapNow())-int64(before)) / float64(chunks)
|
||||
runtime.KeepAlive(held)
|
||||
return per
|
||||
}
|
||||
|
||||
// The table's held heap at the 1 TiB chunk count with canonical keys: at
|
||||
// most 40 B per chunk (32 B SHA-256 + a 2 B owner index, and the slices'
|
||||
// headers), against the flat map's ~287 B with its keys. The source HEAD is
|
||||
// dropped before the reading, so a table that aliased its keys instead of
|
||||
// holding its own bytes would be charged for them: the control, a shallow
|
||||
// copy of the flat map (which shares the source's key strings), measures
|
||||
// well above the bound by the same method.
|
||||
func TestRefTableSpaceAt1TiBChunkCount(t *testing.T) {
|
||||
const chunks = 262144
|
||||
var tab *refTable
|
||||
per := heldAfterSourceDropped(chunks, func(h chunkHead) any {
|
||||
tab = newRefTable(chunks)
|
||||
if err := tab.FillSegment(0, chunks, h.Chunks); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tab
|
||||
})
|
||||
t.Logf("ref table: %.1f B/chunk at %d chunks (%d owner prefix)", per, chunks, len(tab.prefixes))
|
||||
if per > 40 || tab.Len() != chunks || len(tab.other) != 0 {
|
||||
t.Fatalf("ref table %.1f B/chunk, %d named, %d whole; want <= 40, %d, 0", per, tab.Len(), len(tab.other), chunks)
|
||||
}
|
||||
aliased := heldAfterSourceDropped(chunks, func(h chunkHead) any { return copyHead(h) })
|
||||
t.Logf("control, a shallow flat-map copy aliasing the source's keys: %.1f B/chunk", aliased)
|
||||
if aliased <= 40 {
|
||||
t.Fatalf("the control measured %.1f B/chunk: the method would not see aliased keys", aliased)
|
||||
}
|
||||
}
|
||||
|
||||
// A segment's fill makes its range exactly the refs given: a re-fill drops a
|
||||
// reference the new HEAD no longer names (it reads as zeros), and leaves the
|
||||
// other segments alone. A reference beyond the volume, outside the segment's
|
||||
// range, or a range beyond the volume is refused and changes nothing.
|
||||
func TestRefTableFillReplacesItsSegmentAndRefusesOutOfRange(t *testing.T) {
|
||||
tab := newRefTable(20)
|
||||
ref := func(i uint64, tag string) chunkRef {
|
||||
s := sha256.Sum256([]byte(tag))
|
||||
return chunkRef{Key: fmt.Sprintf("layout:v1:0011:%d-%x", i, s), SHA256: s, Encoding: "full"}
|
||||
}
|
||||
if err := tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a"), 2: ref(2, "b")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tab.FillSegment(10, 20, map[uint64]chunkRef{15: ref(15, "c")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// HEAD now names chunk 1 again and no longer chunk 2.
|
||||
if err := tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a2")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := tab.Get(2); ok {
|
||||
t.Fatal("a re-fill kept a reference the new HEAD dropped")
|
||||
}
|
||||
if r, _ := tab.Get(1); r != ref(1, "a2") {
|
||||
t.Fatalf("chunk 1 after the re-fill: %+v", r)
|
||||
}
|
||||
if r, ok := tab.Get(15); !ok || r != ref(15, "c") || tab.Len() != 2 {
|
||||
t.Fatalf("another segment changed: %+v %v, Len %d", r, ok, tab.Len())
|
||||
}
|
||||
before := tab.Len()
|
||||
for name, err := range map[string]error{
|
||||
"Set beyond the volume": tab.Set(20, ref(20, "x")),
|
||||
"a ref outside its segment": tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a3"), 12: ref(12, "y")}),
|
||||
"a segment beyond the volume": tab.FillSegment(10, 30, nil),
|
||||
} {
|
||||
if !errors.Is(err, errRefBeyondVolume) {
|
||||
t.Fatalf("%s: %v; want errRefBeyondVolume", name, err)
|
||||
}
|
||||
}
|
||||
if r, _ := tab.Get(1); r != ref(1, "a2") || tab.Len() != before {
|
||||
t.Fatal("a refused fill changed the table")
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -130,7 +129,13 @@ func TestSpaceMeasurementControls(t *testing.T) {
|
||||
long := strings.Repeat("v", 101) // a 100-byte longer owner name
|
||||
longer := heldPerChunk(t, chunks, 1, long)
|
||||
t.Logf("held per chunk with keys 100 B longer: %.0f B (+%.0f)", longer, longer-geo[1])
|
||||
if longer-geo[1] < 60 || longer-geo[1] > 160 {
|
||||
if chunkV11Format {
|
||||
// The ref table derives canonical keys from an interned owner prefix:
|
||||
// a longer owner name costs once, not per chunk.
|
||||
if d := longer - geo[1]; d > 10 || d < -10 {
|
||||
t.Fatalf("keys 100 B longer moved the ref table's held heap by %.0f B/chunk, want about 0 (owner prefix interned)", d)
|
||||
}
|
||||
} else if longer-geo[1] < 60 || longer-geo[1] > 160 {
|
||||
t.Fatalf("keys 100 B longer moved the held heap by %.0f B/chunk, want about 100", longer-geo[1])
|
||||
}
|
||||
}
|
||||
@@ -139,9 +144,10 @@ func TestSpaceMeasurementControls(t *testing.T) {
|
||||
// chunk for a 1 TiB volume's chunk count (262,144; one-block chunks, which
|
||||
// TestSpaceMeasurementControls shows stand for 4 MiB ones), every chunk
|
||||
// named by HEAD with canonical keys owned by the layer, after GC once the
|
||||
// layer is attached. With CHUNK_SPACE_RED=1 it asserts the target, at most
|
||||
// 200 B per chunk, which fails until PR 4 drops the flat map.
|
||||
// layer is attached, on the v1.1 format (the layer keeps HEAD's chunks in
|
||||
// the ref table, no flat map): at most 200 B per chunk.
|
||||
func TestSpacePerChunkAt1TiBShape(t *testing.T) {
|
||||
withV11Format(t)
|
||||
const chunks = 262144
|
||||
m0 := heapNow()
|
||||
oneMap := fullHead(chunks, "v1")
|
||||
@@ -151,8 +157,8 @@ func TestSpacePerChunkAt1TiBShape(t *testing.T) {
|
||||
per := heldPerChunk(t, chunks, 1, "v1")
|
||||
t.Logf("SPACE at 1 TiB's chunk count (%d chunks, v1.1 format %v, canonical %d-byte keys): %.0f B/chunk held after attach; one flat map with its keys is %.0f B/chunk",
|
||||
chunks, chunkV11Format, len(canonicalKey("v1", "309016fbc5b31531e1e7c44585851c7d", chunks-1, [32]byte{})), per, flat)
|
||||
if os.Getenv("CHUNK_SPACE_RED") == "1" && per > 200 {
|
||||
t.Fatalf("SPACE red: %.0f B/chunk, want at most 200", per)
|
||||
if per > 200 {
|
||||
t.Fatalf("SPACE: %.0f B/chunk held, want at most 200", per)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build swblock_v11_format
|
||||
|
||||
package storage
|
||||
|
||||
// chunkV11FormatBuild is true in a build with the swblock_v11_format tag: the
|
||||
// draft v1.1 store format is exercised on lab volumes. Never a release build
|
||||
// (CI refuses the tag in every image and release build). It is independent of
|
||||
// swblock_lab_bigvol, which lifts only the create cap.
|
||||
const chunkV11FormatBuild = true
|
||||
@@ -1,8 +0,0 @@
|
||||
//go:build swblock_lab_bigvol
|
||||
|
||||
package storage
|
||||
|
||||
// chunkV11FormatBuild is true in a lab build: the draft v1.1 store format is
|
||||
// exercised on lab volumes. Never a release build (CI refuses the tag in
|
||||
// every image and release build).
|
||||
const chunkV11FormatBuild = true
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !swblock_lab_bigvol
|
||||
//go:build !swblock_v11_format
|
||||
|
||||
package storage
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
|
||||
)
|
||||
|
||||
// The draft v1.1 format follows its own tag (swblock_v11_format) alone: the
|
||||
// lab cap tag (swblock_lab_bigvol) does not turn it on, and a build that runs
|
||||
// it names itself in its revision (the image refusal keys on that). CI runs
|
||||
// this with no tag, with each tag alone and with both.
|
||||
func TestV11FormatFollowsItsOwnTagAlone(t *testing.T) {
|
||||
if chunkV11FormatBuild != buildinfo.V11FormatDraft {
|
||||
t.Fatalf("v1.1 format %v, but the build's format tag says %v (cap tag %v)", chunkV11FormatBuild, buildinfo.V11FormatDraft, geometry.LabBigVolume)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// v11ReportLayer is a v1.1 layer over a fake remote with chunks 0 and 1
|
||||
// published, recording every publication report from then on.
|
||||
func v11ReportLayer(t *testing.T) (*WALStore, *fakeChunkRemote, *chunkLayerImpl, *writeLog, func() [][2]chunkHead) {
|
||||
t.Helper()
|
||||
withV11Format(t)
|
||||
s, _ := v11Store(t)
|
||||
f := newFakeChunkRemote()
|
||||
l := v11Attach(t, s, f)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 0, 0x10)
|
||||
w.write(t, s, ctChunkBlocks, 0x11)
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var got [][2]chunkHead
|
||||
l.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) {
|
||||
mu.Lock()
|
||||
got = append(got, [2]chunkHead{prev, next})
|
||||
mu.Unlock()
|
||||
}
|
||||
return s, f, l, w, func() [][2]chunkHead { mu.Lock(); defer mu.Unlock(); return append([][2]chunkHead(nil), got...) }
|
||||
}
|
||||
|
||||
// checkReportedWhole: the first report after the hook went on names the
|
||||
// remote's HEAD before the settled one as prev, whole, and the settled one
|
||||
// as next, whole.
|
||||
func checkReportedWhole(t *testing.T, f *fakeChunkRemote, reports [][2]chunkHead) {
|
||||
t.Helper()
|
||||
if len(reports) == 0 {
|
||||
t.Fatal("the settlement reported no publication")
|
||||
}
|
||||
prev, next := reports[0][0], reports[0][1]
|
||||
heads := f.installedHeads()
|
||||
var before, settled chunkHead
|
||||
for _, h := range heads {
|
||||
if h.Gen == next.Gen {
|
||||
settled = h
|
||||
}
|
||||
if h.Gen == prev.Gen {
|
||||
before = h
|
||||
}
|
||||
}
|
||||
if len(before.Chunks) == 0 || !reflect.DeepEqual(prev.Chunks, before.Chunks) {
|
||||
t.Fatalf("the report's prev (gen %d) names %d chunks; the remote's HEAD then named %d", prev.Gen, len(prev.Chunks), len(before.Chunks))
|
||||
}
|
||||
if !reflect.DeepEqual(next.Chunks, settled.Chunks) {
|
||||
t.Fatalf("the report's next (gen %d) names %d chunks; the remote's HEAD names %d", next.Gen, len(next.Chunks), len(settled.Chunks))
|
||||
}
|
||||
}
|
||||
|
||||
// On the v1.1 format, where the layer's HEAD keeps no chunk map, every
|
||||
// settlement that installs a HEAD read whole reports the previous image
|
||||
// whole, from the ref table: a lost reply read back, a re-proposal read
|
||||
// back, a detach settled.
|
||||
func TestV11SettlementsReportTheWholePreviousImage(t *testing.T) {
|
||||
t.Run("lost reply read back", func(t *testing.T) {
|
||||
s, f, l, w, reports := v11ReportLayer(t)
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casAppliedLost}
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkReportedWhole(t, f, reports())
|
||||
})
|
||||
t.Run("re-proposal read back", func(t *testing.T) {
|
||||
s, f, l, w, reports := v11ReportLayer(t)
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casUnknownNotApplied, casAppliedLost}
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
|
||||
t.Fatalf("cut with an unknown outcome: %v", err)
|
||||
}
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("settling cut: %v", err)
|
||||
}
|
||||
checkReportedWhole(t, f, reports())
|
||||
})
|
||||
t.Run("detach settled", func(t *testing.T) {
|
||||
s, f, l, w, reports := v11ReportLayer(t)
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casAppliedLost}
|
||||
f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown }
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
|
||||
t.Fatalf("detach with an unresolved CAS: %v", err)
|
||||
}
|
||||
healRemote(f)
|
||||
if settled, _, err := l.SettleDetach(ctTimeout(t)); err != nil || settled != detachApplied {
|
||||
t.Fatalf("SettleDetach: %v %v, want applied", settled, err)
|
||||
}
|
||||
checkReportedWhole(t, f, reports())
|
||||
})
|
||||
}
|
||||
|
||||
// On the v1.1 format every outcome reports and keeps HEAD's identity only:
|
||||
// a no-op cut, a lost reply read back, a detach and its repeat, a settled
|
||||
// detach; a detached layer holds no chunk map.
|
||||
func TestV11OutcomesKeepNoChunkMap(t *testing.T) {
|
||||
noMap := func(t *testing.T, what string, h chunkHead) {
|
||||
t.Helper()
|
||||
if h.Gen == 0 || h.Chunks != nil || h.Segments != nil {
|
||||
t.Fatalf("%s: gen %d, %d chunks, %d segments; want HEAD's identity only", what, h.Gen, len(h.Chunks), len(h.Segments))
|
||||
}
|
||||
}
|
||||
t.Run("no-op and read back", func(t *testing.T) {
|
||||
s, f, l, w, _ := v11ReportLayer(t)
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil || !r.Noop {
|
||||
t.Fatalf("no-op cut: %+v %v", r, err)
|
||||
}
|
||||
noMap(t, "a no-op cut", r.Head)
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casAppliedLost}
|
||||
f.mu.Unlock()
|
||||
if r, err = l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noMap(t, "a lost reply read back", r.Head)
|
||||
})
|
||||
t.Run("detach", func(t *testing.T) {
|
||||
_, _, l, _, _ := v11ReportLayer(t)
|
||||
r, err := l.Detach(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noMap(t, "a detach", r.Head)
|
||||
again, err := l.Detach(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noMap(t, "a repeated detach", again.Head)
|
||||
l.stMu.Lock()
|
||||
kept := l.detached.Head
|
||||
l.stMu.Unlock()
|
||||
noMap(t, "the detached layer's kept result", kept)
|
||||
})
|
||||
t.Run("detach settled", func(t *testing.T) {
|
||||
s, f, l, w, _ := v11ReportLayer(t)
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
f.mu.Lock()
|
||||
f.casModes = []fakeCASMode{casAppliedLost}
|
||||
f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown }
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
|
||||
t.Fatalf("detach with an unresolved CAS: %v", err)
|
||||
}
|
||||
healRemote(f)
|
||||
_, r, err := l.SettleDetach(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noMap(t, "a settled detach", r.Head)
|
||||
l.stMu.Lock()
|
||||
kept := l.detached.Head
|
||||
l.stMu.Unlock()
|
||||
noMap(t, "the settled layer's kept result", kept)
|
||||
})
|
||||
}
|
||||
|
||||
// A no-op cut on the v1.1 format that reads HEAD whole and finds it moved,
|
||||
// at this holder's own identity, to another chunk root is fenced, as on the
|
||||
// v1.0 format: its captured chunks alone (none here) cannot tell that HEAD
|
||||
// no longer names what the layer holds. A HEAD moved with the same root
|
||||
// (only its generation) completes.
|
||||
func TestV11NoOpCutFencesAForeignRootAtItsOwnIdentity(t *testing.T) {
|
||||
t.Run("foreign root", func(t *testing.T) {
|
||||
_, f, l, _, _ := v11ReportLayer(t)
|
||||
f.mu.Lock()
|
||||
f.head = copyChunkHead(f.head)
|
||||
f.head.Gen++
|
||||
f.head.Chunks[0] = f.head.Chunks[1] // HEAD now names another chunk at 0
|
||||
f.mu.Unlock()
|
||||
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) {
|
||||
t.Fatalf("a no-op cut over a foreign root at its own identity: %v, want fenced", err)
|
||||
}
|
||||
})
|
||||
t.Run("same root", func(t *testing.T) {
|
||||
_, f, l, _, _ := v11ReportLayer(t)
|
||||
f.mu.Lock()
|
||||
f.head = copyChunkHead(f.head)
|
||||
f.head.Gen++
|
||||
f.mu.Unlock()
|
||||
if r, err := l.Cut(ctTimeout(t)); err != nil || !r.Noop {
|
||||
t.Fatalf("a no-op cut over the same root at a newer generation: %+v %v, want a no-op", r, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// unresolvedV11Detach is a v1.1 layer with chunk 0 published and a detach
|
||||
// (writing chunk 2) whose CAS by change was lost before it applied: HEAD
|
||||
// is still the detach's base, and the outcome is unresolved.
|
||||
func unresolvedV11Detach(t *testing.T) (*chunkLayerImpl, *deltaSpyRemote, chunkHead) {
|
||||
t.Helper()
|
||||
withV11Format(t)
|
||||
s, l, spy := deltaSpyLayer(t)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 0, 0x10)
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base, err := spy.GetHead(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.write(t, s, 2*ctChunkBlocks, 0x22)
|
||||
spy.mu.Lock()
|
||||
spy.lose = true
|
||||
spy.mu.Unlock()
|
||||
if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
|
||||
t.Fatalf("detach with a lost CAS: %v, want an unresolved outcome", err)
|
||||
}
|
||||
return l, spy, base
|
||||
}
|
||||
|
||||
// On the v1.1 format a detach settlement whose detach did not land cancels
|
||||
// it with a commit by change carrying no change, at the detach's base: HEAD
|
||||
// keeps the base's chunks and returns to this holder's active identity. A
|
||||
// cancel that lands is installed in place (the layer stays unfenced and its
|
||||
// table is the remote's HEAD); a cancel whose reply is lost after it applied
|
||||
// is read back and adopted, as before.
|
||||
func TestV11DetachCancelGoesByChangeAndInstallsInPlace(t *testing.T) {
|
||||
settleAndCheck := func(t *testing.T, l *chunkLayerImpl, spy *deltaSpyRemote, base chunkHead) {
|
||||
t.Helper()
|
||||
settled, _, err := l.SettleDetach(ctTimeout(t))
|
||||
if err != nil || settled != detachNotPublished {
|
||||
t.Fatalf("SettleDetach: %v %v, want the detach cancelled (not published)", settled, err)
|
||||
}
|
||||
spy.mu.Lock()
|
||||
last, full := spy.deltas[len(spy.deltas)-1], spy.fullCAS
|
||||
spy.mu.Unlock()
|
||||
if len(last) != 0 || full != 0 {
|
||||
t.Fatalf("the cancel carried %d changes and %d whole-image CASes; want one commit by change with none", len(last), full)
|
||||
}
|
||||
head, err := spy.GetHead(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head.Gen != base.Gen+1 || chunkHeadIsDetached(head) || head.Holder != base.Holder || !reflect.DeepEqual(head.Chunks, base.Chunks) {
|
||||
t.Fatalf("HEAD after the cancel: gen %d detached %v holder %q, %d chunks; want gen %d active with the base's %d chunks", head.Gen, chunkHeadIsDetached(head), head.Holder, len(head.Chunks), base.Gen+1, len(base.Chunks))
|
||||
}
|
||||
l.stMu.Lock()
|
||||
fenced, whole := l.fenced, l.wholeHeadLocked()
|
||||
l.stMu.Unlock()
|
||||
if fenced {
|
||||
t.Fatal("a cancelled detach fenced the layer")
|
||||
}
|
||||
if whole.Gen != head.Gen || !reflect.DeepEqual(whole.Chunks, head.Chunks) {
|
||||
t.Fatalf("the layer's HEAD after the cancel is gen %d with %d chunks; the remote's gen %d with %d", whole.Gen, len(whole.Chunks), head.Gen, len(head.Chunks))
|
||||
}
|
||||
}
|
||||
t.Run("cancel lands", func(t *testing.T) {
|
||||
l, spy, base := unresolvedV11Detach(t)
|
||||
settleAndCheck(t, l, spy, base)
|
||||
})
|
||||
t.Run("cancel reply lost after it applied", func(t *testing.T) {
|
||||
l, spy, base := unresolvedV11Detach(t)
|
||||
spy.fakeChunkRemote.mu.Lock()
|
||||
spy.fakeChunkRemote.casModes = []fakeCASMode{casAppliedLost}
|
||||
spy.fakeChunkRemote.mu.Unlock()
|
||||
settleAndCheck(t, l, spy, base)
|
||||
})
|
||||
}
|
||||
@@ -22,7 +22,7 @@ The design is described in three documents, and this one collects their machines
|
||||
- `INV-WAL-V3-W-MODE-A-001`, `INV-WAL-V3-W-SETWMODE-001`: no production code sets mode A or calls `SetWMode`.
|
||||
- `INV-WAL-V3-RESET-001`, `INV-WAL-V3-RESET-TWO-SLOT-001`, `INV-WAL-V3-RESET-HALF-001`, `INV-WAL-V3-RESET-INVARIANT-001`: no production code starts a reset; an open only detects a half reset.
|
||||
- `INV-PUBLISH-SETTLED-001`: no binary sets `ChunkOnPublishSettled`, so the hook is nil.
|
||||
- `INV-CHUNK-RECORD-V11-001`: the draft v1.1 store format runs only in lab builds and tests (`chunkV11Format`); the row waits for the change that declares the format.
|
||||
- `INV-CHUNK-RECORD-V11-001`: the draft v1.1 store format runs only in builds with the `swblock_v11_format` tag and in tests (`chunkV11Format`), independently of the cap tag `swblock_lab_bigvol` (`TestV11FormatFollowsItsOwnTagAlone`); the row waits for the change that declares the format.
|
||||
- `INV-WAL-V3-BASE-RETIRE-GATE-001`, and the chunk layer's attach over a completed BASE: a BASE is installed only by the replica side of replication, and a chunk volume refuses every replica role, so no production path puts a BASE on a chunk store.
|
||||
|
||||
## Contents
|
||||
@@ -1206,6 +1206,7 @@ Notes:
|
||||
| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `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-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an unwritten object: before its HEAD update it finds present, written by its session or adopted from an earlier one of this volume, the own chunks new against HEAD's current root, every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`); `TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`); also in `core/frontend/chunkstore/layout/commit_test.go` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
|
||||
@@ -7,10 +7,15 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
)
|
||||
|
||||
// LabMarker is in every revision of a lab build (geometry.LabBigVolume): a
|
||||
// published image refuses any binary that reports it
|
||||
// (scripts/refuse-lab-binary.sh, run in each image Dockerfile).
|
||||
const LabMarker = "LAB BUILD(swblock_lab_bigvol)"
|
||||
// LabMarker is in every revision of a lab build (geometry.LabBigVolume), and
|
||||
// V11FormatMarker in every revision of a build with the draft v1.1 store
|
||||
// format (V11FormatDraft): a published image refuses any binary that reports
|
||||
// either (scripts/refuse-lab-binary.sh, run in each image Dockerfile, refuses
|
||||
// "LAB BUILD").
|
||||
const (
|
||||
LabMarker = "LAB BUILD(swblock_lab_bigvol)"
|
||||
V11FormatMarker = "LAB BUILD(swblock_v11_format)"
|
||||
)
|
||||
|
||||
// Version returns a compact provenance string suitable for lab artifacts.
|
||||
func Version(component string) string {
|
||||
@@ -35,8 +40,12 @@ func Revision() string {
|
||||
}
|
||||
}
|
||||
}
|
||||
out := fmt.Sprintf("%s modified=%s", revision, modified)
|
||||
if geometry.LabBigVolume {
|
||||
return fmt.Sprintf("%s modified=%s %s", revision, modified, LabMarker)
|
||||
out += " " + LabMarker
|
||||
}
|
||||
return fmt.Sprintf("%s modified=%s", revision, modified)
|
||||
if V11FormatDraft {
|
||||
out += " " + V11FormatMarker
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -15,3 +15,15 @@ func TestRevisionNamesALabBuild(t *testing.T) {
|
||||
t.Fatalf("lab build %v, revision %q", geometry.LabBigVolume, Revision())
|
||||
}
|
||||
}
|
||||
|
||||
// A build with the draft v1.1 store format names itself in every revision,
|
||||
// independently of the lab cap tag; a release build never does.
|
||||
func TestRevisionNamesADraftFormatBuild(t *testing.T) {
|
||||
has := strings.Contains(Revision(), V11FormatMarker) && strings.Contains(Version("x"), V11FormatMarker)
|
||||
if has != V11FormatDraft {
|
||||
t.Fatalf("draft format build %v, revision %q", V11FormatDraft, Revision())
|
||||
}
|
||||
if strings.Contains(Revision(), LabMarker) != geometry.LabBigVolume {
|
||||
t.Fatalf("the cap tag's marker does not follow the cap tag alone: %q", Revision())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build swblock_v11_format
|
||||
|
||||
package buildinfo
|
||||
|
||||
// V11FormatDraft is true in a build with the swblock_v11_format tag (the
|
||||
// draft v1.1 store format, core/storage chunkV11FormatBuild).
|
||||
const V11FormatDraft = true
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !swblock_v11_format
|
||||
|
||||
package buildinfo
|
||||
|
||||
// V11FormatDraft is false in a release build: the v1.1 store format is not
|
||||
// declared.
|
||||
const V11FormatDraft = false
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# refuse-lab-binary.sh BIN...: refuse to publish a lab build. Each BIN must
|
||||
# answer -version, and its answer must not carry the lab marker
|
||||
# (internal/buildinfo LabMarker, set by the swblock_lab_bigvol tag). A binary
|
||||
# (internal/buildinfo LabMarker or V11FormatMarker, set by the
|
||||
# swblock_lab_bigvol or swblock_v11_format tag; both say "LAB BUILD"). A binary
|
||||
# that cannot answer is refused too (fail closed). Run by every image
|
||||
# Dockerfile right after its go build, so no image holding a lab binary is
|
||||
# built, and so none is pushed.
|
||||
|
||||
Reference in new issue
Block a user