diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index a64963c9f6..ad55735dc9 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -15,6 +15,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -30,6 +31,7 @@ const ( type chunkFlags struct { detachPrecopy bool + hostLimit hostlimit.Config filer string path string collection string @@ -45,10 +47,17 @@ type chunkFlags struct { func validateChunkFlags(f flags) error { c := f.chunk + if c.hostLimit.Directory != "" { + if err := c.hostLimit.Validate(); err != nil { + return err + } + } else if c.hostLimit != (hostlimit.Config{}) && c.hostLimit != hostlimit.DefaultConfig("") { + return errors.New("--host-limit-* settings require --host-limit-dir") + } if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go new file mode 100644 index 0000000000..7eba88af39 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -0,0 +1,20 @@ +package main + +import ( + "flag" + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { + *c = hostlimit.DefaultConfig("") + fs.StringVar(&c.Directory, "host-limit-dir", "", "shared local directory for background-cut slots; empty disables shared slots") + fs.IntVar(&c.NormalSlots, "host-limit-normal-slots", c.NormalSlots, "host normal-cut slots; identical across processes") + fs.IntVar(&c.UrgentSlots, "host-limit-urgent-slots", c.UrgentSlots, "host reserved urgent-cut slots") + fs.IntVar(&c.FillSlots, "host-limit-fill-slots", c.FillSlots, "host background-fill slots; demand hydration bypasses them") + fs.IntVar(&c.IdleSlots, "host-limit-idle-slots", c.IdleSlots, "host idle-work slots") + fs.Int64Var(&c.PayloadBytes, "host-limit-payload-bytes", c.PayloadBytes, "maximum cut payload per slot") + 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") + fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "urgent-fallback per-process divisor; coordinated host cap is not enforced") + fs.DurationVar(&c.MaxHold, "host-limit-max-hold", c.MaxHold, "cut lease timeout; expiration aborts but waits for admitted I/O before release") +} diff --git a/seaweed-block/cmd/blockvolume/host_limit_test.go b/seaweed-block/cmd/blockvolume/host_limit_test.go new file mode 100644 index 0000000000..939050f42e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestHostCutLimitFlags(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--chunk-filer=x:1") + dir := t.TempDir() + args := append(append([]string{}, base...), "--host-limit-dir="+dir, "--host-limit-normal-slots=2", "--host-limit-urgent-slots=1") + f, e := parseFlags(args) + if e != nil { + t.Fatal(e) + } + if f.chunk.hostLimit.Directory != dir || f.chunk.hostLimit.NormalSlots != 2 || f.chunk.hostLimit.UrgentSlots != 1 { + t.Fatal("lost host limits") + } + for _, extra := range [][]string{{"--host-limit-normal-slots=2"}, {"--host-limit-dir=" + dir, "--host-limit-normal-slots=0"}, {"--host-limit-dir=" + dir, "--host-limit-max-hold=-1s"}, {"--host-limit-dir=" + filepath.Join("relative", "pool")}} { + a := append(append([]string{}, base...), extra...) + if _, e = parseFlags(a); e == nil { + t.Fatalf("accepted invalid limits: %v", extra) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 7185c26da4..9514710a1e 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -31,6 +31,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/ublk" "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -194,6 +195,7 @@ func parseFlags(args []string) (flags, error) { fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device") fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") + registerHostLimitFlags(fs, &f.chunk.hostLimit) fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port") fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)") fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") @@ -662,6 +664,23 @@ func run(f flags) int { cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth cfg.ChunkHolder = chunkHolder(f) + cfg.ChunkStagger = true + if f.chunk.hostLimit.Directory != "" { + limiter, limitErr := hostlimit.New(f.chunk.hostLimit) + if limitErr != nil { + chunkErr = errors.Join(chunkErr, limitErr) + } else { + defer limiter.Close() + cfg.ChunkBudget = limiter + cfg.ChunkPayloadMemoryBudget = f.chunk.hostLimit.PayloadBytes + cfg.ChunkCOWSpillLimit = f.chunk.hostLimit.COWBytes + } + } + // A detach is a graceful stop: the lease guard renews at a short + // cadence for the revocation that follows instead of waiting out + // its renewal delay, until the detach provably aborts and resumes. + cfg.OnChunkDetach = h.WorkspaceStopPending + cfg.OnChunkDetachResumed = h.WorkspaceStopResumed if chunkErr == nil { cfg.ChunkRemoteFor = chunk.remoteFor workspaceRemoteFor = chunk.remoteFor diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 510d3846ef..18ad8b8d3a 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -156,3 +156,28 @@ func TestCutPolicy_NothingDueWhileReconciling(t *testing.T) { t.Fatalf("after reconciliation: %q %v; want an immediate periodic cut", r, ok) } } + +func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { + pol := testPolicy() + s := initialCutSchedule("v1", pol.interval, t0, true) + if !s.lastSuccess.Equal(t0) || !s.firstDue.After(t0) || s.firstDue.After(t0.Add(pol.interval)) { + t.Fatal("phase fabricated success or exceeded first period", s) + } + if _, ok := pol.dueNR(s, s.firstDue.Add(-time.Nanosecond)); ok { + t.Fatal("initial phase ignored") + } + if _, ok := pol.dueNR(s, s.firstDue); !ok { + t.Fatal("first phased cut not due") + } + explicit := t0.Add(s.firstDue.Sub(t0) / 2) + s = s.observe(explicit.UnixNano()) + if !s.lastSuccess.Equal(explicit) || !s.firstDue.IsZero() { + t.Fatal("stagger hid explicit success", s) + } + if _, ok := pol.dueNR(s, explicit.Add(pol.interval-time.Nanosecond)); ok { + t.Fatal("timer advanced before explicit success interval") + } + if _, ok := pol.dueNR(s, explicit.Add(pol.interval)); !ok { + t.Fatal("explicit success did not restart timer") + } +} diff --git a/seaweed-block/core/frontend/durable/host_limit_test.go b/seaweed-block/core/frontend/durable/host_limit_test.go new file mode 100644 index 0000000000..e4b38a628b --- /dev/null +++ b/seaweed-block/core/frontend/durable/host_limit_test.go @@ -0,0 +1,95 @@ +package durable_test + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + holder, e := hostlimit.New(c) + if e != nil { + t.Fatal(e) + } + defer holder.Close() + x, e := holder.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + defer holder.Release(x) + lim, e := hostlimit.New(c) + if e != nil { + t.Fatal(e) + } + defer lim.Close() + r := storage.NewMemChunkRemote() + p, e := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View()) + if e != nil { + t.Fatal(e) + } + defer p.Close() + s := openRecovered(t, p) + if _, e = s.Write(0, block(0x72)); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(context.Background(), "v1"); !errors.Is(e, storage.ErrChunkCaptureRefused) { + t.Fatalf("full cut pool: %v", e) + } + if _, e = s.Write(1, block(0x73)); e != nil { + t.Fatal("limiter blocked write", e) + } + if _, e = s.Sync(); e != nil { + t.Fatal("limiter blocked Flush", e) + } + if b, e := s.Read(0); e != nil || b[0] != 0x72 { + t.Fatal("limiter blocked read", e) + } + h, _ := r.GetHead(context.Background()) + if h.Gen != 0 { + t.Fatal("refused cut published") + } +} + +func TestHostUnusablePoolExplicitDurabilityUsesUrgent(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir() + "/missing") + lim, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer lim.Close() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + s := openRecovered(t, p) + if _, err = s.Write(0, block(0x6a)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if _, err = p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("background cut bypassed missing pool: %v", err) + } + if err = p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatalf("explicit durability was not urgent: %v", err) + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.RemoteLSN < 1 { + t.Fatalf("explicit durability did not publish: %+v %v", head, err) + } + if st := lim.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { + t.Fatalf("wrong durability/periodic policy: %+v", st) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 1c59337323..824d89c2d1 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -182,6 +182,16 @@ type ProviderConfig struct { // ChunkDetachPrecopy attempts bounded rolling cuts before stopping I/O. // Nonconvergence leaves service live; no fallback to an unbounded tail. ChunkDetachPrecopy bool + // OnChunkDetach, optional, is called with the volume id when DetachVolume + // starts a detach (a graceful stop), before the drain and final cut, so + // the host can watch for the coming lease revocation; it returns a token + // for this attempt. OnChunkDetachResumed, optional, is called with that + // token only when the detach provably did not happen and serving resumed; + // a detach that applied, fenced or whose outcome is unknown never calls + // it. Both run under the volume's attach lock: they must not block or + // call back into the provider. + OnChunkDetach func(volumeID string) uint64 + OnChunkDetachResumed func(volumeID string, attempt uint64) // ChunkDirtyThreshold is the number of candidate chunks above which // a cut pre-copies (stages) chunks before its barrier, in rounds of // this size; copy-before-write copies the rest outside the barrier. @@ -194,7 +204,10 @@ type ProviderConfig struct { // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. ChunkPayloadMemoryBudget int64 // ChunkBudget optionally admits cuts and accounts COW bytes through the host limiter. - ChunkBudget storage.Budget + ChunkBudget storage.Budget + ChunkCOWSpillLimit int64 + // ChunkStagger spreads automatic cuts by the stable volume-ID phase. + ChunkStagger bool } // DurableProvider is the production frontend.Provider implementation. @@ -301,6 +314,7 @@ type ChunkStatus struct { Fenced bool RemoteLSN uint64 Stats storage.ChunkLayerStats + HostBudget any `json:",omitempty"` } // NewDurableProvider constructs a provider. view is the ONLY @@ -567,6 +581,9 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { if cv.layer != nil { cs.Attached, cs.Fenced, cs.RemoteLSN, cs.Stats = true, cv.layer.Fenced(), cv.layer.RemoteLSN(), cv.layer.Stats() } + if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok { + cs.HostBudget = budget.Snapshot() + } st.Chunk = cs } out = append(out, st) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 9efc49e3fa..a8d3cf1964 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -15,6 +15,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -361,6 +362,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h holder = proj.ReplicaID } bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} + if pace, ok := p.cfg.ChunkBudget.(interface { + WaitUpload(context.Context, int) error + }); ok { + bound.waitUpload = pace.WaitUpload + } bound.setAttach(ctx) // the attach's calls also end with the caller's ctx defer bound.setAttach(nil) var remote storage.ChunkRemote = bound @@ -381,6 +387,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, + COWSpillLimit: p.cfg.ChunkCOWSpillLimit, CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { @@ -467,7 +474,8 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // attach runs, its calls also end with the attach caller's context. type closeBoundRemote struct { storage.ChunkRemote - done context.Context + done context.Context + waitUpload func(context.Context, int) error mu sync.Mutex attach context.Context @@ -504,6 +512,11 @@ func (r *closeBoundRemote) bind(ctx context.Context) (context.Context, func()) { func (r *closeBoundRemote) Put(ctx context.Context, key string, data []byte) error { c, end := r.bind(ctx) defer end() + if r.waitUpload != nil { + if err := r.waitUpload(c, len(data)); err != nil { + return err + } + } return r.ChunkRemote.Put(c, key, data) } @@ -643,6 +656,7 @@ type cutSchedule struct { failedAt time.Time // end of the last failed automatic cut retryAt time.Time // a failed automatic cut's backoff ends here backoff time.Duration + firstDue time.Time // startup phase only; never a fabricated success } // observe takes in a successful cut the layer reports (any trigger). A @@ -653,6 +667,7 @@ func (s cutSchedule) observe(lastCutNs int64) cutSchedule { c := time.Unix(0, lastCutNs) if c.After(s.lastSuccess) { s.lastSuccess = c + s.firstDue = time.Time{} } if !s.failedAt.IsZero() && c.After(s.failedAt) { s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} @@ -671,7 +686,11 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string if !s.lastAuto.IsZero() && now.Sub(s.lastAuto) < pol.minSpacing { return "", false } - if pol.interval > 0 && now.Sub(s.lastSuccess) >= pol.interval { + deadline := s.lastSuccess.Add(pol.interval) + if !s.firstDue.IsZero() { + deadline = s.firstDue + } + if pol.interval > 0 && !now.Before(deadline) { return "periodic", true } return "", false @@ -681,6 +700,7 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSchedule { s.lastAuto = start if err == nil { + s.firstDue = time.Time{} s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} if end.After(s.lastSuccess) { s.lastSuccess = end @@ -699,6 +719,16 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSc return s } +func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool) cutSchedule { + s := cutSchedule{lastSuccess: now} + if stagger && interval > 0 { + phase := hostlimit.Phase(volumeID, interval) + startup := hostlimit.Phase(volumeID+":startup", min(interval, 10*time.Second)) + s.firstDue = now.Add(max(phase, startup)) + } + return s +} + // chunkLoop runs the volume's automatic cuts under cutPolicy. A refused // cut (not a healthy primary of this lineage, BASE install) is expected // and logged only when it is something else. A fenced layer can never @@ -711,7 +741,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, } - s := cutSchedule{lastSuccess: time.Now()} + s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger) t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -794,7 +824,7 @@ func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID if err != nil { return err } - return layer.MakeRemoteDurable(ctx, lsn) + return layer.MakeRemoteDurable(hostlimit.WithClass(ctx, hostlimit.Urgent), lsn) } // chunkFenced refuses a volume whose layer attached fenced: HEAD belongs to @@ -825,6 +855,9 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN return storage.ChunkCutResult{}, fmt.Errorf("durable: cut of %s to LSN %d: that LSN was never written (last %d)", volumeID, minLSN, last) } } + if minLSN > 0 { + ctx = hostlimit.WithClass(ctx, hostlimit.Urgent) + } r, err := layer.Cut(ctx) if err != nil { return storage.ChunkCutResult{}, err @@ -890,6 +923,15 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } }() + var resumed func() + notifyDetach := func() { + if hook := p.cfg.OnChunkDetach; hook != nil { + attempt := hook(volumeID) + if done := p.cfg.OnChunkDetachResumed; done != nil { + resumed = func() { done(volumeID, attempt) } + } + } + } var r storage.ChunkCutResult if p.cfg.ChunkDetachPrecopy { owner, ok := layer.(interface { @@ -898,9 +940,11 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if !ok { return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown) } + // Notify outside captureMu: the host callback may take its own state lock. + notifyDetach() // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) - r, err = owner.PrecopyDetach(cutCtx, func() bool { + r, err = owner.PrecopyDetach(hostlimit.WithClass(cutCtx, hostlimit.Urgent), func() bool { if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } @@ -917,10 +961,16 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } if !r.Precopy.Frozen { p.mu.Lock() - if !p.closed && h.chunk == layer { + active := !p.closed && h.chunk == layer + if active { p.startChunkLoop(volumeID, h, layer) } p.mu.Unlock() + // No final freeze occurred: clear only this still-serving attempt's + // fast-poll token. A prior stopped/unknown detach must remain pending. + if active && !h.chunkDetach && h.backend.operational.Load() && !layer.Fenced() && resumed != nil { + resumed() + } return r, 0, err } } else { @@ -929,6 +979,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st trace("cut", start.Add(freeze*3/4)) } h.chunkDetach = true + notifyDetach() if stop := p.testDetachStopIO; stop != nil { err = stop(cutCtx) } else { @@ -936,7 +987,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } if err == nil { p.stopChunkLoop(h) - if r, err = layer.Detach(cutCtx); err == nil { + if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { return r, h.storage.NextLSN() - 1, nil } } @@ -971,7 +1022,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st case how == storage.DetachFenced: return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err) default: - return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err, resumed) } } @@ -982,8 +1033,8 @@ const ( // resumeAfterDetach undoes a detach that provably did not happen: the // periodic cuts restart, the stop is lifted, and the volume serves again. -// The caller holds h.attachMu. -func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { +// Only then is resumed (if set) called. The caller holds h.attachMu. +func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error, resumed func()) error { p.mu.Lock() closed := p.closed || h.chunk != layer if !closed { @@ -995,6 +1046,9 @@ func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer } h.chunkDetach = false h.backend.SetOperational(true, "chunk detach aborted: serving resumed") + if resumed != nil { + resumed() + } log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) return fmt.Errorf("%w: %w", ErrDetachAborted, cause) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go new file mode 100644 index 0000000000..fff58df4c8 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go @@ -0,0 +1,198 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// detachHooks records the detach hooks: each detach gets the next token. +type detachHooks struct { + mu sync.Mutex + next uint64 + started []string + resumed []string +} + +func (k *detachHooks) detach(id string) uint64 { + k.mu.Lock() + defer k.mu.Unlock() + k.next++ + k.started = append(k.started, id) + return k.next +} + +func (k *detachHooks) resume(id string, attempt uint64) { + k.mu.Lock() + defer k.mu.Unlock() + k.resumed = append(k.resumed, fmt.Sprintf("%s#%d", id, attempt)) +} + +func (k *detachHooks) calls() (started, resumed []string) { + k.mu.Lock() + defer k.mu.Unlock() + return append([]string(nil), k.started...), append([]string(nil), k.resumed...) +} + +// hookedProvider is detachFixture's volume (one cut published, one dirty +// block) with both detach hooks wired. +func hookedProvider(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend, *detachHooks) { + t.Helper() + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + k := &detachHooks{} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + OnChunkDetach: k.detach, + OnChunkDetachResumed: k.resume, + }, v1View()) + if err != nil { + t.Fatalf("NewDurableProvider: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + ctx := context.Background() + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(ctx, 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(ctx, "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(ctx, 8192, block(2)); err != nil { + t.Fatal(err) + } + return remote, p, b, k +} + +// A detach (graceful stop) tells the host once, with the volume id; the +// lease-fence drain, a StopIO of its own, does not. +func TestWALStoreChunk_DetachCallsStopHook(t *testing.T) { + ctx := context.Background() + t.Run("detach", func(t *testing.T) { + _, p, _, k := hookedProvider(t) + if _, _, err := p.DetachVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if started, resumed := k.calls(); len(started) != 1 || started[0] != "v1" || len(resumed) != 0 { + t.Fatalf("detach hook calls %q, resumed %q; want [v1], none", started, resumed) + } + }) + t.Run("fence-stop", func(t *testing.T) { + _, p, _, k := hookedProvider(t) + if err := p.Backend("v1").StopIO(ctx, "workspace lease fenced"); err != nil { + t.Fatal(err) + } + if started, resumed := k.calls(); len(started) != 0 || len(resumed) != 0 { + t.Fatalf("lease-fence StopIO called the detach hooks: %q %q", started, resumed) + } + }) +} + +// The hook runs before the drain starts (and so before the final cut, which +// follows the drain): the host learns of the stop while guest I/O is still +// being drained, not after. +func TestWALStoreChunk_DetachHookPrecedesDrain(t *testing.T) { + _, p, _, k := hookedProvider(t) + drains, hookedAtDrain := 0, -1 + durable.SetTestDetachStopIO(p, func(ctx context.Context) error { + drains++ + started, _ := k.calls() + hookedAtDrain = len(started) + return p.Backend("v1").StopIO(ctx, "chunk detach: I/O stopped until a new attach") + }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", r, err) + } + if drains != 1 { + t.Fatalf("drain ran %d times, want 1", drains) + } + if hookedAtDrain != 1 { + t.Fatalf("detach hook calls when the drain started: %d, want 1 (the hook precedes the drain)", hookedAtDrain) + } +} + +// The resume hook is called with the attempt's own token exactly when a +// failed detach provably did not happen and serving resumed; a detach that +// applied, is fenced, or whose outcome is unknown never calls it. +func TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort(t *testing.T) { + ctx := context.Background() + t.Run("refused-cas-aborts", func(t *testing.T) { + remote, p, b, k := hookedProvider(t) + remote.set(func(r *faultRemote) { r.casMode = "precondition" }) + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err) + } + if _, resumed := k.calls(); len(resumed) != 1 || resumed[0] != "v1#1" { + t.Fatalf("resume hook calls %q, want [v1#1]", resumed) + } + assertServing(t, p, b, remote) + }) + t.Run("failed-drain-aborts-each-attempt", func(t *testing.T) { + remote, p, b, k := hookedProvider(t) + durable.SetTestDetachStopIO(p, func(context.Context) error { return context.Canceled }) + for i := 0; i < 2; i++ { + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach %d with a failed drain: %v; want ErrDetachAborted", i+1, err) + } + } + if _, resumed := k.calls(); len(resumed) != 2 || resumed[0] != "v1#1" || resumed[1] != "v1#2" { + t.Fatalf("resume hook calls %q, want [v1#1 v1#2] (each attempt's own token)", resumed) + } + durable.SetTestDetachStopIO(p, nil) + assertServing(t, p, b, remote) + }) + t.Run("applied-lost-reply", func(t *testing.T) { + remote, p, _, k := hookedProvider(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost" }) + if r, _, err := p.DetachVolume(ctx, "v1"); err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose CAS applied: %+v %v; want the detached result", r, err) + } + if _, resumed := k.calls(); len(resumed) != 0 { + t.Fatalf("resume hook called on an applied detach: %q", resumed) + } + }) + t.Run("unknown", func(t *testing.T) { + remote, p, _, k := hookedProvider(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err) + } + if _, resumed := k.calls(); len(resumed) != 0 { + t.Fatalf("resume hook called on an unknown detach outcome: %q", resumed) + } + remote.set(func(r *faultRemote) { r.getHeadErr = nil }) + }) + t.Run("fenced", func(t *testing.T) { + remote, p, _, k := hookedProvider(t) + cur, err := remote.MemChunkRemote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + newer := cur + newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" + if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + t.Fatal(err) + } + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("detach against a newer epoch: %v; want fenced", err) + } + if _, resumed := k.calls(); len(resumed) != 0 { + t.Fatalf("resume hook called on a fenced detach: %q", resumed) + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 3685deeb12..ae086c106e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -69,12 +69,17 @@ func TestPrecopyFreezeDoesNotWaitForAdmittedIO(t *testing.T) { } } -func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView) *durable.DurableProvider { +func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView, hooks ...*detachHooks) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + if len(hooks) > 0 { + cfg.OnChunkDetach = hooks[0].detach + cfg.OnChunkDetachResumed = hooks[0].resume + } + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -112,7 +117,8 @@ func TestPrecopyProviderPublishesExactDetachedImage(t *testing.T) { func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { remote := storage.NewMemChunkRemote() view := &parkView{stubView: v1View()} - p := precopyProvider(t, remote, view) + k := &detachHooks{} + p := precopyProvider(t, remote, view, k) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -140,6 +146,9 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { t.Fatalf("report=%+v err=%v", r.Precopy, err) } + if started, resumed := k.calls(); len(started) != 1 || len(resumed) != 1 { + t.Fatalf("nonconverged hooks: started=%v resumed=%v", started, resumed) + } if h, _ := remote.GetHead(ctx); h.State == storage.ChunkHeadDetached { t.Fatal("busy owner detached") } @@ -160,6 +169,9 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { if err != nil { t.Fatal(err) } + if started, resumed := k.calls(); len(started) != 2 || len(resumed) != 1 { + t.Fatalf("successful retry hooks: started=%v resumed=%v", started, resumed) + } if !bytes.Equal(headBlock(t, remote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote, 2), block(0x9b)) { t.Fatal("retry lost admitted bytes") } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1743562f8..392e12a380 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -553,7 +554,8 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } - r, err := c.p.CutVolume(ctx, volumeID, 0) + // A named seal is urgent even without a minimum LSN. + r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { return chunkstore.SnapshotInfo{}, err } diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 92ef54d65d..2f26ba2509 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -8,17 +8,20 @@ import ( "sync" "testing" + "errors" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) type fakeChunkProvider struct { - cut storage.ChunkCutResult - cutErr error - detach storage.ChunkCutResult - last uint64 - cuts int - lastMin uint64 + cut storage.ChunkCutResult + cutErr error + cutCheck func(context.Context) error + detach storage.ChunkCutResult + last uint64 + cuts int + lastMin uint64 } type adapterManifestFiler struct { @@ -45,9 +48,14 @@ func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) return append([]byte(nil), b...), nil } -func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { +func (f *fakeChunkProvider) CutVolume(ctx context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { f.cuts++ f.lastMin = minLSN + if f.cutCheck != nil { + if err := f.cutCheck(ctx); err != nil { + return storage.ChunkCutResult{}, err + } + } if f.cutErr != nil { return storage.ChunkCutResult{}, f.cutErr } @@ -201,3 +209,30 @@ func TestChunkControl_CutMinLSNAndDetach(t *testing.T) { t.Fatalf("detach: %+v %v", d, err) } } + +func TestChunkControl_NamedSnapshotUsesUrgentFallback(t *testing.T) { + fp, ctl := adapterFixture(t) + c := hostlimit.DefaultConfig(t.TempDir() + "/missing") + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer l.Close() + fp.cutCheck = func(ctx context.Context) error { + id, err := l.Admit(ctx, 1, nil) + if err == nil { + l.Release(id) + } + return err + } + if _, err = ctl.Cut(context.Background(), "v1", 0); !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("ordinary cut bypassed missing pool: %v", err) + } + info, err := ctl.Snapshot(context.Background(), "v1", ChunkSnapshotRequest{Name: "named", RequestID: "named-r1"}) + if err != nil || info.Name != "named" { + t.Fatalf("named seal did not use urgent fallback: %+v %v", info, err) + } + if st := l.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { + t.Fatalf("wrong named/normal policy: %+v", st) + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index bd077186d4..4da678246d 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -171,6 +171,11 @@ type Host struct { // workspaceLeaseMu -> guard.mu; never hold either across RPC or drain. workspaceLeaseMu sync.Mutex workspaceLeaseFenced bool + // workspaceStopPending is the guard's stop-pending mode, kept here for a + // guard installed later; workspaceStopAttempt numbers detach attempts so + // only the latest one's resume clears it. + workspaceStopPending bool + workspaceStopAttempt uint64 readyOnce atomic.Bool readyMarkerMu sync.Mutex supportingReadyMarks map[string]struct{} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index cf99b03c73..3a829129a8 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -39,6 +39,72 @@ type WorkspaceLeaseGuard struct { // because the shutdown it triggers is otherwise silent (issue #205). cause string logged bool + // stopPending is a scheduling-only mode, it changes no admission or ACK + // rule: set by StopPending when a detach starts, cleared by + // ClearStopPending only when that detach provably did not happen and + // serving resumed; otherwise it lasts until the guard fences. kick wakes + // Run from its sleep. + stopPending bool + kick chan struct{} + // after schedules Run's sleep between renewals (time.After; tests + // replace it before Run starts to observe the delays chosen). + after func(time.Duration) <-chan time.Time +} + +// stopPendingPoll caps Run's sleep after a completed renewal while a stop is +// pending (the normal sleep is up to 10 s). It bounds scheduling only: a kick +// does not interrupt a renewal already in flight, and the time from a +// revocation to its ACK also includes that renewal, the drain and the ACK. +const stopPendingPoll = 250 * time.Millisecond + +// StopPending records that a graceful stop of this workspace has begun (the +// chunk layer is being detached) and wakes Run to renew at once; while it +// stays pending Run sleeps at most stopPendingPoll between renewals. +// Idempotent, safe from any goroutine, never blocks and makes no RPC. +func (g *WorkspaceLeaseGuard) StopPending() { + g.mu.Lock() + g.stopPending = true + g.mu.Unlock() + select { + case g.kick <- struct{}{}: + default: + } +} + +// ClearStopPending leaves stop-pending after a detach that provably did not +// happen (serving resumed): Run's next sleep is the normal renewal delay +// again, and a kick not yet consumed is dropped. Never blocks, makes no RPC. +func (g *WorkspaceLeaseGuard) ClearStopPending() { + g.mu.Lock() + g.stopPending = false + g.mu.Unlock() + select { + case <-g.kick: + default: + } +} + +// renewDelay is Run's sleep after a renewal: a third of the remaining lease +// (1 s before any grant) within [50 ms, 10 s], and at most stopPendingPoll +// while a stop is pending. +func (g *WorkspaceLeaseGuard) renewDelay() time.Duration { + g.mu.Lock() + delay := g.until.Sub(g.now()) / 3 + if g.until.IsZero() { + delay = time.Second + } + pending := g.stopPending + g.mu.Unlock() + if delay < 50*time.Millisecond { + delay = 50 * time.Millisecond + } + if delay > 10*time.Second { + delay = 10 * time.Second + } + if pending && delay > stopPendingPoll { + delay = stopPendingPoll + } + return delay } // fenceLocked latches the fence and records its first cause. Caller holds mu. @@ -76,7 +142,7 @@ func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseC if now == nil { now = time.Now } - return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch}, stop: stop, now: now}, nil + return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch}, stop: stop, now: now, kick: make(chan struct{}, 1), after: time.After}, nil } func (g *WorkspaceLeaseGuard) Projection() frontend.Projection { @@ -263,18 +329,7 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error { if closed { return err } - g.mu.Lock() - delay := g.until.Sub(g.now()) / 3 - if g.until.IsZero() { - delay = time.Second - } - g.mu.Unlock() - if delay < 50*time.Millisecond { - delay = 50 * time.Millisecond - } - if delay > 10*time.Second { - delay = 10 * time.Second - } + wake := g.after(g.renewDelay()) select { case <-ctx.Done(): g.operation.Lock() @@ -285,7 +340,8 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error { err := g.drain(ctx, false) g.operation.Unlock() return err - case <-time.After(delay): + case <-wake: + case <-g.kick: } } } diff --git a/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go b/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go new file mode 100644 index 0000000000..a9643e7bb3 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go @@ -0,0 +1,452 @@ +package volume + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// joinTimeout bounds a test's wait for a lease worker it cancelled. The +// guard's own drain budget is 5 s for the stop callback plus 2 s for an ACK; +// the join allows that and leaves margin for scheduling and settlement. +const joinTimeout = 15 * time.Second + +// startJoined runs run in a worker. Before the worker starts it registers the +// cleanup that cancels it, waits for it (at most joinTimeout; a timeout fails +// the test) and only after the worker is seen done runs teardown, so a failed +// assertion never closes resources under a still-running worker. +func startJoined(t *testing.T, run func(context.Context) error, teardown func()) <-chan error { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done, finished := make(chan error, 1), make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-finished: + if teardown != nil { + teardown() + } + case <-time.After(joinTimeout): + t.Errorf("lease worker not joined within %s of its cancel; teardown skipped", joinTimeout) + } + }) + go func() { + defer close(finished) + done <- run(ctx) + }() + return done +} + +// stopPendingClient grants 30 s leases (normal renewal delay 10 s) and counts +// renewals; revoking makes the next reply revoke. +type stopPendingClient struct { + mu sync.Mutex + renewals int + revoking bool + acks int +} + +func (c *stopPendingClient) client() workspaceTestClient { + return workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.renewals++ + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second), Revoking: c.revoking}, nil + }, ack: func() error { + c.mu.Lock() + c.acks++ + c.mu.Unlock() + return nil + }} +} + +func (c *stopPendingClient) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.renewals +} + +// scheduler replaces the guard's sleep: it records every delay Run chooses +// after a renewal and wakes Run only when the test fires it, so the cadence +// is asserted on the delay itself, with no wall-clock window. +type scheduler struct { + delays chan time.Duration + wake chan time.Time +} + +func newScheduler(g *WorkspaceLeaseGuard) *scheduler { + s := &scheduler{delays: make(chan time.Duration, 16), wake: make(chan time.Time)} + g.after = func(d time.Duration) <-chan time.Time { + s.delays <- d + return s.wake + } + return s +} + +// next is the delay Run chose after its latest renewal. A Run that never +// renews again (a kick it ignored) fails here, after a generous bound. +func (s *scheduler) next(t *testing.T, what string) time.Duration { + t.Helper() + select { + case d := <-s.delays: + return d + case <-time.After(5 * time.Second): + t.Fatalf("%s: Run did not renew and schedule its next sleep", what) + return 0 + } +} + +func (s *scheduler) fire(t *testing.T) { + t.Helper() + select { + case s.wake <- time.Now(): + case <-time.After(5 * time.Second): + t.Fatal("Run is not sleeping on the scheduler") + } +} + +// pendingSleepBound is the documented stop-pending bound +// (INV-WS-STOP-PENDING-001), written out so a changed stopPendingPoll fails. +const pendingSleepBound = 250 * time.Millisecond + +// The schedule, step by step: a 30 s lease sleeps ~10 s; StopPending renews +// at once (the kick, without the sleep ending) and every following sleep is +// at most pendingSleepBound; ClearStopPending restores the normal sleep; a +// revocation then fences and ACKs. +func TestWorkspaceLeaseStopPendingSchedule(t *testing.T) { + c := &stopPendingClient{} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, c.client(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + s := newScheduler(g) + done := startJoined(t, g.Run, nil) + + if d := s.next(t, "first renewal"); d <= 5*time.Second { + t.Fatalf("sleep %s after renewing a 30 s lease, want the normal ~10 s", d) + } + + g.StopPending() + // The kick alone wakes Run: the scheduled sleep is never fired here. + if d := s.next(t, "renewal on the StopPending kick"); d > pendingSleepBound { + t.Fatalf("sleep %s after the kicked renewal, want at most %s", d, pendingSleepBound) + } + if n := c.count(); n != 2 { + t.Fatalf("%d renewals after the kick, want 2", n) + } + s.fire(t) + if d := s.next(t, "renewal while pending"); d > pendingSleepBound { + t.Fatalf("sleep %s after a renewal while a stop is pending, want at most %s", d, pendingSleepBound) + } + + g.ClearStopPending() + s.fire(t) + if d := s.next(t, "renewal after clear"); d <= 5*time.Second { + t.Fatalf("sleep %s after ClearStopPending, want the normal ~10 s again", d) + } + if n := c.count(); n != 4 { + t.Fatalf("%d renewals, want 4 (a stale kick must not add one)", n) + } + + c.mu.Lock() + c.revoking = true + c.mu.Unlock() + s.fire(t) + select { + case err := <-done: + if err != nil { + t.Fatalf("revocation ACK path: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("guard did not fence on the revocation") + } + c.mu.Lock() + acks := c.acks + c.mu.Unlock() + if g.FenceCause() != "revoked by the master" || acks != 1 { + t.Fatalf("cause %q acks %d", g.FenceCause(), acks) + } +} + +// StopPending and ClearStopPending before Run, repeated, never block. +func TestWorkspaceLeaseStopPendingNeverBlocks(t *testing.T) { + c := &stopPendingClient{} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, c.client(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + finished := make(chan struct{}) + go func() { + for i := 0; i < 5; i++ { + g.StopPending() + g.ClearStopPending() + g.StopPending() + } + close(finished) + }() + select { + case <-finished: + case <-time.After(time.Second): + t.Fatal("StopPending/ClearStopPending blocked") + } +} + +func guardPending(g *WorkspaceLeaseGuard) bool { + g.mu.Lock() + defer g.mu.Unlock() + return g.stopPending +} + +// Detach attempts are numbered: only the latest attempt's resume clears +// stop-pending, on the host and on the installed guard; an older attempt's, +// another volume's or a repeated resume changes nothing. +func TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt(t *testing.T) { + h := workspaceRuntimeHost(t, "127.0.0.1:1", true) + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, (&stopPendingClient{}).client(), &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: 3}, func(context.Context) (uint64, error) { return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + h.view.workspaceGuard.Store(g) + pending := func() (bool, bool) { + h.workspaceLeaseMu.Lock() + defer h.workspaceLeaseMu.Unlock() + return h.workspaceStopPending, guardPending(g) + } + if a := h.WorkspaceStopPending("other"); a != 0 { + t.Fatalf("another volume's detach got token %d, want 0", a) + } + if hp, gp := pending(); hp || gp { + t.Fatal("another volume's detach set stop-pending") + } + older := h.WorkspaceStopPending("v1") + newer := h.WorkspaceStopPending("v1") + if older == 0 || newer == older { + t.Fatalf("attempt tokens %d, %d: want distinct and non-zero", older, newer) + } + h.WorkspaceStopResumed("v1", older) + if hp, gp := pending(); !hp || !gp { + t.Fatalf("an older attempt's resume cleared a newer pending detach (host %v, guard %v)", hp, gp) + } + h.WorkspaceStopResumed("other", newer) + h.WorkspaceStopResumed("v1", 0) + if hp, gp := pending(); !hp || !gp { + t.Fatal("a resume for another volume or token 0 cleared stop-pending") + } + h.WorkspaceStopResumed("v1", newer) + if hp, gp := pending(); hp || gp { + t.Fatalf("the latest attempt's resume left stop-pending (host %v, guard %v)", hp, gp) + } + if d := g.renewDelay(); d <= stopPendingPoll { + t.Fatalf("sleep %s after the resume, want the normal delay", d) + } + h.WorkspaceStopPending("v1") + h.WorkspaceStopResumed("v1", newer) // the resumed attempt again: stale now + if hp, gp := pending(); !hp || !gp { + t.Fatal("a stale resume cleared a later detach") + } +} + +// detachFaultRemote makes the next detach fail one way. +type detachFaultRemote struct { + *storage.MemChunkRemote + mu sync.Mutex + casMode string // "refuse": precondition, not applied; "lost": not applied, error + getHeadErr error +} + +var errInjectedRemote = errors.New("injected remote fault") + +func (r *detachFaultRemote) set(mode string, headErr error) { + r.mu.Lock() + r.casMode, r.getHeadErr = mode, headErr + r.mu.Unlock() +} + +func (r *detachFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + r.mu.Lock() + err := r.getHeadErr + r.mu.Unlock() + if err != nil { + return storage.ChunkHead{}, err + } + return r.MemChunkRemote.GetHead(ctx) +} + +func (r *detachFaultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + r.mu.Lock() + mode := r.casMode + r.casMode = "" + r.mu.Unlock() + switch mode { + case "refuse": + return 0, storage.ErrChunkHeadPrecondition + case "lost": + return 0, errInjectedRemote + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + +// detachHost is a leased workspace host whose provider reports detaches to +// it through both hooks, as blockvolume wires them. +type detachHost struct { + h *Host + p *durable.DurableProvider + wire *runtimeLeaseServer + remote *detachFaultRemote + done <-chan error +} + +func newDetachHost(t *testing.T) *detachHost { + t.Helper() + var stopped atomic.Bool + d := &detachHost{wire: &runtimeLeaseServer{ttl: 30 * time.Second, stopped: &stopped}, remote: &detachFaultRemote{MemChunkRemote: storage.NewMemChunkRemote()}} + d.h = workspaceRuntimeHost(t, runtimeWire(t, d.wire), true) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return d.remote, nil }, + OnChunkDetach: d.h.WorkspaceStopPending, + OnChunkDetachResumed: d.h.WorkspaceStopResumed}, d.h.ProjectionView()) + if err != nil { + t.Fatal(err) + } + d.p = p + handedOver := false + t.Cleanup(func() { // only while no runtime exists; see handedOver below + if !handedOver { + _ = p.Close() + } + }) + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + // From here the provider is closed only by the joined teardown, after the + // runtime is seen done. + handedOver = true + d.done = startJoined(t, func(ctx context.Context) error { + return d.h.RunWorkspaceLease(ctx, func(c context.Context, id *control.WorkspaceIdentity) (uint64, error) { + if err := p.Backend("v1").StopIO(c, "workspace lease fenced"); err != nil { + return 0, err + } + stopped.Store(true) + head, err := d.remote.MemChunkRemote.GetHead(c) + return head.Gen, err + }) + }, func() { _ = p.Close() }) + runtimeAwait(t, "leased operational provider", func() bool { + st := p.DurableStatuses() + return d.h.ProjectionView().Projection().Healthy && len(st) == 1 && st[0].Operational && d.h.view.workspaceGuard.Load() != nil + }) + return d +} + +func (d *detachHost) pending() bool { + d.h.workspaceLeaseMu.Lock() + defer d.h.workspaceLeaseMu.Unlock() + g := d.h.view.workspaceGuard.Load() + return d.h.workspaceStopPending || (g != nil && guardPending(g)) +} + +func (d *detachHost) renewals() int { + d.wire.mu.Lock() + defer d.wire.mu.Unlock() + return d.wire.renewals +} + +// Host wiring: the provider's detach hook makes the real lease runtime see +// the revocation that follows a detach soon after it, where the 30 s lease's +// renewal delay would be 10 s. +func TestWorkspaceHostDetachHookFencesWithinPoll(t *testing.T) { + d := newDetachHost(t) + if _, _, err := d.p.DetachVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if !d.pending() { + t.Fatal("a detach did not set stop-pending") + } + d.wire.mu.Lock() + d.wire.revoking = true + d.wire.mu.Unlock() + revoked := time.Now() + if err := runtimeDone(t, d.done); err != nil { + t.Fatalf("revocation ACK path: %v", err) + } + if took := time.Since(revoked); took > 3*time.Second { + t.Fatalf("revocation ACKed %s after it, want well inside the 10 s renewal delay", took) + } + d.wire.mu.Lock() + acks := d.wire.acks + d.wire.mu.Unlock() + if acks != 1 { + t.Fatalf("acks %d, want 1", acks) + } +} + +// A failed detach that provably did not happen resumes serving and leaves +// stop-pending: the guard is back on its normal renewal delay. A detach whose +// outcome is unknown, or that is fenced, stays stopped and stays pending. +func TestWorkspaceHostFailedDetachStopPendingByOutcome(t *testing.T) { + t.Run("aborted-resumes-normal-cadence", func(t *testing.T) { + d := newDetachHost(t) + d.remote.set("refuse", nil) + if _, _, err := d.p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err) + } + if st := d.p.DurableStatuses(); len(st) != 1 || !st[0].Operational { + t.Fatal("serving did not resume after the aborted detach") + } + if d.pending() { + t.Fatal("stop-pending survived a detach that provably aborted and resumed serving") + } + if delay := d.h.view.workspaceGuard.Load().renewDelay(); delay <= stopPendingPoll { + t.Fatalf("guard sleep %s after the resume, want the normal delay", delay) + } + // The sleep already running when the resume came is at most one poll; + // after it the guard renews once more and then sleeps ~10 s. Pending, + // it would renew about four times a second. + time.Sleep(4 * stopPendingPoll) + before := d.renewals() + time.Sleep(8 * stopPendingPoll) + if after := d.renewals(); after != before { + t.Fatalf("%d renewals in %s after the resume, want none (normal cadence)", after-before, 8*stopPendingPoll) + } + }) + t.Run("unknown-stays-pending", func(t *testing.T) { + d := newDetachHost(t) + d.remote.set("lost", errInjectedRemote) + if _, _, err := d.p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err) + } + if !d.pending() { + t.Fatal("stop-pending cleared on an unknown detach outcome") + } + d.remote.set("", nil) + }) + t.Run("fenced-stays-pending", func(t *testing.T) { + d := newDetachHost(t) + ctx := context.Background() + cur, err := d.remote.MemChunkRemote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + newer := cur + newer.Epoch, newer.Holder = max(cur.Epoch, 3)+1, "another-holder" // above the host's assignment epoch 3 + if _, err := d.remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + t.Fatal(err) + } + if _, _, err := d.p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("detach against a newer epoch: %v; want fenced", err) + } + if !d.pending() { + t.Fatal("stop-pending cleared on a fenced detach") + } + }) +} diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index 41c72a54c9..13e8d55c15 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -44,6 +44,7 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, // The guard is not yet shared: publish it already fenced if a // synchronous shutdown won the race with this installer. guard.fenced = h.workspaceLeaseFenced || ctx.Err() != nil + guard.stopPending = h.workspaceStopPending h.view.workspaceGuard.Store(guard) h.workspaceLeaseMu.Unlock() return guard.Run(ctx) @@ -56,6 +57,47 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, } } +// WorkspaceStopPending is called when a graceful stop of volumeID has begun +// (its chunk layer is being detached): the lease guard renews at once and +// then sleeps at most stopPendingPoll between renewals, instead of its normal +// renewal delay, so it sees the revocation that follows sooner. Scheduling +// only: what the guard admits or ACKs is unchanged. It returns this detach +// attempt's token for WorkspaceStopResumed; other volume ids are ignored +// (token 0). Never blocks. +func (h *Host) WorkspaceStopPending(volumeID string) uint64 { + if volumeID != h.cfg.VolumeID { + return 0 + } + h.workspaceLeaseMu.Lock() + defer h.workspaceLeaseMu.Unlock() + h.workspaceStopAttempt++ + h.workspaceStopPending = true + if g := h.view.workspaceGuard.Load(); g != nil { + g.StopPending() + } + return h.workspaceStopAttempt +} + +// WorkspaceStopResumed is called when the detach attempt that returned +// attempt provably did not happen and the volume serves again: stop-pending +// ends and the guard returns to its normal renewal delay. A token other than +// the latest attempt's (an older attempt, 0, another volume) changes nothing, +// so an old attempt's resume never clears a newer pending detach. Never blocks. +func (h *Host) WorkspaceStopResumed(volumeID string, attempt uint64) { + if volumeID != h.cfg.VolumeID || attempt == 0 { + return + } + h.workspaceLeaseMu.Lock() + defer h.workspaceLeaseMu.Unlock() + if !h.workspaceStopPending || attempt != h.workspaceStopAttempt { + return + } + h.workspaceStopPending = false + if g := h.view.workspaceGuard.Load(); g != nil { + g.ClearStopPending() + } +} + // FenceWorkspaceLease closes admission synchronously before process shutdown. // Physical drain remains owned by run's stop callback; this never ACKs/cuts. func (h *Host) FenceWorkspaceLease() { diff --git a/seaweed-block/core/host/volume/workspace_runtime_test.go b/seaweed-block/core/host/volume/workspace_runtime_test.go index aa23922b4e..824d57d149 100644 --- a/seaweed-block/core/host/volume/workspace_runtime_test.go +++ b/seaweed-block/core/host/volume/workspace_runtime_test.go @@ -78,6 +78,7 @@ type runtimeLeaseServer struct { ttl time.Duration disabled, blocked, revoking bool blockedCalls int // renewals that arrived while blocked + renewals int // every renewal that arrived acks int ackGen uint64 first chan struct{} @@ -88,6 +89,7 @@ type runtimeLeaseServer struct { func (s *runtimeLeaseServer) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { s.once.Do(func() { close(s.first) }) s.mu.Lock() + s.renewals++ ttl, disabled, blocked, revoking := s.ttl, s.disabled, s.blocked, s.revoking s.mu.Unlock() if disabled { diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go new file mode 100644 index 0000000000..3ab765d5e6 --- /dev/null +++ b/seaweed-block/core/hostlimit/limiter.go @@ -0,0 +1,478 @@ +// Package hostlimit coordinates background cuts across cooperating host processes. +// Guest I/O never acquires a slot. An unavailable pool skips background work; +// urgent seals may use explicitly uncoordinated per-process limits. +package hostlimit + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "hash/fnv" + "io" + "log" + "os" + "path/filepath" + "sync" + "time" +) + +var ErrBusy = errors.New("hostlimit: no background slot") +var ErrConfig = errors.New("hostlimit: incompatible host configuration") +var ErrRevoked = errors.New("hostlimit: cut budget revoked") + +type Class uint8 + +const ( + Normal Class = iota + Urgent + BackgroundFill + Idle +) + +type classKey struct{} + +func WithClass(ctx context.Context, c Class) context.Context { + return context.WithValue(ctx, classKey{}, c) +} + +type Config struct { + Directory string + NormalSlots, UrgentSlots int + FillSlots, IdleSlots int + PayloadBytes, COWBytes int64 + BytesPerSecond int64 + FallbackVolumes int + MaxHold 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, MaxHold: 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.MaxHold <= 0 { + return errors.New("hostlimit: invalid configuration") + } + return nil +} + +type Stats struct { + Active int + PayloadReserved, COWReserved int64 + Admitted, Skipped, Fallback, Revoked, Released uint64 + FallbackActive bool + AdmissionNs, MaxHoldNs uint64 + SkippedByClass [4]uint64 + LastPoolError string +} +type lease struct { + file *os.File + started time.Time + class Class + fallback bool + payload, cow int64 + abort func(error) + timer *time.Timer + releasing bool + revoked bool +} +type Limiter struct { + testBeforeConfigWrite func() // test-only crash boundary; immutable before first admission + testBeforeConfigLock func(*os.File) // test-only fault boundary; immutable before first admission + cfg Config + mu sync.Mutex + admitWG sync.WaitGroup + next uint64 + live map[uint64]*lease + stats Stats + closed bool + wake chan struct{} + done chan struct{} + nextUpload time.Time + fallback bool +} + +func New(c Config) (*Limiter, error) { + if err := c.Validate(); err != nil { + return nil, err + } + l := &Limiter{cfg: c, live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})} + go l.releaseLoop() + return l, nil +} + +// Phase is stable across process restarts; it never delays guest readiness. +func Phase(volume string, period time.Duration) time.Duration { + if period <= 0 { + return 0 + } + h := fnv.New64a() + _, _ = h.Write([]byte(volume)) + return time.Duration(h.Sum64() % uint64(period)) +} + +// 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) (*os.File, error) { + info, err := os.Lstat(l.cfg.Directory) + if 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) + } + guard, err := open("configuration.lock") + if err != nil { + return nil, err + } + defer guard.Close() + if l.testBeforeConfigLock != nil { + l.testBeforeConfigLock(guard) + } + if err = tryLock(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 + } + names := []string{} + if c == BackgroundFill || c == Idle { + n, prefix := l.cfg.FillSlots, "fill" + if c == Idle { + n, prefix = l.cfg.IdleSlots, "idle" + } + for i := 0; i < n; i++ { + names = append(names, fmt.Sprintf("%s-%d", prefix, i)) + } + } else { + if c == Urgent { + for i := 0; i < l.cfg.UrgentSlots; i++ { + names = append(names, fmt.Sprintf("urgent-%d", i)) + } + } + for i := 0; i < l.cfg.NormalSlots; i++ { + names = append(names, fmt.Sprintf("normal-%d", i)) + } + } + for _, name := range names { + f, e := open(name) + if e != nil { + return nil, e + } + if e = tryLock(f); e == nil { + return f, nil + } + _ = f.Close() + if !errors.Is(e, ErrBusy) { + return nil, e + } + } + return nil, ErrBusy +} + +// publishConfig runs under the configuration OS lock. A killed initializer +// leaves an ignored temporary file, never a partially visible configuration. +func (l *Limiter) publishConfig(path string, data []byte) error { + f, err := os.CreateTemp(l.cfg.Directory, ".configuration-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + defer f.Close() + if l.testBeforeConfigWrite != nil { + l.testBeforeConfigWrite() + } + n, err := f.Write(data) + if err != nil { + return err + } + if n != len(data) { + return io.ErrShortWrite + } + if err = f.Sync(); err != nil { + return err + } + if err = f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), path) +} + +// Acquire exposes background fill/idle permits to future background callers. +// Demand hydration must bypass this API; these permits carry no cut payload. +func (l *Limiter) Acquire(ctx context.Context, c Class, abort func(error)) (uint64, error) { + return l.Admit(WithClass(ctx, c), 0, abort) +} + +func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + start := time.Now() + defer func() { l.mu.Lock(); l.stats.AdmissionNs += uint64(time.Since(start)); l.mu.Unlock() }() + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return 0, ErrRevoked + } + l.admitWG.Add(1) + l.mu.Unlock() + defer l.admitWG.Done() + if err := ctx.Err(); err != nil { + return 0, err + } + if payload < 0 || payload > l.cfg.PayloadBytes { + return 0, ErrBusy + } + c, _ := ctx.Value(classKey{}).(Class) + if c > Idle || (c >= BackgroundFill && payload != 0) { + return 0, ErrBusy + } + f, err := l.pool(c) + if errors.Is(err, ErrBusy) { + l.mu.Lock() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + return 0, err + } + if errors.Is(err, ErrConfig) { + l.mu.Lock() + warn := l.stats.LastPoolError != err.Error() + l.stats.LastPoolError = err.Error() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + if warn { + log.Printf("hostlimit: shared pool configuration refused; background protection may lag: %v", err) + } + return 0, err + } + if err != nil && c != Urgent { + l.mu.Lock() + warn := l.stats.LastPoolError != err.Error() + l.stats.LastPoolError = err.Error() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + if warn { + log.Printf("hostlimit: shared pool unavailable; background work skipped: %v", err) + } + return 0, errors.Join(ErrBusy, err) + } + fallback := err != nil // Urgent fallback has no coordinated host resource/rate bound. + l.mu.Lock() + if l.closed || ctx.Err() != nil || len(l.live) >= l.cfg.NormalSlots+l.cfg.UrgentSlots+l.cfg.FillSlots+l.cfg.IdleSlots { + l.stats.Skipped++ + l.mu.Unlock() + if f != nil { + _ = f.Close() + } + if ctx.Err() != nil { + return 0, ctx.Err() + } + return 0, ErrBusy + } + l.next++ + id := l.next + x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort} + l.live[id] = x + l.stats.Admitted++ + l.stats.PayloadReserved += payload + l.stats.Active++ + l.fallback = fallback + for _, held := range l.live { + l.fallback = l.fallback || held.fallback + } + l.stats.FallbackActive = l.fallback + warnFallback := fallback && l.stats.Fallback == 0 + if fallback { + l.stats.LastPoolError = err.Error() + l.stats.Fallback++ + l.stats.FallbackActive = true + } + x.timer = time.AfterFunc(l.cfg.MaxHold, func() { l.revoke(id) }) + l.mu.Unlock() + if warnFallback { + log.Printf("hostlimit: shared cut pool unavailable (%v); using static fallback, shared memory/spill cap NOT enforced", err) + } + return id, nil +} +func (l *Limiter) revoke(id uint64) { + l.mu.Lock() + x := l.live[id] + var abort func(error) + if x != nil && !x.releasing && !x.revoked { + x.revoked = true + abort = x.abort + l.stats.Revoked++ + } + l.mu.Unlock() + if abort != nil { + abort(ErrRevoked) + } +} + +// ReserveCOW is guest-path accounting only: no OS calls, RPC or waiting for a slot. +func (l *Limiter) ReserveCOW(id uint64, n int64) error { + l.mu.Lock() + x := l.live[id] + if x == nil || x.releasing || x.revoked || n < 0 || (x.class >= BackgroundFill && n != 0) { + l.mu.Unlock() + return ErrRevoked + } + if n > l.cfg.COWBytes-x.cow { + x.revoked = true + abort := x.abort + l.stats.Revoked++ + l.mu.Unlock() + if abort != nil { + abort(ErrRevoked) + } + return ErrRevoked + } + x.cow += n + l.stats.COWReserved += n + l.mu.Unlock() + return nil +} + +// Release only marks settled work; one owned worker closes descriptors. Until +// then the kernel slot remains unavailable, conservatively retaining capacity. +func (l *Limiter) Release(id uint64) { + l.mu.Lock() + if x := l.live[id]; x != nil && !x.releasing { + x.releasing = true + x.timer.Stop() + } + l.mu.Unlock() + select { + case l.wake <- struct{}{}: + default: + } +} +func (l *Limiter) releaseLoop() { + defer close(l.done) + for range l.wake { + for { + l.mu.Lock() + var id uint64 + var x *lease + for k, v := range l.live { + if v.releasing { + id, x = k, v + break + } + } + if x == nil { + stop := l.closed && len(l.live) == 0 + l.mu.Unlock() + if stop { + return + } + break + } + l.mu.Unlock() + if x.file != nil { + _ = x.file.Close() + } + l.mu.Lock() + delete(l.live, id) + l.fallback = false + for _, held := range l.live { + l.fallback = l.fallback || held.fallback + } + l.stats.FallbackActive = l.fallback + l.stats.Active-- + l.stats.PayloadReserved -= x.payload + l.stats.COWReserved -= x.cow + l.stats.Released++ + l.stats.MaxHoldNs = max(l.stats.MaxHoldNs, uint64(time.Since(x.started))) + l.mu.Unlock() + } + } +} +func (l *Limiter) Snapshot() any { l.mu.Lock(); defer l.mu.Unlock(); return l.stats } + +// WaitUpload paces background payload PUTs, including parallel uploader workers. +// One process spaces reservations by the previous payload/rate. Its first +// payload is immediate; debt survives its leases but resets on a new process. +// For a constant share r and maximum payload B, one process reserves at most +// r*T+B bytes over T. Fresh processes each add a new B; neither process/slot +// churn nor uncoordinated fallback has a fixed host-rate bound. Wire overhead +// is excluded. Local WAL flushing, COW reads and demand hydration bypass it. +func (l *Limiter) WaitUpload(ctx context.Context, n int) error { + if n < 0 { + return ErrBusy + } + for { + if err := ctx.Err(); err != nil { + return err + } + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return ErrRevoked + } + div := l.cfg.NormalSlots + l.cfg.UrgentSlots + if l.fallback { + div = l.cfg.FallbackVolumes + } + rate := l.cfg.BytesPerSecond / int64(div) + if rate < 1 { + rate = 1 + } + now := time.Now() + wait := time.Until(l.nextUpload) + if wait <= 0 { + l.nextUpload = now.Add(time.Duration(float64(n) / float64(rate) * float64(time.Second))) + l.mu.Unlock() + return ctx.Err() + } + l.mu.Unlock() + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} + +// Close cancels cuts but cannot release their physical-I/O ownership. Callers +// must still settle their cuts and call Release; Close joins that settlement. +func (l *Limiter) Close() { + l.mu.Lock() + l.closed = true + callbacks := []func(error){} + for _, x := range l.live { + if !x.releasing && x.abort != nil { + callbacks = append(callbacks, x.abort) + } + } + l.mu.Unlock() + l.admitWG.Wait() + for _, a := range callbacks { + a(ErrRevoked) + } + select { + case l.wake <- struct{}{}: + default: + } + <-l.done +} diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go new file mode 100644 index 0000000000..cbc5f3cdb5 --- /dev/null +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -0,0 +1,595 @@ +package hostlimit + +import ( + "bufio" + "context" + "errors" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func testConfig(t *testing.T) Config { + t.Helper() + c := DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + return c +} +func newTest(t *testing.T, c Config) *Limiter { + t.Helper() + l, e := New(c) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { + l.mu.Lock() + ids := make([]uint64, 0, len(l.live)) + for id := range l.live { + ids = append(ids, id) + } + l.mu.Unlock() + for _, id := range ids { + l.Release(id) + } + l.Close() + }) + return l +} +func settled(t *testing.T, l *Limiter) { + t.Helper() + deadline := time.After(3 * time.Second) + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + if l.Snapshot().(Stats).Active == 0 { + return + } + select { + case <-deadline: + t.Fatal("release did not settle") + case <-tick.C: + } + } +} +func TestSlotsUrgentAndJoinedRelease(t *testing.T) { + c := testConfig(t) + a, b, d := newTest(t, c), newTest(t, c), newTest(t, c) + x, e := a.Admit(context.Background(), c.PayloadBytes, nil) + if e != nil { + t.Fatal(e) + } + defer a.Release(x) + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("normal bypass: %v", e) + } + y, e := b.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + defer b.Release(y) + if _, e = d.Admit(WithClass(context.Background(), Urgent), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("urgent bypass: %v", e) + } + a.Release(x) + a.Release(x) + settled(t, a) + z, e := d.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + d.Release(z) + settled(t, d) +} +func TestCOWAbortHoldsSlotUntilWorkerSettlement(t *testing.T) { + c := testConfig(t) + a, b := newTest(t, c), newTest(t, c) + revoked := make(chan struct{}, 1) + x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} }) + if e != nil { + t.Fatal(e) + } + defer a.Release(x) + if e = a.ReserveCOW(x, c.COWBytes); e != nil { + t.Fatal(e) + } + if e = a.ReserveCOW(x, 1); !errors.Is(e, ErrRevoked) { + t.Fatal(e) + } + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("no abort") + } + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("revocation released live I/O: %v", e) + } + a.Release(x) + settled(t, a) +} +func TestHoldExpiryAndCloseDoNotSteal(t *testing.T) { + c := testConfig(t) + c.MaxHold = 30 * time.Millisecond + a, b := newTest(t, c), newTest(t, c) + revoked := make(chan struct{}, 4) + x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} }) + if e != nil { + t.Fatal(e) + } + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("no expiry") + } + done := make(chan struct{}) + go func() { a.Close(); close(done) }() + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("Close did not cancel") + } + select { + case <-done: + t.Fatal("Close abandoned worker") + default: + } + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatal("lease stolen", e) + } + a.Release(x) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Close not joined") + } +} +func TestFallbackAndConfigMismatch(t *testing.T) { + c := testConfig(t) + a := newTest(t, c) + x, e := a.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + a.Release(x) + settled(t, a) + a.Close() + bad := c + bad.NormalSlots++ + b := newTest(t, bad) + for _, class := range []Class{Normal, Urgent} { + if _, e = b.Admit(WithClass(context.Background(), class), 1, nil); !errors.Is(e, ErrConfig) { + t.Fatalf("config mismatch bypassed cap: class=%d err=%v", class, e) + } + } + if st := b.Snapshot().(Stats); st.LastPoolError == "" || st.Skipped != 2 || st.Fallback != 0 { + t.Fatal("configuration refusal was silent", st) + } + c.Directory += "-missing" + f := newTest(t, c) + x, e = f.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + if !f.Snapshot().(Stats).FallbackActive { + t.Fatal("degraded cap hidden") + } + f.Release(x) + settled(t, f) + if st := f.Snapshot().(Stats); st.FallbackActive || st.Fallback != 1 { + t.Fatalf("settled fallback status: %+v", st) + } +} +func TestRateCancellationAndPhase(t *testing.T) { + c := testConfig(t) + c.BytesPerSecond = 1024 + l := newTest(t, c) + if e := l.WaitUpload(context.Background(), 2048); e != nil { + t.Fatal(e) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if e := l.WaitUpload(ctx, 2048); !errors.Is(e, context.DeadlineExceeded) { + t.Fatal(e) + } + seen := map[time.Duration]bool{} + for i := 0; i < 200; i++ { + v := fmt.Sprint(i) + p := Phase(v, time.Minute) + if p < 0 || p >= time.Minute || p != Phase(v, time.Minute) { + t.Fatal("bad phase") + } + seen[p] = true + } + if len(seen) < 190 { + t.Fatal("phase collision", len(seen)) + } +} +func TestProcessSlotHelper(t *testing.T) { + dir := os.Getenv("SWBLOCK_TEST_LIMITER_DIR") + if dir == "" { + return + } + c := DefaultConfig(dir) + c.NormalSlots = 1 + c.UrgentSlots = 1 + l, e := New(c) + if e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_TEST_LIMITER_INIT_GATE") == "1" { + l.testBeforeConfigWrite = func() { fmt.Println("CONFIG-WRITE"); _, _ = bufio.NewReader(os.Stdin).ReadByte() } + } + _, e = l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + fmt.Println("HELD") + _, _ = bufio.NewReader(os.Stdin).ReadByte() +} +func TestKilledProcessReleasesButLiveHolderDoesNot(t *testing.T) { + c := testConfig(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProcessSlotHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_LIMITER_DIR="+c.Directory) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + in, e := cmd.StdinPipe() + if e != nil { + t.Fatal(e) + } + defer in.Close() + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = 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("child failed") + } + case <-time.After(15 * time.Second): + t.Fatal("child not ready") + } + l := newTest(t, c) + if _, e = l.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("live child not counted: %v", e) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + _ = cmd.Wait() + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal("dead child retained slot", e) + } + l.Release(x) + settled(t, l) +} + +func TestBackgroundPoolsDoNotBorrowCutReservations(t *testing.T) { + c := testConfig(t) + c.FillSlots = 1 + c.IdleSlots = 1 + l := newTest(t, c) + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(x) + y, e := l.Acquire(context.Background(), BackgroundFill, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(y) + if _, e = l.Acquire(context.Background(), BackgroundFill, nil); !errors.Is(e, ErrBusy) { + t.Fatal("fill exceeded independent pool", e) + } + z, e := l.Acquire(context.Background(), Idle, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(z) + if e = l.ReserveCOW(y, 1); !errors.Is(e, ErrRevoked) { + t.Fatal("fill consumed cut spill", e) + } +} + +type heldLog struct { + entered, release chan struct{} + once sync.Once +} + +func (w *heldLog) Write(p []byte) (int, error) { + w.once.Do(func() { close(w.entered) }) + <-w.release + return len(p), nil +} +func TestFallbackLogDoesNotHoldCOWAccountingLock(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + gate := &heldLog{entered: make(chan struct{}), release: make(chan struct{})} + before := log.Writer() + log.SetOutput(gate) + defer log.SetOutput(before) + defer close(gate.release) + done := make(chan struct{}) + go func() { _, _ = l.Admit(WithClass(context.Background(), Urgent), 1, nil); close(done) }() + select { + case <-gate.entered: + case <-time.After(5 * time.Second): + t.Fatal("fallback log not reached") + } + if !l.mu.TryLock() { + t.Fatal("blocked log holds guest COW accounting lock") + } + l.mu.Unlock() +} + +func TestLastFallbackReleaseClearsActiveStatus(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + id, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatal(err) + } + if !l.Snapshot().(Stats).FallbackActive { + t.Fatal("fallback not reported while held") + } + l.Release(id) + settled(t, l) + st := l.Snapshot().(Stats) + if st.FallbackActive || st.PayloadReserved != 0 || st.COWReserved != 0 || st.Released != 1 { + t.Fatalf("last fallback release left stale status: %+v", st) + } +} + +func TestConfigurationLockFailurePreservesPoolPolicy(t *testing.T) { + for _, class := range []Class{Normal, Urgent} { + t.Run(fmt.Sprint(class), func(t *testing.T) { + l := newTest(t, testConfig(t)) + var lockErr error + l.testBeforeConfigLock = func(f *os.File) { + if err := f.Close(); err != nil { + t.Fatal(err) + } + lockErr = tryLock(f) + } + id, err := l.Acquire(context.Background(), class, nil) + if lockErr == nil || errors.Is(lockErr, ErrBusy) { + t.Fatalf("fault did not cause non-contention lock error: %v", lockErr) + } + st := l.Snapshot().(Stats) + if class == Normal { + if id != 0 || !errors.Is(err, ErrBusy) || !errors.Is(err, lockErr) || st.SkippedByClass[Normal] != 1 || st.Fallback != 0 { + t.Fatalf("configuration lock fault lost cause: id=%d err=%v stats=%+v", id, err, st) + } + } else { + if err != nil || id == 0 || st.Fallback != 1 || !st.FallbackActive { + t.Fatalf("configuration lock fault refused urgent fallback: id=%d err=%v stats=%+v", id, err, st) + } + l.Release(id) + } + if st.LastPoolError != lockErr.Error() { + t.Fatalf("configuration lock alarm lost cause: got %q want %q", st.LastPoolError, lockErr) + } + }) + } +} + +func TestConfigurationLockContentionRefusesAllClasses(t *testing.T) { + c := testConfig(t) + f, err := os.OpenFile(filepath.Join(c.Directory, "configuration.lock"), os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if err = tryLock(f); err != nil { + t.Fatal(err) + } + for _, class := range []Class{Normal, Urgent} { + l := newTest(t, c) + id, err := l.Acquire(context.Background(), class, nil) + st := l.Snapshot().(Stats) + if id != 0 || !errors.Is(err, ErrBusy) || st.Fallback != 0 || st.FallbackActive || st.LastPoolError != "" || st.SkippedByClass[class] != 1 { + t.Fatalf("configuration contention bypassed cap: class=%d id=%d err=%v stats=%+v", class, id, err, st) + } + } +} + +func TestHealthyAdmissionDoesNotHideOlderFallbackLease(t *testing.T) { + c := testConfig(t) + c.Directory = filepath.Join(c.Directory, "late-pool") + l := newTest(t, c) + x, e := l.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + if e = os.Mkdir(c.Directory, 0700); e != nil { + t.Fatal(e) + } + y, e := l.Acquire(context.Background(), BackgroundFill, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(y) + if !l.Snapshot().(Stats).FallbackActive { + t.Fatal("healthy admission hid an active uncoordinated lease") + } + l.Release(x) + deadline := time.After(3 * time.Second) + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for l.Snapshot().(Stats).Active != 1 { + select { + case <-deadline: + t.Fatal("fallback lease not released") + case <-tick.C: + } + } + if l.Snapshot().(Stats).FallbackActive { + t.Fatal("settled fallback lease still degrades healthy owner") + } +} + +func TestKilledInitializerDoesNotPublishPartialConfiguration(t *testing.T) { + c := testConfig(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProcessSlotHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_LIMITER_DIR="+c.Directory, "SWBLOCK_TEST_LIMITER_INIT_GATE=1") + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + in, e := cmd.StdinPipe() + if e != nil { + t.Fatal(e) + } + defer in.Close() + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + ready := make(chan bool, 1) + go func() { + s := bufio.NewScanner(out) + for s.Scan() { + if s.Text() == "CONFIG-WRITE" { + ready <- true + return + } + } + ready <- false + }() + select { + case ok := <-ready: + if !ok { + t.Fatal("initializer did not reach write boundary") + } + case <-time.After(15 * time.Second): + t.Fatal("initializer boundary not reached") + } + if _, e = os.Stat(filepath.Join(c.Directory, "configuration.json")); !errors.Is(e, os.ErrNotExist) { + t.Fatal("unpublished configuration became visible", e) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + _ = cmd.Wait() + l := newTest(t, c) + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal("successor did not recover interrupted initialization", e) + } + defer l.Release(x) + if l.Snapshot().(Stats).FallbackActive { + t.Fatal("successor silently bypassed shared cap") + } +} + +func TestUnusablePoolClassPolicy(t *testing.T) { + for _, class := range []Class{Normal, Urgent, BackgroundFill, Idle} { + t.Run(fmt.Sprint(class), func(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + id, err := l.Acquire(context.Background(), class, nil) + st := l.Snapshot().(Stats) + if class == Urgent { + if err != nil || st.Fallback != 1 || !st.FallbackActive || st.LastPoolError == "" { + t.Fatalf("urgent fallback: id=%d err=%v stats=%+v", id, err, st) + } + l.Release(id) + } else if !errors.Is(err, ErrBusy) || id != 0 || st.Admitted != 0 || st.SkippedByClass[class] != 1 || st.Fallback != 0 || st.LastPoolError == "" { + t.Fatalf("background bypassed unavailable pool: class=%d id=%d err=%v stats=%+v", class, id, err, st) + } + }) + } +} + +func TestPacingDebtSurvivesOwnLeaseTurnover(t *testing.T) { + c := testConfig(t) + c.BytesPerSecond = 2 // one byte/second per coordinated cut slot + l := newTest(t, c) + first, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + if err = l.WaitUpload(context.Background(), 4<<20); err != nil { + t.Fatal(err) + } + l.Release(first) + settled(t, l) + next, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(next) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if err = l.WaitUpload(ctx, 1); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("same-process debt reset at lease turnover: %v", err) + } +} + +func TestPacingProcessHelper(t *testing.T) { + dir := os.Getenv("SWBLOCK_TEST_PACING_DIR") + if dir == "" { + return + } + c := DefaultConfig(dir) + c.NormalSlots, c.UrgentSlots, c.BytesPerSecond = 1, 1, 2 + l, err := New(c) + if err != nil { + t.Fatal(err) + } + id, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer func() { l.Release(id); l.Close() }() + // Start the pacing budget after process startup and slot admission. + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err = l.WaitUpload(ctx, 4<<20); err != nil { + t.Fatalf("fresh process inherited another process's pacing debt: %v", err) + } + fmt.Println("FRESH-PACING 4194304") +} + +func TestPacingFreshProcessesDoNotShareDebt(t *testing.T) { + dir := t.TempDir() + const starts = 6 + start := time.Now() + for i := 0; i < starts; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPacingProcessHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_PACING_DIR="+dir) + out, err := cmd.CombinedOutput() + cancel() + if err != nil || !strings.Contains(string(out), "FRESH-PACING 4194304") { + t.Fatalf("fresh holder %d: %v\n%s", i, err, out) + } + } + // Each new process gets an immediate first reservation. Slot reuse does + // not preserve pacing debt, so these bytes cannot certify a host-rate cap. + t.Logf("fresh_processes=%d attempted_payload_bytes=%d elapsed=%s", starts, starts*(4<<20), time.Since(start)) +} diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go new file mode 100644 index 0000000000..ff77b2a3da --- /dev/null +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -0,0 +1,17 @@ +//go:build !windows + +package hostlimit + +import ( + "errors" + "os" + "syscall" +) + +func tryLock(f *os.File) error { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { + return ErrBusy + } + return err +} diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go new file mode 100644 index 0000000000..6cd06b16d9 --- /dev/null +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package hostlimit + +import ( + "errors" + "golang.org/x/sys/windows" + "os" +) + +func tryLock(f *os.File) error { + err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return ErrBusy + } + return err +} diff --git a/seaweed-block/core/storage/chunk_host_budget_test.go b/seaweed-block/core/storage/chunk_host_budget_test.go new file mode 100644 index 0000000000..2fa955eccf --- /dev/null +++ b/seaweed-block/core/storage/chunk_host_budget_test.go @@ -0,0 +1,54 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "testing" +) + +func TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin(t *testing.T) { + s, l, f, gate := cowFixture(t) + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + c.COWBytes = ctChunkBytes - 1 + budget, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + contender, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { gate.unblock(); _ = l.Close(); budget.Close(); contender.Close() }) + l.cfg.Budget = budget + before := f.stats().head.Gen + done, errs := cowStartCut(t, l, gate) + if _, err = s.Write(5, makeBlock(ctBlockSize, 0xeb)); err != nil { + t.Fatal("host cap failed guest write:", err) + } + ticket, admitErr := contender.Admit(context.Background(), 1, nil) + if admitErr == nil { + contender.Release(ticket) + } + if !errors.Is(admitErr, hostlimit.ErrBusy) { + t.Fatalf("revoked but unjoined cut lost permit: %v", admitErr) + } + gate.unblock() + cowWaitSignal(t, done, "host-budget abort settlement") + if err = <-errs; !errors.Is(err, hostlimit.ErrRevoked) { + t.Fatalf("cut abort: %v", err) + } + if f.stats().head.Gen != before { + t.Fatal("host-cap aborted cut published") + } + b, err := s.Read(5) + if err != nil || !bytes.Equal(b, makeBlock(ctBlockSize, 0xeb)) { + t.Fatal("guest bytes lost after cut abort", err) + } + if l.Stats().CutsAborted["budget_revoked"] != 1 { + t.Fatal("host cap abort not reported") + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 97e3a0a084..8b1152d2cd 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -389,3 +389,17 @@ Native pre-copy streams logical reads directly to remote while remaining candida A cut does not pin WAL space or defer flushing. Local reads validate and re-resolve across dirty-map retirement and slot reuse. CopyFinish releases local chunk ownership; every PUT retry sends the same immutable slot, while lazy fills use the cut's fixed base HEAD. + + +### Host background-cut budget + +```mermaid +stateDiagram-v2 + Free --> Admitted: OS slot before staging/barrier + Admitted --> Draining: cancellation or lease expiry + Admitted --> Joined: workers settle + Draining --> Joined: workers settle + Joined --> Free: descriptor closed +``` + +Guest I/O never acquires a slot. An unavailable pool skips background cuts; urgent and named seals may use per-process fallback with an alarm. Active coordinated reservations exclude orphaned crash spill. Upload pacing debt survives leases in one process, but a new process starts fresh, so arbitrary process turnover has no fixed host-rate bound. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4a71b24968..a4e22a1c18 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -149,6 +149,10 @@ stateDiagram-v2 [*] --> NoLease NoLease --> Valid: renewal reply for this volume, replica and epoch Valid --> Valid: renewal before the local deadline + Valid --> StopPending: detach started (renew at once) + StopPending --> StopPending: renewal, then sleep at most 250 ms + StopPending --> Valid: that detach provably aborted, serving resumed + StopPending --> Fenced: deadline passed, invalid reply, or revoking Valid --> Fenced: deadline passed, invalid reply, or revoking Fenced --> Drained: frontend and cuts stopped Drained --> Acked: revocation acknowledged with the HEAD gen @@ -170,7 +174,10 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | -| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` | +| StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` | +| StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | | Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | | Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | | (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` | @@ -315,6 +322,10 @@ snapshot lifetime; local persistence does not bypass it. and refusal after Recover. Missing map coverage still forbids checkpoint advancement; the earlier unmapped dark fixture is not a production geometry. +### M7. Host background-cut admission + +`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. 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; expiry 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. + ## Part B. Invariant ledger 81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. @@ -436,6 +447,7 @@ Notes: | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | @@ -444,6 +456,7 @@ Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. +- `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. ### B.5 Workspace: the cut pipeline @@ -463,6 +476,8 @@ Notes: | `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | | `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | +| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | 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-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | 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 | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | diff --git a/seaweed-block/docs/spec/HostBudget.tla b/seaweed-block/docs/spec/HostBudget.tla new file mode 100644 index 0000000000..bae8554b27 --- /dev/null +++ b/seaweed-block/docs/spec/HostBudget.tla @@ -0,0 +1,66 @@ +----------------------------- MODULE HostBudget ----------------------------- +\* Active coordinated reservations only: fallback, pacing, RSS and retained +\* crash scratch bytes are outside this abstraction. Crash frees active slots. +EXTENDS Integers, FiniteSets, TLC +CONSTANTS N, SlotCount, Payload, Spill, EarlyRelease, AtomicConfig +Owners == 1..N +Slots == 1..SlotCount +VARIABLES phase, owner, slot, saved, cfg, initializer +vars == <> +Init == /\ cfg = "absent" + /\ initializer = 0 + /\ phase = [o \in Owners |-> "free"] + /\ owner = [s \in Slots |-> 0] + /\ slot = [o \in Owners |-> 0] + /\ saved = [o \in Owners |-> 0] +Admit(o,s) == /\ cfg = "ready" + /\ phase[o] = "free" /\ owner[s] = 0 + /\ (o = N \/ s < SlotCount) + /\ phase' = [phase EXCEPT ![o] = "active"] + /\ owner' = [owner EXCEPT ![s] = o] + /\ slot' = [slot EXCEPT ![o] = s] + /\ UNCHANGED <> +Save(o) == /\ phase[o] = "active" /\ saved[o] < Spill + /\ saved' = [saved EXCEPT ![o] = @ + 1] + /\ UNCHANGED <> +Abort(o) == /\ phase[o] = "active" + /\ phase' = [phase EXCEPT ![o] = "draining"] + /\ owner' = IF EarlyRelease THEN [owner EXCEPT ![slot[o]] = 0] ELSE owner + /\ UNCHANGED <> +Join(o) == /\ phase[o] \in {"active","draining"} + /\ phase' = [phase EXCEPT ![o] = "joined"] + /\ UNCHANGED <> +Release(o) == /\ phase[o] = "joined" + /\ owner' = [owner EXCEPT ![slot[o]] = 0] + /\ phase' = [phase EXCEPT ![o] = "free"] + /\ slot' = [slot EXCEPT ![o] = 0] + /\ saved' = [saved EXCEPT ![o] = 0] + /\ UNCHANGED <> +Crash(o) == /\ phase[o] # "free" + /\ owner' = [owner EXCEPT ![slot[o]] = 0] + /\ phase' = [phase EXCEPT ![o] = "free"] + /\ slot' = [slot EXCEPT ![o] = 0] + /\ saved' = [saved EXCEPT ![o] = 0] + /\ UNCHANGED <> +BeginConfig(o) == /\ cfg = "absent" + /\ cfg' = IF AtomicConfig THEN "writing" ELSE "partial" + /\ initializer' = o + /\ UNCHANGED <> +PublishConfig == /\ cfg \in {"writing","partial"} + /\ cfg' = "ready" /\ initializer' = 0 + /\ UNCHANGED <> +CrashInitializer == /\ cfg \in {"writing","partial"} + /\ cfg' = "absent" /\ initializer' = 0 + /\ UNCHANGED <> +Next == (\E o \in Owners: BeginConfig(o)) \/ PublishConfig \/ CrashInitializer \/ + (\E o \in Owners,s \in Slots: Admit(o,s)) \/ + (\E o \in Owners: Save(o) \/ Abort(o) \/ Join(o) \/ Release(o) \/ Crash(o)) +Spec == Init /\ [][Next]_vars +NoPartialConfig == cfg # "partial" +ConfigBeforeAdmission == (\E o \in Owners: phase[o] # "free") => cfg = "ready" +HeldUntilJoined == \A o \in Owners: phase[o] # "free" => owner[slot[o]] = o +RECURSIVE Total(_) +Total(n) == IF n=0 THEN 0 ELSE saved[n]+Total(n-1) +PayloadBound == Cardinality({o \in Owners: phase[o] # "free"})*Payload <= SlotCount*Payload +SpillBound == Total(N) <= SlotCount*Spill +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index ae3adb124e..98c2c668f4 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -311,3 +311,9 @@ TLC. This is an abstraction: physical fsync success, byte layout, crash recovery both-slot retirement, timing and multiple writers remain covered by their other models and actual Go controls. Do not treat finite liveness checking as an end-to-end wall-clock latency guarantee. Keep long model runs off tp04. + +## HostBudget + +`HostBudget.tla` abstracts cooperating process slots, COW reservation and joined release. Config `HostBudget.cfg` checks three owners/two slots; `HostBudget_early_release.cfg` must violate HeldUntilJoined. It excludes degraded static fallback and does not prove filesystem locks, rates or physical-I/O deadlines. Native subprocess tests cover lock lifetime. + +HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. diff --git a/seaweed-block/docs/spec/cfg/HostBudget.cfg b/seaweed-block/docs/spec/cfg/HostBudget.cfg new file mode 100644 index 0000000000..37f2082ee0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=FALSE +AtomicConfig=TRUE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound diff --git a/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg b/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg new file mode 100644 index 0000000000..6cf3a12ea2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=TRUE +AtomicConfig=TRUE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound diff --git a/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg b/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg new file mode 100644 index 0000000000..f0e304be5b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=FALSE +AtomicConfig=FALSE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound