Merge #384: hostlimit background cuts wait while urgent work is pending; launch checks

# Conflicts:
#	docs/design/invariants.md
This commit is contained in:
pingqiu committed 2026-11-22 03:29:24 -08:00
commit 75b0bc731d
13 files changed
+327 -2

No files matched your search

+5 -1
View File
@@ -678,7 +678,11 @@ func run(f flags) int {
cfg.ChunkHolder = chunkHolder(f)
cfg.ChunkStagger = true
if f.chunk.hostLimit.Directory != "" {
limiter, limitErr := hostlimit.New(f.chunk.hostLimit)
limitErr := hostlimit.CheckLaunch(f.chunk.hostLimit)
var limiter *hostlimit.Limiter
if limitErr == nil {
limiter, limitErr = hostlimit.New(f.chunk.hostLimit)
}
if limitErr != nil {
chunkErr = errors.Join(chunkErr, limitErr)
} else {
@@ -247,6 +247,10 @@ func (s *StatusServer) chunkMux() http.Handler {
return mux
}
// codeHostSlotBusy refuses a cut, snapshot or detach because every host
// cut slot is held (retryable).
const codeHostSlotBusy = "host_slot_busy"
func writeChunkJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
@@ -338,6 +342,11 @@ func chunkErrorCode(err error) (int, string, bool) {
return http.StatusConflict, chunkstore.CodeNotChunkVolume, false
case errors.Is(err, context.DeadlineExceeded):
return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true
// Every host cut slot held (host admission, --host-limit-dir): a wait
// that ends when another cut releases its slot. Its own code, so a
// caller can resend on exactly this refusal without reading messages.
case errors.Is(err, hostlimit.ErrSlotsHeld):
return http.StatusServiceUnavailable, codeHostSlotBusy, true
case errors.Is(err, storage.ErrChunkCaptureRefused):
return http.StatusServiceUnavailable, "capture_refused", true
default:
@@ -0,0 +1,30 @@
package volume
import (
"fmt"
"net/http"
"testing"
"github.com/seaweedfs/seaweed-block/core/hostlimit"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// A refusal because every host cut slot is held has its own retryable
// code; other capture refusals, a plain host busy included, keep
// capture_refused.
func TestHostSlotHeldHasItsOwnCode(t *testing.T) {
for _, tc := range []struct {
err error
code string
}{
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld), codeHostSlotBusy},
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrUrgentPending), codeHostSlotBusy},
{fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrBusy), "capture_refused"},
{fmt.Errorf("%w: not a healthy primary", storage.ErrChunkCaptureRefused), "capture_refused"},
} {
status, code, retryable := chunkErrorCode(tc.err)
if status != http.StatusServiceUnavailable || code != tc.code || !retryable {
t.Fatalf("%v: %d %s %v; want 503 %s retryable", tc.err, status, code, retryable, tc.code)
}
}
}
+56
View File
@@ -0,0 +1,56 @@
package hostlimit
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
// CheckLaunch refuses a host-limit configuration whose premises do not
// hold, before the process uses it. The directory must exist as a real
// directory, outside temporary directories that cleaners empty, on a local
// file system (kernel file locks are not shared reliably over network
// file systems), and a configuration already published there by other
// processes must equal this one. The premise that every process on the
// host uses the same directory cannot be checked from one process.
func CheckLaunch(c Config) error {
return checkLaunch(c, []string{"/tmp", "/var/tmp", "/dev/shm", os.TempDir()}, remoteFS)
}
func checkLaunch(c Config, tempRoots []string, remote func(string) (string, bool)) error {
if err := c.Validate(); err != nil {
return err
}
dir := filepath.Clean(c.Directory)
info, err := os.Lstat(dir)
if err != nil {
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("hostlimit: --host-limit-dir %s must be a directory, not a symlink or a file", dir)
}
for _, root := range tempRoots {
root = filepath.Clean(root)
if root != "" && root != "." && (dir == root || strings.HasPrefix(dir, root+string(filepath.Separator))) {
return fmt.Errorf("hostlimit: --host-limit-dir %s is under %s, which temporary-file cleaners empty", dir, root)
}
}
if fs, isRemote := remote(dir); isRemote {
return fmt.Errorf("hostlimit: --host-limit-dir %s is on %s, a network file system; slot locks need a local one", dir, fs)
}
existing, err := os.ReadFile(filepath.Join(dir, "configuration.json"))
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
}
expected, _ := json.Marshal(c)
if string(existing) != string(expected) {
return fmt.Errorf("hostlimit: --host-limit-dir %s is in use with other host-limit flags (%s); every process on the host must use identical flags (this one: %s)", dir, existing, expected)
}
return nil
}
+32
View File
@@ -23,6 +23,16 @@ var ErrBusy = errors.New("hostlimit: no background slot")
// work: retrying once one is released can succeed. Other ErrBusy results
// (an oversized payload, an unusable pool) do not change by waiting.
var ErrSlotsHeld = fmt.Errorf("%w: every slot is held", ErrBusy)
// ErrUrgentPending refuses a Normal admission while an urgent cut runs or
// a caller holds HoldUrgentPending on the host: new background cuts wait
// for it. It is an ErrSlotsHeld, so waiting callers treat it alike.
var ErrUrgentPending = fmt.Errorf("%w: an urgent cut is pending", ErrSlotsHeld)
// urgentPendingFile is the pool file urgent work holds shared; Normal
// admission probes it exclusively, without waiting. It has no content.
const urgentPendingFile = "urgent-pending"
var ErrConfig = errors.New("hostlimit: incompatible host configuration")
var ErrRevoked = errors.New("hostlimit: cut budget revoked")
@@ -72,6 +82,7 @@ type Stats struct {
}
type lease struct {
file *os.File
pending *os.File // urgent only: the shared hold on urgentPendingFile
started time.Time
class Class
fallback bool
@@ -157,6 +168,20 @@ func (l *Limiter) pool(c Class) (*os.File, error) {
if string(existing) != string(expected) {
return nil, ErrConfig
}
if c == Normal {
probe, err := open(urgentPendingFile)
if err != nil {
return nil, err
}
err = tryLock(probe)
_ = probe.Close()
if errors.Is(err, ErrBusy) {
return nil, ErrUrgentPending
}
if err != nil {
return nil, err
}
}
names := []string{}
if c == BackgroundFill || c == Idle {
n, prefix := l.cfg.FillSlots, "fill"
@@ -299,6 +324,10 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (
l.next++
id := l.next
x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort}
if c == Urgent && !fallback {
// Best effort: an urgent cut that cannot signal still runs.
x.pending, _ = holdShared(filepath.Join(l.cfg.Directory, urgentPendingFile))
}
l.live[id] = x
l.stats.Admitted++
l.stats.PayloadReserved += payload
@@ -399,6 +428,9 @@ func (l *Limiter) releaseLoop() {
if x.file != nil {
_ = x.file.Close()
}
if x.pending != nil {
_ = x.pending.Close()
}
l.mu.Lock()
delete(l.live, id)
l.fallback = false
@@ -80,6 +80,12 @@ func TestSlotsUrgentAndJoinedRelease(t *testing.T) {
a.Release(x)
a.Release(x)
settled(t, a)
// A free normal slot is not taken while the urgent cut runs.
if _, e = d.Admit(context.Background(), 1, nil); !errors.Is(e, ErrUrgentPending) {
t.Fatalf("normal admission during an urgent cut: %v", e)
}
b.Release(y)
settled(t, b)
z, e := d.Admit(context.Background(), 1, nil)
if e != nil {
t.Fatal(e)
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
}
return err
}
// lockShared waits for a shared lock on f. An exclusive holder keeps it
// only for a non-blocking probe, so the wait is short.
func lockShared(f *os.File) error {
return syscall.Flock(int(f.Fd()), syscall.LOCK_SH)
}
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
}
return err
}
// lockShared waits for a shared lock on f. An exclusive holder keeps it
// only for a non-blocking probe, so the wait is short.
func lockShared(f *os.File) error {
return windows.LockFileEx(windows.Handle(f.Fd()), 0, 0, 1, 0, &windows.Overlapped{})
}
+33
View File
@@ -0,0 +1,33 @@
package hostlimit
import (
"os"
"path/filepath"
)
// HoldUrgentPending tells every limiter using dir that urgent work is
// pending on the host: until release is called, Normal admissions there
// are refused with ErrUrgentPending. Callers hold it across a stop or a
// drain, so background cuts do not take slots the stop is waiting for.
func HoldUrgentPending(dir string) (release func(), err error) {
f, err := holdShared(filepath.Join(dir, urgentPendingFile))
if err != nil {
return nil, err
}
return func() { _ = f.Close() }, nil
}
func holdShared(path string) (*os.File, error) {
if i, err := os.Lstat(path); err == nil && !i.Mode().IsRegular() {
return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrInvalid}
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err = lockShared(f); err != nil {
_ = f.Close()
return nil, err
}
return f, nil
}
@@ -0,0 +1,110 @@
package hostlimit
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// While a caller holds HoldUrgentPending, Normal admissions on the host
// wait (ErrUrgentPending, an ErrSlotsHeld); urgent ones still run.
func TestNormalWaitsWhileUrgentPendingIsHeld(t *testing.T) {
c := testConfig(t)
l := newTest(t, c)
release, err := HoldUrgentPending(c.Directory)
if err != nil {
t.Fatal(err)
}
if id, err := l.Acquire(context.Background(), Normal, nil); id != 0 || !errors.Is(err, ErrUrgentPending) || !errors.Is(err, ErrSlotsHeld) {
t.Fatalf("normal admission with an urgent pending: id=%d err=%v", id, err)
}
id, err := l.Acquire(context.Background(), Urgent, nil)
if err != nil {
t.Fatalf("urgent admission refused: %v", err)
}
l.Release(id)
release()
waitAdmitted(t, l, Normal)
}
// An urgent cut holds the pending signal for its lease: another process's
// Normal admission waits until the urgent cut is released.
func TestUrgentLeaseHoldsThePendingSignal(t *testing.T) {
c := testConfig(t)
a, b := newTest(t, c), newTest(t, c)
id, err := a.Acquire(context.Background(), Urgent, nil)
if err != nil {
t.Fatal(err)
}
if _, err := b.Acquire(context.Background(), Normal, nil); !errors.Is(err, ErrUrgentPending) {
t.Fatalf("normal admission during an urgent lease: %v", err)
}
a.Release(id)
waitAdmitted(t, b, Normal)
}
func waitAdmitted(t *testing.T, l *Limiter, c Class) {
t.Helper()
for deadline := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) {
id, err := l.Acquire(context.Background(), c, nil)
if err == nil {
l.Release(id)
return
}
if time.Now().After(deadline) {
t.Fatalf("still refused after the pending signal ended: %v", err)
}
}
}
func TestCheckLaunch(t *testing.T) {
local := func(string) (string, bool) { return "", false }
c := testConfig(t)
if err := checkLaunch(c, nil, local); err != nil {
t.Fatalf("a fresh local directory refused: %v", err)
}
refused := map[string]struct {
c Config
roots []string
remote func(string) (string, bool)
want string
}{
"missing": {DefaultConfig(filepath.Join(c.Directory, "missing")), nil, local, "missing"},
"temp root": {c, []string{filepath.Dir(c.Directory)}, local, "temporary-file cleaners"},
"remote": {c, nil, func(string) (string, bool) { return "NFS", true }, "network file system"},
}
file := filepath.Join(t.TempDir(), "f")
if err := os.WriteFile(file, nil, 0o600); err != nil {
t.Fatal(err)
}
refused["file"] = struct {
c Config
roots []string
remote func(string) (string, bool)
want string
}{DefaultConfig(file), nil, local, "must be a directory"}
for name, tc := range refused {
if err := checkLaunch(tc.c, tc.roots, tc.remote); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("%s: %v; want %q", name, err, tc.want)
}
}
// A configuration published by other processes must be identical.
l := newTest(t, c)
id, err := l.Acquire(context.Background(), Normal, nil)
if err != nil {
t.Fatal(err)
}
l.Release(id)
if err := checkLaunch(c, nil, local); err != nil {
t.Fatalf("the same flags refused: %v", err)
}
other := c
other.NormalSlots = 3
if err := checkLaunch(other, nil, local); err == nil || !strings.Contains(err.Error(), "identical flags") {
t.Fatalf("different flags accepted: %v", err)
}
}
@@ -0,0 +1,24 @@
//go:build linux
package hostlimit
import "syscall"
// remoteFS names the network file system dir is on, if it is on one.
func remoteFS(dir string) (string, bool) {
var st syscall.Statfs_t
if syscall.Statfs(dir, &st) != nil {
return "", false
}
switch uint32(st.Type) {
case 0x6969:
return "NFS", true
case 0xFF534D42:
return "CIFS", true
case 0xFE534D42:
return "SMB2", true
case 0x65735546:
return "FUSE", true
}
return "", false
}
@@ -0,0 +1,6 @@
//go:build !linux
package hostlimit
// remoteFS reports no network file system where it cannot tell.
func remoteFS(string) (string, bool) { return "", false }
+4 -1
View File
@@ -412,7 +412,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
304 rows: 233 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 289 new.
307 rows: 236 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 292 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -743,6 +743,9 @@ Notes:
| `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on per-process fallback limits that claim no host-wide bound and are reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `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 |
| `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE |
| `INV-HOST-URGENT-PENDING-001` | While an urgent cut holds its slot, or a caller holds HoldUrgentPending, every Normal admission on the host is refused with ErrUrgentPending (a held-slot wait); urgent admissions still run. | M7 host cut admission (Normal before a slot) | `core/hostlimit/limiter.go` `pool`, `Admit`; `core/hostlimit/pending.go` `HoldUrgentPending` | `TestNormalWaitsWhileUrgentPendingIsHeld`, `TestUrgentLeaseHoldsThePendingSignal` (`core/hostlimit/pending_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
| `INV-HOST-LAUNCH-CHECK-001` | blockvolume refuses to start with a --host-limit-dir that is missing or not a directory, under a temporary directory, on a network file system, or already in use with different host-limit flags. | M7 host cut admission (process start) | `core/hostlimit/launch.go` `CheckLaunch`; `core/hostlimit/remotefs_linux.go`; `cmd/blockvolume/main.go` | `TestCheckLaunch` (`core/hostlimit/pending_test.go`) | — | ACTIVE |
| `INV-HOST-SLOT-BUSY-CODE-001` | The chunk control API refuses a cut, snapshot or detach that host admission refused because every slot is held (or urgent work is pending) with 503 host_slot_busy, retryable; every other capture refusal keeps capture_refused. | M7 free → admitted (refused, wait) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestHostSlotHeldHasItsOwnCode` (`core/host/volume/chunk_host_slot_code_test.go`) | — | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, an intent naming every key of that kind the round preallocated is durable in the filer: one for all candidate chunks, however many upload waves the round uses, and one for all new segments. | M5 Intent → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_FailedPutIntentUploadsNothing` (`core/storage/chunk_layer_intent_test.go`); `TestCutPayloadIntentCountIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |