Merge branch 'main' into feat/v5-incremental-build

This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-01 15:35:55 -08:00
commit 2e81e41347
31 files changed
+1577 -79

No files matched your search

@@ -16,6 +16,8 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) {
fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot")
fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked")
fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)")
fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout")
fs.DurationVar(&c.YieldAfter, "host-limit-yield-after", c.YieldAfter, "a normal cut that has held its slot this long gives it to a waiting cut at its next staging batch (keeping what it staged); a lone cut never yields")
fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release")
fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)")
}
+44 -6
View File
@@ -130,7 +130,11 @@ type Publisher struct {
mu sync.Mutex
state map[subKey]assignmentState
subs map[subKey][]*subscription
// replicas indexes state by volume: the replica ids of every key of
// that volume. Kept by setStateLocked, the only writer of state, so a
// per-volume read costs that volume's replicas, not every line.
replicas map[string]map[string]struct{}
subs map[subKey][]*subscription
// P14 S5 — durable authority store. Optional; nil means
// in-memory only (existing behavior, used by tests and
@@ -251,6 +255,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
p := &Publisher{
dir: dir,
state: make(map[subKey]assignmentState),
replicas: map[string]map[string]struct{}{},
subs: make(map[subKey][]*subscription),
writeSeqByVolume: map[string]uint64{},
workspace: map[string]*WorkspaceState{},
@@ -304,7 +309,7 @@ func (p *Publisher) reloadFromStore() {
loaded.info.Primary = *rec.Primary
}
p.captureAssignmentOwner(&loaded.info, rec.Workspace)
p.state[key] = loaded
p.setStateLocked(key, loaded)
if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] {
p.writeSeqByVolume[rec.VolumeID] = rec.WriteSeq
}
@@ -567,7 +572,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
// any slot of the volume holds an authority line, a Bind for
// another slot would mint a second epoch-1 line beside it.
// Moving authority to another slot is IntentReassign.
if bound, ok := boundReplicaForVolume(p.state, ask.VolumeID); ok {
if bound, ok := boundReplicaForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID); ok {
p.mu.Unlock()
return fmt.Errorf("%w: volume %s is already bound to replica %s; use Reassign",
ErrBindAlreadyBound, ask.VolumeID, bound)
@@ -636,7 +641,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
// establishment is the IntentBind path, not this one —
// using Reassign to create a volume's very first binding
// would confuse the per-volume monotonic line.
maxEpoch := maxPublishedEpochForVolume(p.state, ask.VolumeID)
maxEpoch := maxPublishedEpochForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID)
if maxEpoch == 0 {
p.mu.Unlock()
return ErrReassignNotBound
@@ -672,7 +677,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
// planned (after the planned-move guard, no fence), or heal (the
// line's own primary, at this epoch). No path mints one without.
if ask.Evidence.Kind == adapter.PrimaryKindPromotion {
if err := promotionBasisHolds(ask, next.Epoch, p.state, maxEpoch); err != nil {
if err := promotionBasisHolds(ask, next.Epoch, p.volumeStateLocked(ask.VolumeID), maxEpoch); err != nil {
p.mu.Unlock()
return fmt.Errorf("%w: volume %s replica %s: %v", ErrPromotionUnfenced, ask.VolumeID, ask.ReplicaID, err)
}
@@ -737,7 +742,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
p.workspace[ask.VolumeID] = issuedWorkspace
}
p.state[k] = assignmentState{info: next, present: true}
p.setStateLocked(k, assignmentState{info: next, present: true})
if issuedWorkspace != nil {
// The issued move starts the new holder's lease (issuedAt+TTL grant).
p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL))
@@ -771,6 +776,39 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
return nil
}
// setStateLocked records the state of key k and indexes it under its
// volume. It is the only writer of p.state. p.mu held.
func (p *Publisher) setStateLocked(k subKey, st assignmentState) {
p.state[k] = st
r := p.replicas[k.volumeID]
if r == nil {
r = map[string]struct{}{}
p.replicas[k.volumeID] = r
}
r[k.replicaID] = struct{}{}
}
// volumeStateLocked is the state of every key of one volume, read through
// the index: O(replicas of the volume), whatever the number of volumes.
// p.mu held.
func (p *Publisher) volumeStateLocked(volumeID string) map[subKey]assignmentState {
out := make(map[subKey]assignmentState, len(p.replicas[volumeID]))
for r := range p.replicas[volumeID] {
k := subKey{volumeID: volumeID, replicaID: r}
if st, ok := p.state[k]; ok {
out[k] = st
}
}
if check := testLineIndexCheck; check != nil {
check(p, volumeID, out)
}
return out
}
// testLineIndexCheck, set by tests, is called with every per-volume read
// of the index, so the package's tests check the index against the scan.
var testLineIndexCheck func(p *Publisher, volumeID string, got map[subKey]assignmentState)
func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent) {
defer func() {
_ = recover()
@@ -0,0 +1,157 @@
package authority
import (
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// Every per-volume read of the line index, in every test of this package,
// checks the whole index against the whole state, both ways: the read
// equals the scan restricted to its volume, and the index holds exactly the
// keys of the state (no stale extra entry, none missing).
func init() {
testLineIndexCheck = func(p *Publisher, volumeID string, got map[subKey]assignmentState) {
if err := lineIndexMismatch(p, volumeID, got); err != "" {
panic("authority: " + err)
}
}
}
// lineIndexMismatch is "" when the index is exact: got equals the state of
// volumeID's keys, every state key is indexed, and every indexed key is in
// the state.
func lineIndexMismatch(p *Publisher, volumeID string, got map[subKey]assignmentState) string {
want := map[subKey]assignmentState{}
for k, st := range p.state {
if k.volumeID == volumeID {
want[k] = st
}
if _, ok := p.replicas[k.volumeID][k.replicaID]; !ok {
return fmt.Sprintf("line index lacks state key %v", k)
}
}
for v, rs := range p.replicas {
if len(rs) == 0 {
return fmt.Sprintf("line index holds an empty set for volume %q", v)
}
for r := range rs {
if _, ok := p.state[subKey{volumeID: v, replicaID: r}]; !ok {
return fmt.Sprintf("line index holds %s/%s, which the state does not", v, r)
}
}
}
if !reflect.DeepEqual(got, want) {
return fmt.Sprintf("line index read for volume %q is %v, the scan %v", volumeID, got, want)
}
return ""
}
// The exact-membership check catches each way the index can drift: a stale
// extra entry, a missing entry, and an empty volume set.
func TestLineIndexCheckIsExact(t *testing.T) {
saved := testLineIndexCheck
testLineIndexCheck = nil
t.Cleanup(func() { testLineIndexCheck = saved })
p := NewPublisher(nil)
p.mu.Lock()
defer p.mu.Unlock()
st := assignmentState{info: adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1}, present: true}
p.setStateLocked(subKey{volumeID: "v1", replicaID: "r1"}, st)
if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err != "" {
t.Fatalf("green: %s", err)
}
p.replicas["v1"]["r9"] = struct{}{} // stale extra entry
if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" {
t.Error("a stale extra index entry was not caught")
}
delete(p.replicas["v1"], "r9")
p.state[subKey{volumeID: "v2", replicaID: "r1"}] = st // a state key the index lacks
if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" {
t.Error("a missing index entry was not caught")
}
delete(p.state, subKey{volumeID: "v2", replicaID: "r1"})
p.replicas["v3"] = map[string]struct{}{}
if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" {
t.Error("an empty volume set was not caught")
}
}
// A per-volume authority read costs that volume's replicas, not every
// line: reading one volume among 64,000 takes about as long as among
// 1,000 (the scan it replaces grows 64 times).
func TestVolumeAuthorityLineCostIsPerVolume(t *testing.T) {
saved := testLineIndexCheck
testLineIndexCheck = nil // the check itself scans; time the read alone
t.Cleanup(func() { testLineIndexCheck = saved })
perRead := func(volumes int) time.Duration {
p := NewPublisher(nil)
p.mu.Lock()
for i := 0; i < volumes; i++ {
for _, r := range []string{"r1", "r2"} {
p.setStateLocked(subKey{volumeID: fmt.Sprintf("v%06d", i), replicaID: r}, assignmentState{info: adapter.AssignmentInfo{VolumeID: fmt.Sprintf("v%06d", i), ReplicaID: r, Epoch: 1}, present: true})
}
}
p.mu.Unlock()
const reads = 2000
best := time.Duration(1 << 62)
for round := 0; round < 3; round++ {
start := time.Now()
for i := 0; i < reads; i++ {
if _, ok := p.VolumeAuthorityLine(fmt.Sprintf("v%06d", i%volumes)); !ok {
t.Fatal("no line")
}
}
if d := time.Since(start) / reads; d < best {
best = d
}
}
return best
}
small, large := perRead(1000), perRead(64000)
t.Logf("per read: %v at 1,000 volumes, %v at 64,000", small, large)
if large > 8*small+5*time.Microsecond {
t.Fatalf("a read among 64,000 volumes took %v, among 1,000 %v: the read scans every line", large, small)
}
}
// The index is right only while setStateLocked is the one writer of
// p.state: a source scan of the package's non-test files finds every
// assignment to, delete from or replacement of the state map, and fails on
// any outside it (a new writer must keep the index too).
func TestLineIndexHasOneWriter(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
write := regexp.MustCompile(`\bp\.state\[[^\]]*\]\s*=[^=]|\bdelete\(p\.state,|\bp\.state\s*=[^=]`)
var sites []string
for _, f := range files {
if strings.HasSuffix(f, "_test.go") {
continue
}
b, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
inSetter := false
for i, line := range strings.Split(string(b), "\n") {
if strings.HasPrefix(line, "func ") {
inSetter = strings.HasPrefix(line, "func (p *Publisher) setStateLocked(")
}
if write.MatchString(line) && !inSetter {
sites = append(sites, fmt.Sprintf("%s:%d: %s", f, i+1, strings.TrimSpace(line)))
}
}
}
if len(sites) != 0 {
t.Fatalf("p.state is written outside setStateLocked, which keeps the line index:\n%s", strings.Join(sites, "\n"))
}
}
+1 -1
View File
@@ -99,7 +99,7 @@ func (p *Publisher) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool)
func (p *Publisher) volumeLineLocked(volumeID string) (AuthorityBasis, bool) {
var best AuthorityBasis
any := false
for k, st := range p.state {
for k, st := range p.volumeStateLocked(volumeID) {
if !st.present || k.volumeID != volumeID {
continue
}
+2 -2
View File
@@ -379,7 +379,7 @@ func (p *Publisher) WorkspaceSourceMoved(volume, replica, server string) (Publis
func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState, bool) {
var key subKey
var line assignmentState
for k, s := range p.state {
for k, s := range p.volumeStateLocked(volume) {
if k.volumeID == volume && s.present && s.info.Epoch > line.info.Epoch {
key, line = k, s
}
@@ -550,7 +550,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK")
}
}
max := maxPublishedEpochForVolume(p.state, q.VolumeID)
max := maxPublishedEpochForVolume(p.volumeStateLocked(q.VolumeID), q.VolumeID)
for _, r := range s.Moves {
if r.NewEpoch > max {
max = r.NewEpoch
@@ -0,0 +1,77 @@
package durable
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// slotYieldingLayer admits each cut through the budget (consuming its ticket);
// its first two attempts yield their slot, every later one succeeds. It
// reports nothing staged, so nothing but the yield rule can excuse a backoff.
type slotYieldingLayer struct {
storage.ChunkLayer // unused methods panic
budget storage.Budget
cuts atomic.Int32
mu sync.Mutex
at []time.Time
}
func (l *slotYieldingLayer) Fenced() bool { return false }
func (l *slotYieldingLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} }
func (l *slotYieldingLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) {
l.mu.Lock()
l.at = append(l.at, time.Now())
l.mu.Unlock()
n := l.cuts.Add(1)
id, err := l.budget.Admit(ctx, 1, nil)
if err != nil {
return storage.ChunkCutResult{}, err
}
l.budget.Release(id)
if n <= 2 {
return storage.ChunkCutResult{}, storage.ErrCutYielded
}
return storage.ChunkCutResult{}, nil
}
// A yielded attempt is not a failure: no backoff, it tries again at the next
// poll (on a ticket at the back, as any admitted attempt that did not
// succeed), and status counts it apart.
func TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart(t *testing.T) {
b := newRecordingBudget(t)
layer := &slotYieldingLayer{budget: b}
wait := &cutWaitSlot{}
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go p.chunkLoop(ctx, "v1", layer, done, wait, nil)
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("the cut loop did not end within 5 s of its cancel")
}
})
for deadline := time.Now().Add(5 * time.Second); layer.cuts.Load() < 3; time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatalf("the loop made %d attempts in 5 s, want 3", layer.cuts.Load())
}
}
layer.mu.Lock()
at := append([]time.Time(nil), layer.at...)
layer.mu.Unlock()
for i := 1; i < 3; i++ {
if gap := at[i].Sub(at[i-1]); gap >= 500*time.Millisecond {
t.Fatalf("attempt %d came %s after a yield: a yield was backed off as a failure", i+1, gap.Round(time.Millisecond))
}
}
if got := wait.status(0).CutYields; got != 2 {
t.Fatalf("status counts %d yields, want 2", got)
}
}
@@ -442,6 +442,7 @@ type CutScheduleStatus struct {
TicketDueHostNs int64 `json:",omitempty"` // the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting
TicketsSkipped uint64 `json:",omitempty"` // earlier tickets the waiting cut passed by the skip rule
TicketDropReason string `json:",omitempty"` // why the last ticket was given up before admission, when it was a refusal that waiting cannot fix
CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (not failures)
}
// NewDurableProvider constructs a provider. view is the ONLY
@@ -843,6 +843,7 @@ type cutSchedule struct {
failedSeenSeq uint64 // the layer's CutSeq when the last automatic cut failed
slotWaitSince time.Time // first refusal for held host slots since the last success; zero when not waiting
slotWaits uint64 // automatic cuts refused for held host slots
yields uint64 // automatic cut attempts that yielded their slot to a waiting cut
}
// observe takes in, at now, the latest cut the layer reports (any
@@ -890,6 +891,13 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string
// after records the outcome of an automatic cut started at start, with
// the layer's CutSeq read after it.
func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq uint64) cutSchedule {
if errors.Is(err, storage.ErrCutYielded) {
// Not a failure: the slot went to a waiting cut; try again at the
// next poll (on a ticket at the back of the queue).
s.yields++
s.retryAt = end
return s
}
if errors.Is(err, hostlimit.ErrSlotsHeld) {
s.slotWaits++
if s.slotWaitSince.IsZero() {
@@ -1084,7 +1092,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
}
s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks)
wait.record(s, ticket)
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && !errors.Is(err, storage.ErrCutYielded) && ctx.Err() == nil {
if note, stuck := capturePendingNote(err); stuck {
log.Printf("durable: %s chunk cut for volume=%s REFUSED: %s (retry in %s)", reason, volumeID, note, s.backoff)
} else {
@@ -2004,7 +2012,7 @@ func (w *cutWaitSlot) record(s cutSchedule, ticket *hostlimit.Ticket) {
}
w.mu.Lock()
defer w.mu.Unlock()
st := CutScheduleStatus{HostSlotWaits: s.slotWaits, TicketDropReason: w.st.TicketDropReason}
st := CutScheduleStatus{HostSlotWaits: s.slotWaits, CutYields: s.yields, TicketDropReason: w.st.TicketDropReason}
if !s.slotWaitSince.IsZero() {
st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano()
}
+4 -1
View File
@@ -157,7 +157,10 @@ type Host struct {
lifecycle *LifecycleStores
// RPC registration/place/move/ACK/delete and product ticks serialize here.
// Order: workspaceMu -> publisher or lifecycle store locks (not reversed).
workspaceMu sync.Mutex
workspaceMu sync.Mutex
// bindingRetry: volumes whose binding reconcile failed, retried with the
// next call's own volume (workspaceMu held).
bindingRetry map[string]bool
events *eventRing
promotionMu sync.RWMutex
promotionProber PromotionEvidenceProvider
@@ -32,7 +32,7 @@ func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.Work
if err := ctx.Err(); err != nil {
return nil, workspaceError(err)
}
if err := s.host.reconcileWorkspaceBindings(); err != nil {
if err := s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil {
return nil, workspaceError(err)
}
if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok {
@@ -133,29 +133,56 @@ func (h *Host) placementSourceHost(volume, replica string) string {
// Recover retirement after a crash between the authority ACK/issued record
// and binding persistence. Epoch-tagged retirements cannot retire a later
// re-registration when an old Move/ACK is retried or replayed on restart.
// Caller owns workspaceMu, or Host.New has not exposed the host yet.
// Caller owns workspaceMu, or Host.New has not exposed the host yet. Every
// volume: the start's pass.
func (h *Host) reconcileWorkspaceBindings() error {
for _, v := range h.lifecycle.Volumes.ListVolumes() {
volume := v.Spec.VolumeID
state := h.Publisher().WorkspaceState(volume)
if state == nil {
continue
if err := h.reconcileWorkspaceBinding(v.Spec.VolumeID); err != nil {
return err
}
for _, m := range state.Moves {
// A move must not retire its own target reservation. A same-host
// successor reuses it; a later ACK still retires that epoch below.
if m.Issued && m.OldHost != m.NewHost {
if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil {
return err
}
}
return nil
}
// reconcileWorkspaceCall is a call's reconcile (a register, an ACK, a move):
// the call's own volume, and every volume whose reconcile failed before, so a
// failed retirement is retried by the next call as the whole pass did, at the
// cost of the volumes it touches, not every volume. workspaceMu held.
func (h *Host) reconcileWorkspaceCall(volume string) error {
if h.bindingRetry == nil {
h.bindingRetry = map[string]bool{}
}
h.bindingRetry[volume] = true
for v := range h.bindingRetry {
if err := h.reconcileWorkspaceBinding(v); err != nil {
return err
}
delete(h.bindingRetry, v)
}
return nil
}
// reconcileWorkspaceBinding retires the bindings one volume's moves and ACK
// left behind.
func (h *Host) reconcileWorkspaceBinding(volume string) error {
state := h.Publisher().WorkspaceState(volume)
if state == nil {
return nil
}
for _, m := range state.Moves {
// A move must not retire its own target reservation. A same-host
// successor reuses it; a later ACK still retires that epoch below.
if m.Issued && m.OldHost != m.NewHost {
if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil {
return err
}
}
if a := state.Ack; a != nil {
host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch)
if host != "" {
if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil {
return err
}
}
if a := state.Ack; a != nil {
host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch)
if host != "" {
if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil {
return err
}
}
}
@@ -0,0 +1,66 @@
package master
import (
"errors"
"reflect"
"runtime"
"testing"
)
// A call's binding reconcile (register, ACK, move) is the whole pass
// restricted to the volumes it touches: its own volume, and any volume whose
// reconcile failed before. Another volume's call retires nothing of a volume
// it does not touch; the volume's own call retires exactly what the whole
// pass retires; and an interrupted reconcile is finished by the next call,
// whichever volume that call is for.
func TestWorkspaceBindingCallReconcilesItsVolumeAndRetries(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("requires the binding store's supported directory fsync")
}
want := []bindingRetirement{{"recover", "node-a", 1}, {"recover", "node-b", 2}, {"recover", "node-c", 4}}
h := bindingReconcileHistory(t, false)
rec := &interruptedBindingStore{workspaceBindingStore: h.lifecycle.WorkspaceBindings}
h.workspaceMu.Lock()
h.lifecycle.WorkspaceBindings = rec
err := h.reconcileWorkspaceCall("other")
h.workspaceMu.Unlock()
if err != nil || len(rec.calls) != 0 {
t.Fatalf("another volume's call retired %+v (%v): it must touch only its own volume", rec.calls, err)
}
h.workspaceMu.Lock()
err = h.reconcileWorkspaceCall("recover")
h.workspaceMu.Unlock()
if err != nil || !reflect.DeepEqual(rec.calls, want) {
t.Fatalf("the volume's own call retired %+v (%v), the whole pass retires %+v", rec.calls, err, want)
}
h2 := bindingReconcileHistory(t, false)
fault := &interruptedBindingStore{workspaceBindingStore: h2.lifecycle.WorkspaceBindings, at: 2}
h2.workspaceMu.Lock()
h2.lifecycle.WorkspaceBindings = fault
err = h2.reconcileWorkspaceCall("recover")
h2.workspaceMu.Unlock()
if !errors.Is(err, errBindingReconcileInterrupted) {
t.Fatalf("interruption not propagated: %v", err)
}
h2.workspaceMu.Lock()
err = h2.reconcileWorkspaceCall("other")
h2.workspaceMu.Unlock()
if err != nil {
t.Fatal(err)
}
got, _, err := fault.workspaceBindingStore.Get("recover")
if err != nil {
t.Fatal(err)
}
for _, b := range got {
epoch := map[string]uint64{"node-a": 1, "node-b": 2, "node-c": 4}[b.ServerID]
if !b.Retired || b.RetiredEpoch != epoch {
t.Fatalf("the next call did not finish the interrupted volume's retirements: %+v", got)
}
}
if len(h2.bindingRetry) != 0 {
t.Fatalf("volumes still marked for retry: %v", h2.bindingRetry)
}
}
@@ -243,7 +243,7 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace
return nil, workspaceError(err)
}
recorded = time.Now()
if err := s.host.reconcileWorkspaceBindings(); err != nil {
if err := s.host.reconcileWorkspaceCall(id.GetVolumeId()); err != nil {
return nil, workspaceError(err)
}
return &control.WorkspaceEmpty{}, nil
@@ -388,7 +388,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
// The move is issued from here on: record it for the audit log before
// anything else can fail.
issued = s.grantWithLostRange(r)
if err = s.host.reconcileWorkspaceBindings(); err != nil {
if err = s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil {
postIssue = err
return nil, postIssueError(q, err)
}
+155
View File
@@ -0,0 +1,155 @@
package hostlimit
import (
"context"
"errors"
"fmt"
"hash/fnv"
"os"
"sync"
"time"
)
// fetchRetry is how often a waiting fetch tries the slots again while every
// one is held.
const fetchRetry = 20 * time.Millisecond
// fetchSlot is the slot a key's tries start from: its hash, modulo the slot
// count, so concurrent fetches spread over the slots.
func fetchSlot(key string, n int) int {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return int(h.Sum32() % uint32(n))
}
// HoldFetch holds one of the host's FetchSlots fetch slots (files fetch-0 ..
// fetch-(N-1) in the pool, so the cap is per host and a slot dies with its
// holder) for one chunk transfer; release gives it back. It never refuses for
// want of a slot:
//
// 1. a limiter's first fetch checks the host's configuration under
// configuration.lock, publishing it when absent, as a cut admission does:
// ErrConfig when another process uses other flags;
// 2. it takes a free slot without waiting, trying from key's hash slot;
// 3. with every slot held, it waits for its limiter's turn (one fetch per
// limiter polls; blockvolume makes one limiter per process) and then
// tries every slot each fetchRetry. The waiting is unordered, so other
// fetches can take a freed slot first; it ends with ctx's error once ctx
// ends, after any file-system step in progress (a configuration check
// can add up to its bounded guard wait, guardWait);
// 4. a slot taken when ctx has already ended is given back, and ctx's error
// returned.
//
// Every lock try is non-blocking, so a wait that ends leaves no lock request,
// descriptor or goroutine behind.
func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := l.checkFetchConfig(ctx); err != nil {
return nil, err
}
home := fetchSlot(key, l.cfg.FetchSlots)
f, err := l.tryFetch(home)
if f == nil && err == nil {
f, err = l.waitFetch(ctx, home)
}
if err != nil {
return nil, err
}
if l.testFetchLocked != nil {
l.testFetchLocked()
}
if err := ctx.Err(); err != nil {
_ = f.Close()
return nil, err
}
return releaseFetch(f), nil
}
// checkFetchConfig checks the host's configuration once per limiter. A
// configuration lock held past its bound by another admission is waited out
// within ctx; a mismatch is ErrConfig.
func (l *Limiter) checkFetchConfig(ctx context.Context) error {
if l.fetchChecked.Load() {
return nil
}
if err := l.checkPoolDir(); err != nil {
return err
}
for {
guard, err := l.configGuard()
if err == nil {
_ = guard.Close()
l.fetchChecked.Store(true)
return nil
}
if !errors.Is(err, ErrSlotsHeld) {
return err
}
if err := sleepCtx(ctx, fetchRetry); err != nil {
return err
}
}
}
// tryFetch takes a free fetch slot without waiting, trying from home; nil
// when every slot is held.
func (l *Limiter) tryFetch(home int) (*os.File, error) {
n := l.cfg.FetchSlots
for k := 0; k < n; k++ {
f, err := l.poolFile(fmt.Sprintf("fetch-%d", (home+k)%n))
if err != nil {
return nil, err
}
err = tryLock(f)
if err == nil {
return f, nil
}
_ = f.Close()
if !errors.Is(err, ErrBusy) {
return nil, err
}
}
return nil, nil
}
// waitFetch waits for a fetch slot while every one is held: it takes its
// limiter's turn, so one fetch per limiter polls, and tries every slot each
// fetchRetry until one is free or ctx ends.
func (l *Limiter) waitFetch(ctx context.Context, home int) (*os.File, error) {
select {
case l.fetchTurn <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-l.fetchTurn }()
for {
f, err := l.tryFetch(home)
if f != nil || err != nil {
return f, err
}
if err := sleepCtx(ctx, fetchRetry); err != nil {
return nil, err
}
}
}
// sleepCtx waits d, or until ctx ends (its error).
func sleepCtx(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// releaseFetch gives a fetch slot back, once: closing the file releases its
// lock.
func releaseFetch(f *os.File) func() {
var once sync.Once
return func() { once.Do(func() { _ = f.Close() }) }
}
@@ -0,0 +1,300 @@
package hostlimit
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"sync"
"testing"
"time"
)
// TestFetchProcessHelper is a child process for the fetch tests: it holds one
// fetch slot of the pool in SWBLOCK_TEST_FETCH_DIR, with FetchSlots from
// SWBLOCK_TEST_FETCH_SLOTS, prints HELD, and holds it until stdin closes or
// it is killed. It makes no cut admission, so nothing but the fetch
// initialises the pool.
func TestFetchProcessHelper(t *testing.T) {
dir := os.Getenv("SWBLOCK_TEST_FETCH_DIR")
if dir == "" {
return
}
c := DefaultConfig(dir)
c.NormalSlots = 1
c.UrgentSlots = 1
n, err := strconv.Atoi(os.Getenv("SWBLOCK_TEST_FETCH_SLOTS"))
if err != nil {
t.Fatal(err)
}
c.FetchSlots = n
l, err := New(c)
if err != nil {
t.Fatal(err)
}
release, err := l.HoldFetch(context.Background(), "v/child")
if err != nil {
t.Fatal(err)
}
// The release keeps the slot's file reachable for as long as the child
// lives; the forced collections show the hold does not depend on luck.
defer release()
runtime.GC()
runtime.GC()
fmt.Println("HELD")
_, _ = bufio.NewReader(os.Stdin).ReadByte()
}
// fetchChild starts a child process holding one fetch slot of dir's pool and
// waits until it holds it. The test's cleanup kills it.
func fetchChild(t *testing.T, dir string, slots int) *exec.Cmd {
t.Helper()
cmd := exec.Command(os.Args[0], "-test.run=^TestFetchProcessHelper$")
cmd.Env = append(os.Environ(), "SWBLOCK_TEST_FETCH_DIR="+dir, "SWBLOCK_TEST_FETCH_SLOTS="+strconv.Itoa(slots))
out, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
in, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = in.Close(); _ = cmd.Process.Kill(); _ = cmd.Wait() })
ready := make(chan bool, 1)
go func() {
s := bufio.NewScanner(out)
for s.Scan() {
if s.Text() == "HELD" {
ready <- true
return
}
}
ready <- false
}()
select {
case ok := <-ready:
if !ok {
t.Fatal("the fetch child failed before holding a slot")
}
case <-time.After(15 * time.Second):
t.Fatal("the fetch child never held a slot")
}
return cmd
}
// A fetch-only start publishes the host's configuration and checks it, as a
// cut admission does: a second process with another FetchSlots is refused
// with ErrConfig on its first fetch, never let in with a cap of its own.
func TestHoldFetchFirstFetchChecksTheHostConfiguration(t *testing.T) {
c := fetchConfig(t, 1)
fetchChild(t, c.Directory, 2) // publishes FetchSlots 2 by its fetch alone
if _, err := os.Stat(filepath.Join(c.Directory, "configuration.json")); err != nil {
t.Fatalf("a fetch-only start published no configuration: %v", err)
}
l := newTest(t, c)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
r, err := l.HoldFetch(ctx, keyOnSlot(t, 1, 2))
if r != nil {
r()
}
if !errors.Is(err, ErrConfig) {
t.Fatalf("a fetch with FetchSlots 1 beside a process with 2 answered %v, want ErrConfig", err)
}
}
// A fetch slot dies with its process: a killed holder's slot is taken by a
// waiter in another process.
func TestHoldFetchSlotDiesWithItsProcess(t *testing.T) {
c := fetchConfig(t, 1)
child := fetchChild(t, c.Directory, 1)
l := newTest(t, c)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
if r, err := l.HoldFetch(ctx, "v/parent"); !errors.Is(err, context.DeadlineExceeded) {
if r != nil {
r()
}
t.Fatalf("a fetch beside a live holder of the only slot answered %v, want its deadline", err)
}
_ = child.Process.Kill()
_ = child.Wait()
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel2()
r, err := l.HoldFetch(ctx2, "v/parent")
if err != nil {
t.Fatalf("the killed holder's slot was not freed: %v", err)
}
r()
}
// openFDs counts the process's open descriptors where the platform lists
// them (-1 elsewhere).
func openFDs() int {
if runtime.GOOS != "linux" {
return -1
}
es, err := os.ReadDir("/proc/self/fd")
if err != nil {
return -1
}
return len(es)
}
// settlesTo waits up to a bound for the goroutine (and, on Linux, descriptor)
// count to come back to the baseline plus slack.
func settlesTo(t *testing.T, what string, goroutines, fds int) {
t.Helper()
const slack = 3
deadline := time.Now().Add(time.Second)
for {
g, f := runtime.NumGoroutine(), openFDs()
if g <= goroutines+slack && (fds < 0 || f <= fds+slack) {
return
}
if time.Now().After(deadline) {
t.Fatalf("after %s: %d goroutines (baseline %d), %d descriptors (baseline %d): fetch waits left work behind", what, g, goroutines, f, fds)
}
time.Sleep(10 * time.Millisecond)
}
}
// Waits that end (at their deadline, or by taking another slot) leave nothing
// running and nothing open while the slot they waited on stays held.
func TestHoldFetchEndedWaitsLeaveNothingBehind(t *testing.T) {
c := fetchConfig(t, 2)
homeHolder, otherHolder, w := newTest(t, c), newTest(t, c), newTest(t, c)
key := keyOnSlot(t, 0, 2)
rHome := mustHold(t, homeHolder, key) // held for the whole test
defer rHome()
otherKey := keyOnSlot(t, 1, 2)
rOther := mustHold(t, otherHolder, otherKey)
defer rOther() // releases are idempotent
g0, f0 := runtime.NumGoroutine(), openFDs()
for i := 0; i < 20; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
r, err := w.HoldFetch(ctx, key)
cancel()
if r != nil {
r()
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("wait %d with both slots held answered %v, want its deadline", i, err)
}
}
settlesTo(t, "20 waits ended at their deadline", g0, f0)
// Each fetch below is already waiting (both slots held) when the other
// slot is freed, so it takes that slot from the waiting path.
for i := 0; i < 10; i++ {
if i > 0 {
rOther = mustHold(t, otherHolder, otherKey)
defer rOther()
}
got := holdAsync(t, w, context.Background(), key)
select {
case h := <-got:
if h.release != nil {
h.release()
}
t.Fatalf("fetch %d returned while both slots were held (err %v)", i, h.err)
case <-time.After(60 * time.Millisecond):
}
rOther()
select {
case h := <-got:
if h.err != nil {
t.Fatalf("waiting fetch %d: %v", i, h.err)
}
h.release()
case <-time.After(2 * time.Second):
t.Fatalf("waiting fetch %d never took the freed slot", i)
}
}
settlesTo(t, "10 waiting fetches that took the freed slot", g0, f0)
}
// A context that ends as a slot is taken gets its context's error, and the
// slot is given back: no fetch holds a slot past its context.
func TestHoldFetchCancelledAtTheHandoffHoldsNothing(t *testing.T) {
c := fetchConfig(t, 1)
w, later := newTest(t, c), newTest(t, c)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w.testFetchLocked = cancel
r, err := w.HoldFetch(ctx, "v/w")
if r != nil {
r()
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("a fetch cancelled as it took its slot answered %v, want its context's error", err)
}
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel2()
r2, err := later.HoldFetch(ctx2, "v/later")
if err != nil {
t.Fatalf("the slot a cancelled fetch took was kept: %v", err)
}
r2()
}
// The waiting is unordered (a waiter can be passed by other fetches), and
// bounded by the waiter's own context: with others taking and giving back
// the only slot all along, a waiter ends by its deadline, with a slot or with
// its deadline's error.
func TestHoldFetchAPassedWaiterEndsByItsDeadline(t *testing.T) {
c := fetchConfig(t, 1)
// The competitors' fetches derive from stopCtx, so stopping cancels a
// fetch in progress too; the cleanup joins them within a bound.
stopCtx, stop := context.WithCancel(context.Background())
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
l := newTest(t, c)
wg.Add(1)
go func(i int) {
defer wg.Done()
for stopCtx.Err() == nil {
ctx, cancel := context.WithTimeout(stopCtx, 100*time.Millisecond)
r, err := l.HoldFetch(ctx, fmt.Sprintf("v/c%d", i))
cancel()
if err == nil {
time.Sleep(5 * time.Millisecond)
r()
}
}
}(i)
}
defer func() {
stop()
joined := make(chan struct{})
go func() { wg.Wait(); close(joined) }()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("the competing fetches did not stop after their context ended")
}
}()
w := newTest(t, c)
const deadline = 150 * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), deadline)
defer cancel()
start := time.Now()
r, err := w.HoldFetch(ctx, "v/w")
took := time.Since(start)
if r != nil {
r()
}
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("a passed waiter answered %v, want a slot or its deadline", err)
}
if took > deadline+250*time.Millisecond {
t.Fatalf("a waiter with a %s deadline returned after %s", deadline, took)
}
}
+187
View File
@@ -0,0 +1,187 @@
package hostlimit
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
)
func fetchConfig(t *testing.T, slots int) Config {
t.Helper()
c := testConfig(t)
c.FetchSlots = slots
return c
}
// keyOnSlot is a key whose hash slot is s among n.
func keyOnSlot(t *testing.T, s, n int) string {
t.Helper()
for i := 0; i < 10000; i++ {
k := fmt.Sprintf("v/%d", i)
if fetchSlot(k, n) == s {
return k
}
}
t.Fatalf("no key on slot %d of %d", s, n)
return ""
}
type held struct {
release func()
err error
}
// holdAsync runs HoldFetch in the background; its result arrives on the
// channel. The test's cleanup ends the wait, joins it (bounded) and releases
// a slot it got, whether or not the test read the result.
func holdAsync(t *testing.T, l *Limiter, ctx context.Context, key string) <-chan held {
t.Helper()
ctx, cancel := context.WithCancel(ctx)
got := make(chan held, 1)
done := make(chan struct{})
var mu sync.Mutex
var release func()
go func() {
defer close(done)
r, err := l.HoldFetch(ctx, key)
mu.Lock()
release = r
mu.Unlock()
got <- held{r, err}
}()
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("a background fetch did not return after its context ended")
return
}
mu.Lock()
defer mu.Unlock()
if release != nil {
release() // releases are idempotent
}
})
return got
}
func mustHold(t *testing.T, l *Limiter, key string) func() {
t.Helper()
r, err := l.HoldFetch(context.Background(), key)
if err != nil {
t.Fatal(err)
}
return r
}
// While slots are free, a fetch takes one without waiting.
func TestHoldFetchTakesAFreeSlotAtOnce(t *testing.T) {
c := fetchConfig(t, 2)
a, b := newTest(t, c), newTest(t, c)
r1 := mustHold(t, a, keyOnSlot(t, 0, 2))
defer r1()
start := time.Now()
r2 := mustHold(t, b, keyOnSlot(t, 0, 2)) // its hash slot is held: it takes the other one
defer r2()
if d := time.Since(start); d > 200*time.Millisecond {
t.Fatalf("a fetch with a free slot waited %s", d)
}
}
// The cap holds across limiters on one pool (separate processes: see
// TestHoldFetchSlotDiesWithItsProcess): with every slot held by others, a
// fetch waits until one is released, and then takes it.
func TestHoldFetchCapHoldsAcrossLimiters(t *testing.T) {
c := fetchConfig(t, 2)
a, b, w := newTest(t, c), newTest(t, c), newTest(t, c)
r1 := mustHold(t, a, keyOnSlot(t, 0, 2))
r2 := mustHold(t, b, keyOnSlot(t, 1, 2))
defer r2()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
got := holdAsync(t, w, ctx, "v/third")
select {
case h := <-got:
if h.release != nil {
h.release()
}
t.Fatalf("a third fetch held a slot while both were held (err %v)", h.err)
case <-time.After(150 * time.Millisecond):
}
r1()
select {
case h := <-got:
if h.err != nil {
t.Fatalf("the waiting fetch: %v", h.err)
}
h.release()
case <-time.After(2 * time.Second):
t.Fatal("the waiting fetch did not take the released slot")
}
}
// A waiter whose context ends returns its context's error, and a slot it
// gets after that is released at once: a later fetch is not held back by it.
func TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld(t *testing.T) {
c := fetchConfig(t, 1)
a, w, later := newTest(t, c), newTest(t, c), newTest(t, c)
r1 := mustHold(t, a, "v/a")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if _, err := w.HoldFetch(ctx, "v/w"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("a waiter past its context answered %v, want its deadline", err)
}
r1() // the abandoned wait now gets the slot, and must release it at once
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel2()
select {
case h := <-holdAsync(t, later, ctx2, "v/later"):
if h.err != nil {
t.Fatalf("a later fetch was held back by an abandoned wait: %v", h.err)
}
h.release()
case <-time.After(3 * time.Second):
t.Fatal("a later fetch never got the slot")
}
}
// A waiter blocked behind a slow holder on its own hash slot is not delayed
// beyond one retry interval once another slot is free: the host's slots are
// one pool, not N separate queues.
func TestHoldFetchTakesAnotherSlotThatFreesFirst(t *testing.T) {
c := fetchConfig(t, 2)
slow, other, w := newTest(t, c), newTest(t, c), newTest(t, c)
key := keyOnSlot(t, 0, 2)
rSlow := mustHold(t, slow, key) // the waiter's hash slot, held for the whole test
defer rSlow()
rOther := mustHold(t, other, keyOnSlot(t, 1, 2))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
got := holdAsync(t, w, ctx, key)
select {
case h := <-got:
if h.release != nil {
h.release()
}
t.Fatalf("the waiter held a slot while both were held (err %v)", h.err)
case <-time.After(150 * time.Millisecond):
}
freed := time.Now()
rOther()
select {
case h := <-got:
if h.err != nil {
t.Fatalf("the waiter: %v", h.err)
}
if d := time.Since(freed); d > 300*time.Millisecond {
t.Fatalf("the waiter took the freed slot %s after it was freed, behind a slow holder of its own slot", d)
}
h.release()
case <-time.After(2 * time.Second):
t.Fatal("the waiter never took the other slot while its own stayed held")
}
}
+117 -35
View File
@@ -63,13 +63,20 @@ type Config struct {
// only after this long with no progress of its work (Progress). Work
// that keeps progressing is never revoked, however long it holds.
NoProgress time.Duration
// FetchSlots caps the chunk fetches in flight on the host, across its
// processes (HoldFetch): a guest read waits for a slot, never refused.
FetchSlots int
// YieldAfter is S: a Normal hold at least this old yields its slot at
// its cut's next staging batch when another cut on the host waits (a
// live ticket). A lone hold never yields; an urgent one never does.
YieldAfter time.Duration
}
func DefaultConfig(dir string) Config {
return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second}
return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64, YieldAfter: 5 * time.Minute}
}
func (c Config) Validate() error {
if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 {
if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 || c.YieldAfter <= 0 {
return errors.New("hostlimit: invalid configuration")
}
return nil
@@ -121,6 +128,7 @@ type Limiter struct {
testExpireRace func() // tests: runs as a hold's expiry decides, under the limiter's lock
testAfterTicketCreate func(string) // test-only: between a ticket's create and its lock
testSkipAfter time.Duration // test-only TicketSkipAfter override
testFetchLocked func() // test-only: a fetch slot was just locked, before HoldFetch hands it over
cfg Config
// base is the limiter's monotonic origin: a hold's progress stamp is
// time.Since(base), so the window never reads the wall clock.
@@ -147,6 +155,12 @@ type Limiter struct {
// by the skip rule. It is never taken with mu held, nor mu under it.
skipMu sync.Mutex
stalled map[string]bool
// fetchChecked is set once a fetch has checked the host's configuration;
// fetchTurn (capacity 1) is held by the one fetch of this limiter that
// polls for a slot while every slot is held.
fetchChecked atomic.Bool
fetchTurn chan struct{}
}
func (l *Limiter) skipAfter() time.Duration {
@@ -160,7 +174,7 @@ func New(c Config) (*Limiter, error) {
if err := c.Validate(); err != nil {
return nil, err
}
l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})}
l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{}), fetchTurn: make(chan struct{}, 1)}
go l.releaseLoop()
return l, nil
}
@@ -178,20 +192,10 @@ func Phase(volume string, period time.Duration) time.Duration {
// pool checks the immutable configuration under a separate OS lock. Slot files
// are never unlinked: replacing them could create a second set of live permits.
func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) {
info, err := os.Lstat(l.cfg.Directory)
if err != nil {
if err := l.checkPoolDir(); err != nil {
return nil, err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return nil, errors.New("hostlimit: pool must be a local directory")
}
open := func(name string) (*os.File, error) {
path := filepath.Join(l.cfg.Directory, name)
if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() {
return nil, errors.New("hostlimit: nonregular pool file")
}
return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
}
open := l.poolFile
// A ticketed Normal admission first checks its place in the queue. The
// ticket files synchronise through their own locks, so this runs outside
// the configuration lock and does not lengthen it.
@@ -200,30 +204,11 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) {
return nil, err
}
}
guard, err := open("configuration.lock")
guard, err := l.configGuard()
if err != nil {
return nil, err
}
defer guard.Close()
if l.testBeforeConfigLock != nil {
l.testBeforeConfigLock(guard)
}
if err = lockGuard(guard); err != nil {
return nil, err
}
expected, _ := json.Marshal(l.cfg)
path := filepath.Join(l.cfg.Directory, "configuration.json")
existing, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
err = l.publishConfig(path, expected)
existing = expected
}
if err != nil {
return nil, err
}
if string(existing) != string(expected) {
return nil, ErrConfig
}
if c == Normal {
// The probe is held until the slot try-lock below has been made, so
// no Normal admission completes after urgent work became pending.
@@ -276,6 +261,60 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) {
return nil, ErrSlotsHeld
}
// checkPoolDir refuses a pool that is not a local directory.
func (l *Limiter) checkPoolDir() error {
info, err := os.Lstat(l.cfg.Directory)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("hostlimit: pool must be a local directory")
}
return nil
}
// poolFile opens (creating) a regular file of the pool.
func (l *Limiter) poolFile(name string) (*os.File, error) {
path := filepath.Join(l.cfg.Directory, name)
if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() {
return nil, errors.New("hostlimit: nonregular pool file")
}
return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
}
// configGuard takes configuration.lock and, under it, checks the host's
// immutable configuration, publishing it when absent: ErrConfig when another
// process published other flags. The caller closes the guard, which releases
// the lock.
func (l *Limiter) configGuard() (*os.File, error) {
guard, err := l.poolFile("configuration.lock")
if err != nil {
return nil, err
}
if l.testBeforeConfigLock != nil {
l.testBeforeConfigLock(guard)
}
if err = lockGuard(guard); err != nil {
_ = guard.Close()
return nil, err
}
expected, _ := json.Marshal(l.cfg)
path := filepath.Join(l.cfg.Directory, "configuration.json")
existing, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
err = l.publishConfig(path, expected)
existing = expected
}
if err == nil && string(existing) != string(expected) {
err = ErrConfig
}
if err != nil {
_ = guard.Close()
return nil, err
}
return guard, nil
}
// guardWait bounds how long an admission waits for configuration.lock.
// Another admission holds it only while it checks the configuration and
// tries its slots.
@@ -465,6 +504,49 @@ func (l *Limiter) Progress(id uint64) {
}
}
// ShouldYield reports whether the hold id should yield its slot now: it is
// a Normal hold at least YieldAfter old and another cut on the host waits.
// It takes no lock of the limiter; the waiter probe (the tickets directory)
// runs only once the hold is old enough.
func (l *Limiter) ShouldYield(id uint64) bool {
v, ok := l.leases.Load(id)
if !ok {
return false
}
x := v.(*lease)
if x.class != Normal || time.Since(x.started) < l.cfg.YieldAfter {
return false
}
return l.waiterLive()
}
// waiterLive reports whether another cut waits on the host: a live ticket in
// the pool (its holder's lock held) that this process has not judged stalled.
// A dead ticket found on the way is reaped, as a waiter's head check does.
func (l *Limiter) waiterLive() bool {
dir := filepath.Join(l.cfg.Directory, ticketsDir)
ents, err := os.ReadDir(dir)
if err != nil {
return false
}
present := make(map[string]bool, len(ents))
for _, e := range ents {
present[e.Name()] = true
}
stalled := l.stalledTickets(present)
for _, e := range ents {
n := e.Name()
if _, ok := ticketDue(n); !ok || stalled[n] {
continue
}
if reap(filepath.Join(dir, n)) {
continue // its holder exited
}
return true
}
return false
}
// expire runs when a hold's timer fires: a hold that progressed within its
// window is armed again for the rest of it; one that did not is revoked. The
// decision and the revocation are one step under the limiter's lock, reading
@@ -7,7 +7,10 @@ import (
)
// A hold whose work reports no progress is revoked within its no-progress
// window W: not before W, and not much after it.
// window W: not before W, and not much after it. The window starts inside
// Admit, so "not before" is measured from before Admit and "not much after"
// from its return: the admission's own file-system work (a first admission
// publishes and syncs the host configuration) is not counted against W.
func TestStalledHoldIsRevokedWithinTheWindow(t *testing.T) {
c := testConfig(t)
c.NoProgress = 100 * time.Millisecond
@@ -18,11 +21,15 @@ func TestStalledHoldIsRevokedWithinTheWindow(t *testing.T) {
if err != nil {
t.Fatal(err)
}
admitted := time.Now()
defer l.Release(x)
select {
case at := <-revoked:
if d := at.Sub(start); d < 80*time.Millisecond || d > 400*time.Millisecond {
t.Fatalf("revoked after %s, want about the window (%s)", d, c.NoProgress)
if d := at.Sub(start); d < 80*time.Millisecond {
t.Fatalf("revoked %s after the admission began, before the window (%s)", d, c.NoProgress)
}
if d := at.Sub(admitted); d > 400*time.Millisecond {
t.Fatalf("revoked %s after the admission returned, want about the window (%s); the admission took %s", d, c.NoProgress, admitted.Sub(start))
}
case <-time.After(2 * time.Second):
t.Fatalf("a stalled hold was not revoked within its no-progress window (%s)", c.NoProgress)
@@ -0,0 +1,61 @@
package hostlimit
import (
"context"
"path/filepath"
"testing"
"time"
)
// A Normal hold yields only once it is S old AND another process waits (a
// live ticket in the pool): a lone hold never yields however old, a waiter
// before S changes nothing, an urgent hold never yields, and a ticket this
// process judged stalled is not a waiter.
func TestShouldYieldOnlyAfterSWithALiveWaiter(t *testing.T) {
c := testConfig(t)
c.NormalSlots = 2
c.YieldAfter = 60 * time.Millisecond
l := newTest(t, c)
waiter := newTest(t, c) // another process on the host
x, err := l.Admit(context.Background(), 1, nil)
if err != nil {
t.Fatal(err)
}
defer l.Release(x)
if l.ShouldYield(x) {
t.Fatal("a fresh hold with no waiter yields")
}
tk, err := waiter.TakeTicket(HostNow())
if err != nil {
t.Fatal(err)
}
if l.ShouldYield(x) {
t.Fatal("a hold younger than S yields to a waiter")
}
time.Sleep(80 * time.Millisecond)
if !l.ShouldYield(x) {
t.Fatal("a hold older than S does not yield to a live waiter")
}
l.markStalled(filepath.Base(tk.path))
if l.ShouldYield(x) {
t.Fatal("a ticket this process judged stalled counts as a waiter")
}
tk.Close()
if l.ShouldYield(x) {
t.Fatal("a hold older than S yields with no waiter")
}
tk2, err := waiter.TakeTicket(HostNow())
if err != nil {
t.Fatal(err)
}
defer tk2.Close()
u, err := l.Acquire(context.Background(), Urgent, nil)
if err != nil {
t.Fatal(err)
}
defer l.Release(u)
time.Sleep(80 * time.Millisecond)
if l.ShouldYield(u) {
t.Fatal("an urgent hold yields")
}
}
+31 -1
View File
@@ -1,6 +1,29 @@
package storage
import "context"
import (
"context"
"errors"
)
// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut,
// at a staging batch boundary. It is its own outcome, never a failed cut: the
// chunks the attempt staged are kept, and its next attempt stages the rest.
var ErrCutYielded = errors.New("storage: the cut yielded its host slot to a waiting cut")
// BudgetYield is a Budget that asks a long hold to yield its slot:
// ShouldYield must be nonblocking and cheap while the hold is young.
type BudgetYield interface {
ShouldYield(ticket uint64) bool
}
// budgetYield is the question a cut asks at each staging batch boundary; nil
// when the Budget never asks a hold to yield.
func budgetYield(b Budget, ticket uint64) func() bool {
if y, ok := b.(BudgetYield); ok {
return func() bool { return y.ShouldYield(ticket) }
}
return nil
}
// Budget is the host limiter seam. Admit runs before staging or the cut
// barrier and reserves the configured payload ceiling. ReserveCOW accounts
@@ -32,6 +55,13 @@ func budgetProgress(b Budget, ticket uint64) func() {
return func() {}
}
// BudgetFetch is a Budget that caps the chunk fetches in flight on the host:
// HoldFetch holds one slot for one chunk transfer, waiting (bounded by ctx)
// when every slot is held; release gives it back.
type BudgetFetch interface {
HoldFetch(ctx context.Context, key string) (release func(), err error)
}
type cutBudgetReservation struct {
budget Budget
ticket uint64
@@ -17,8 +17,12 @@ type testCutBudget struct {
abort func(error)
probe func()
progressed int
yield bool // ShouldYield's answer (BudgetYield)
}
// ShouldYield answers yield (BudgetYield).
func (b *testCutBudget) ShouldYield(uint64) bool { b.mu.Lock(); defer b.mu.Unlock(); return b.yield }
// Progress counts the cut's progress reports (BudgetProgress).
func (b *testCutBudget) Progress(uint64) { b.mu.Lock(); b.progressed++; b.mu.Unlock() }
@@ -22,11 +22,20 @@ type cutAttemptObservation struct {
// progress renews the attempt's host hold (set at its admission, before
// any worker starts; nil without a budget).
progress func()
spans [cutWorkSpanCount]atomic.Int64
counts [cutWorkCountCount]atomic.Int64
// yield asks the attempt's host hold whether to give its slot to a
// waiting cut (set at its admission; nil without a yielding budget).
yield func() bool
spans [cutWorkSpanCount]atomic.Int64
counts [cutWorkCountCount]atomic.Int64
}
type cutObservationKey struct{}
// shouldYield asks, at a staging batch boundary, whether the attempt gives
// its host slot to a waiting cut.
func (w *cutAttemptObservation) shouldYield() bool {
return w != nil && w.yield != nil && w.yield()
}
// progressed reports one unit of the attempt's work to its host hold.
func (w *cutAttemptObservation) progressed() {
if w != nil && w.progress != nil {
@@ -0,0 +1,39 @@
package storage
import (
"errors"
"testing"
)
// A cut whose budget asks it to yield ends its attempt at the next staging
// batch boundary with ErrCutYielded: an outcome of its own (never a failed
// cut in status), it publishes nothing, and the chunks it staged are kept,
// so the next attempt stages only the rest.
func TestCutYieldsAtABatchBoundaryAndKeepsItsStaging(t *testing.T) {
_, l := zeroStagedLayer(t, 6)
b := &testCutBudget{yield: true}
l.cfg.Budget = b
before := l.Stats()
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, ErrCutYielded) {
t.Fatalf("cut: %v; want it to yield at a staging batch boundary", err)
}
after := l.Stats()
if after.CutsYielded != before.CutsYielded+1 || after.CutsFailed != before.CutsFailed || after.LastCutFailure != nil {
t.Fatalf("a yield counted yielded %d->%d, failed %d->%d, failure %+v; want one yield and no failure",
before.CutsYielded, after.CutsYielded, before.CutsFailed, after.CutsFailed, after.LastCutFailure)
}
staged := after.StagedChunks - before.StagedChunks
if staged == 0 || after.CutSeq != before.CutSeq {
t.Fatalf("the yielding attempt staged %d chunks and moved the cut sequence %d->%d; want a staged batch and no publication",
staged, before.CutSeq, after.CutSeq)
}
b.mu.Lock()
b.yield = false
b.mu.Unlock()
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if again := l.Stats().StagedChunks - after.StagedChunks; again >= staged {
t.Fatalf("the retry staged %d chunks again after the yield staged %d; want the yielded attempt's chunks kept", again, staged)
}
}
@@ -0,0 +1,74 @@
package storage
import (
"context"
"sync"
"testing"
"time"
)
// fetchSlots is a BudgetFetch that counts the fetch slots held, and the most
// held at once.
type fetchSlots struct {
Budget
mu sync.Mutex
active, holds int
keys []string
}
func (f *fetchSlots) HoldFetch(ctx context.Context, key string) (func(), error) {
f.mu.Lock()
f.active++
f.holds++
f.keys = append(f.keys, key)
f.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
f.mu.Lock()
f.active--
f.mu.Unlock()
})
}, nil
}
func (f *fetchSlots) state() (active, holds int) {
f.mu.Lock()
defer f.mu.Unlock()
return f.active, f.holds
}
// A chunk fetch holds one host fetch slot exactly across its remote read:
// held while the read is in flight, released once the read has returned (the
// install and the reader's wake-up hold none).
func TestChunkFetchHoldsAHostSlotAroundItsRemoteRead(t *testing.T) {
s, layer, remote, _ := hydrationFixture(t, 2, 64)
slots := &fetchSlots{}
layer.cfg.Budget = slots
entered, release := holdGets(t, remote)
read := make(chan error, 1)
go func() {
_, err := s.Read(0)
read <- err
}()
select {
case <-entered:
case <-time.After(ctLocalBound):
t.Fatal("the read miss never reached the remote")
}
if active, holds := slots.state(); active != 1 || holds != 1 {
t.Fatalf("during the remote read %d slots are held (%d taken), want exactly one", active, holds)
}
release()
select {
case err := <-read:
if err != nil {
t.Fatal(err)
}
case <-time.After(ctLocalBound):
t.Fatal("the read did not complete")
}
if active, _ := slots.state(); active != 0 {
t.Fatalf("%d fetch slots still held after the read returned", active)
}
}
+20
View File
@@ -701,7 +701,19 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun
l.stMu.Lock()
version := l.chunkVersion(idx)
l.stMu.Unlock()
// The host's fetch cap: one slot held across the remote read only, not
// the install. Its wait is bounded by ctx, a context error that the
// hydration path answers as pending.
release := func() {}
if fb, ok := l.cfg.Budget.(BudgetFetch); ok {
r, err := fb.HoldFetch(ctx, fmt.Sprintf("%s/%d", l.cfg.VolumeID, idx))
if err != nil {
return false, fmt.Errorf("storage: chunk %d fetch slot: %w", idx, err)
}
release = r
}
data, err := l.remote.Get(ctx, ref.Key)
release()
if err != nil {
return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err)
}
@@ -1110,6 +1122,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
budget = &cutBudgetReservation{budget: host, ticket: ticket, ctx: ctx}
work.progress = budgetProgress(host, ticket)
work.yield = budgetYield(host, ticket)
defer func() {
if err != nil {
err = errors.Join(err, context.Cause(budgetCtx))
@@ -1975,6 +1988,8 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error
reason = "fenced"
case errors.Is(err, errChunkLayerDetached):
reason = "detached"
case errors.Is(err, ErrCutYielded):
l.stats.CutsYielded++ // its own outcome: never a failed cut
default:
l.stats.CutsFailed++
l.noteCutFailureLocked(err, abortReason)
@@ -2172,6 +2187,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap
if hook := l.testAfterStageHook; hook != nil {
hook(round)
}
// A batch boundary: a long hold gives its slot to a waiting cut here,
// keeping what it staged (its next attempt stages only the rest).
if cutObservation(ctx).shouldYield() {
return nil, ErrCutYielded
}
}
return staged, nil
}
+1
View File
@@ -510,6 +510,7 @@ type chunkLayerStats struct {
CutsNoop uint64 // cuts with nothing new (no CAS)
CutsFailed uint64 // every other cut failure
CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached
CutsYielded uint64 // attempts that gave their host slot to a waiting cut at a staging batch boundary
CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload
CASConflicts uint64 // HEAD CAS precondition failures
CASUnknown uint64 // HEAD CAS results still unresolved after the re-read
@@ -65,6 +65,10 @@ var (
// ErrMigrationIncomplete: no selectable slot exists but a prepared
// migration slot does (DESIGN 2.3, 10.1). The volume must not serve.
ErrMigrationIncomplete = errors.New("storage: v3 migration not committed (only a prepared descriptor slot exists)")
// ErrStoreFormatNewer: an intact descriptor slot names a store format
// newer than this binary knows (its chunk-state format). The store is
// refused as written by a newer version, never read or changed.
ErrStoreFormatNewer = errors.New("storage: store written by a newer format: use a newer binary")
// ErrCounterExhausted: a persisted counter would exceed 2^64-2
// (DESIGN 2.4). Nothing is written.
ErrCounterExhausted = errors.New("storage: v3 counter exhausted")
@@ -127,6 +131,9 @@ const (
var crc32cTable = crc32.MakeTable(crc32.Castagnoli)
// chunkStateFormatKnownV3 is the newest chunk-state format this binary reads.
const chunkStateFormatKnownV3 = 1
// reservedRangesV3 are the [start, end) byte ranges that must be zero.
var reservedRangesV3 = [][2]int{
{9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {308, 312}, {320, slotCRCOffsetV3},
@@ -212,6 +219,11 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) {
if f := le.Uint16(b[6:]); f != 0 {
return descriptorV3{}, fmt.Errorf("%w: slot flags %#x", errSuperblockInvalid, f)
}
// A newer store format is told apart before any check of its bytes: an
// intact slot of a newer version is not an invalid one.
if f := le.Uint16(b[306:]); f > chunkStateFormatKnownV3 {
return descriptorV3{}, fmt.Errorf("%w: chunk-state format %d, this binary knows %d", ErrStoreFormatNewer, f, chunkStateFormatKnownV3)
}
for _, r := range reservedRangesV3 {
if i := firstNonZero(b[r[0]:r[1]]); i >= 0 {
return descriptorV3{}, fmt.Errorf("%w: reserved byte %d is nonzero", errSuperblockInvalid, r[0]+i)
@@ -430,6 +442,9 @@ func selectSlotV3(a, b []byte, accept slotImplAcceptor) (descriptorV3, slotIDV3,
da, errA := decodeSlotV3(a, accept)
db, errB := decodeSlotV3(b, accept)
if errA != nil && errB != nil {
if errors.Is(errA, ErrStoreFormatNewer) || errors.Is(errB, ErrStoreFormatNewer) {
return descriptorV3{}, 0, fmt.Errorf("%w (A: %v; B: %v)", ErrStoreFormatNewer, errA, errB)
}
return descriptorV3{}, 0, fmt.Errorf("%w: neither descriptor slot is valid (A: %v; B: %v)",
errSuperblockInvalid, errA, errB)
}
@@ -0,0 +1,116 @@
package storage
import (
"crypto/sha256"
"errors"
"os"
"path/filepath"
"testing"
)
// formatNewerStore is a closed store whose descriptor slots are rewritten by
// mutate (each decoded, changed, and re-sealed with its CRC), plus a planted
// cut COW side file.
func formatNewerStore(t *testing.T, mutate func(slot int, d *descriptorV3)) (path, side string) {
t.Helper()
path = filepath.Join(t.TempDir(), "volume")
s, err := CreateWALStoreWithOptions(path, 64, 4096, WALStoreOptions{ChunkBlocks: 4})
if err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
f, err := os.OpenFile(path, os.O_RDWR, 0o644)
if err != nil {
t.Fatal(err)
}
for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} {
raw := make([]byte, slotSizeV3)
if _, err := f.ReadAt(raw, off); err != nil {
t.Fatal(err)
}
d, err := decodeSlotV3(raw, nil)
if err != nil {
t.Fatalf("setup: slot %d: %v", i, err)
}
mutate(i, &d)
if _, err := f.WriteAt(d.encode(), off); err != nil {
t.Fatal(err)
}
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
side = path + ".cut-cow-planted"
if err := os.WriteFile(side, []byte("side"), 0o600); err != nil {
t.Fatal(err)
}
return path, side
}
func fileSum(t *testing.T, path string) [32]byte {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return sha256.Sum256(b)
}
// A store written by a newer format (its descriptor slots intact, sealed,
// naming a chunk-state format this binary does not know) is refused with the
// typed ErrStoreFormatNewer, not reported as an invalid slot, and the open
// changes nothing: the file's bytes and the directory's cut COW side files
// stay as they were. A half-fence (one slot newer, the other at a known
// format) opens on the known slot, as before; a slot invalid otherwise is
// still invalid, not newer.
func TestANewerStoreFormatIsRefusedTypedAndUntouched(t *testing.T) {
t.Run("both slots newer", func(t *testing.T) {
path, side := formatNewerStore(t, func(_ int, d *descriptorV3) {
d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1
})
before := fileSum(t, path)
s, err := OpenWALStore(path)
if err == nil {
_ = s.Close()
}
if !errors.Is(err, ErrStoreFormatNewer) {
t.Fatalf("open of a newer-format store: %v, want ErrStoreFormatNewer", err)
}
if fileSum(t, path) != before {
t.Fatal("the refused open changed the store's bytes")
}
if _, err := os.Stat(side); err != nil {
t.Fatalf("the refused open removed a cut COW side file: %v", err)
}
})
t.Run("half-fence opens on the known slot", func(t *testing.T) {
path, _ := formatNewerStore(t, func(slot int, d *descriptorV3) {
if slot == 0 {
d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1
}
})
s, err := OpenWALStore(path)
if err != nil {
t.Fatalf("open with one slot newer and one known: %v", err)
}
_ = s.Close()
})
t.Run("control: an invalid slot is not newer", func(t *testing.T) {
path, side := formatNewerStore(t, func(_ int, d *descriptorV3) {
d.ChunkStateFormat, d.LocalWorkEpoch = 0, 5 // epoch without a format: invalid
})
s, err := OpenWALStore(path)
if err == nil {
_ = s.Close()
t.Fatal("an invalid descriptor opened")
}
if errors.Is(err, ErrStoreFormatNewer) {
t.Fatalf("an invalid descriptor reported as a newer format: %v", err)
}
if _, err := os.Stat(side); err != nil {
t.Fatalf("a refused open removed a cut COW side file: %v", err)
}
})
}
+10 -4
View File
@@ -347,10 +347,6 @@ func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOption
_ = f.Close()
return nil, err
}
if err := discardCutCOWFiles(path); err != nil {
_ = f.Close()
return nil, err
}
return openWALStoreV3File(path, f, requireMap, opts, nil, false)
}
@@ -376,6 +372,16 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO
_ = f.Close()
return nil, err
}
// Side files are discarded only by an open that selected a slot: an open
// refused at slot selection (a newer format, no valid descriptor) leaves
// the directory as it was. A later refusal (a corrupt map) may follow the
// discard, as before.
if !creating {
if err := discardCutCOWFiles(path); err != nil {
_ = f.Close()
return nil, err
}
}
var other *descriptorV3
otherRaw := b
if id == slotB {
+4 -1
View File
@@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it.
### M7. Host background-cut admission
`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots.
`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). A Normal hold at least `YieldAfter` old (default 5 min) yields its slot at its cut's next staging batch while another cut on the host holds a live ticket (`INV-HOST-CUT-YIELD-001`): the attempt ends as `yielded`, keeps what it staged, and its next attempt takes a ticket at the back; a lone hold never yields. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots.
**Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once.
@@ -632,6 +632,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE |
| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB |
| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB |
@@ -1003,6 +1004,8 @@ Notes:
| `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE |
| `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE |
| `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE |
| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE |
| `INV-HOST-CUT-YIELD-001` | A Normal hold at least YieldAfter old yields its slot at its cut's next staging batch only while another cut on the host holds a live ticket it has not judged stalled; the attempt ends as yielded, never a failure, and keeps what it staged. A lone or urgent hold never yields. | M7 admitted → released (yielded) | `core/hostlimit/limiter.go` `ShouldYield`, `waiterLive`; `core/storage/chunk_layer.go` `stage`; `core/storage/chunk_cut_budget.go` `ErrCutYielded`, `budgetYield`; `core/frontend/durable/provider_chunk.go` `cutPolicy.after` | `TestShouldYieldOnlyAfterSWithALiveWaiter` (`core/hostlimit/yield_test.go`); `TestCutYieldsAtABatchBoundaryAndKeepsItsStaging` (`core/storage/chunk_cut_yield_test.go`); `TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart` (`core/frontend/durable/cut_loop_yield_test.go`) | SlotShareN (yield on the waiting probe, a new ticket at the back); SlotShare rows 189 to 193 | ACTIVE |
| `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
| `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE |
| `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
+8
View File
@@ -13,6 +13,14 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
chunk compared, staged or uploaded), instead of at a fixed 5 minutes of age. `--host-limit-max-hold` is kept as a
deprecated alias of the new flag. The window must exceed one chunk's send time at the paced rate per held slot.
- With the limiter on, chunk fetches are capped per host: `--host-limit-fetch-slots` (default 64) fetches in flight
across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a
slot, in no set order and bounded by its read-miss timeout, and is never refused. A process's first fetch checks the
host's `configuration.json` as a cut admission does, so a fetch-only process with other flags is refused too.
- A normal cut that has held its host slot for `--host-limit-yield-after` (default 5 min) gives the slot to a waiting
cut at its next staging batch, keeping what it staged; its next attempt queues behind the waiters. A lone cut never
yields, and status counts yields apart from failures (`CutYields`).
## Upgrade
- With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was
created with, and v1.1's differ. Upgrade such a host whole: stop every process using the directory, remove
+2
View File
@@ -255,6 +255,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) |
| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure |
| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached |
| `Volumes[].Chunk.Stats.CutsYielded` | uint64 | attempts that gave their host slot to a waiting cut at a staging batch boundary |
| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload |
| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures |
| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read |
@@ -339,6 +340,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.CutSchedule.TicketDueHostNs` | int64 | the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting (omitted when empty) |
| `Volumes[].Chunk.CutSchedule.TicketsSkipped` | uint64 | earlier tickets the waiting cut passed by the skip rule (omitted when empty) |
| `Volumes[].Chunk.CutSchedule.TicketDropReason` | string | why the last ticket was given up before admission, when it was a refusal that waiting cannot fix (omitted when empty) |
| `Volumes[].Chunk.CutSchedule.CutYields` | uint64 | automatic cut attempts that yielded their host slot to a waiting cut (not failures) (omitted when empty) |
| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |