Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ has a matching GitHub release whose body comes from its section below.

### Fixed

- A `berth run` or `berth train` engine is always visible to a berthd that restarts. The run writes
its record when the engine starts, not only after its wrapper notices the lost socket, so a wrapper
that is stopped or slow cannot let the new daemon grant a second whole-card lease onto a live engine.
(#354)
- `go test ./internal/cli` on a Windows machine with Berth installed no longer deletes the installed services'
launchers (`units\*.vbs` in the state directory). Three service tests ran a real uninstall or install against
the user's own state directory instead of a temporary one. (#351)
Expand Down
8 changes: 5 additions & 3 deletions docs/leasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@
keeps dialling, and re-attaches when a daemon answers, so a service that starts before
berthd at boot ends up leased.
- **Survives a daemon restart.** A running engine stays up when berthd restarts or is
upgraded; `berth run` dials the new daemon and re-attaches by PID plus start time. For
15 s after a start the daemon grants nothing new while such engines are still due back,
so nothing is loaded onto a card an engine already holds.
upgraded; `berth run` dials the new daemon and re-attaches by PID plus start time. Every
run records its engine from the moment the engine starts, so a daemon that comes up while
a run has not yet noticed the old one went away still sees that engine. For 15 s after a
start the daemon grants nothing new while such engines are still due back, so nothing is
loaded onto a card an engine already holds.
- **ComfyUI at a job boundary.** `--drain-comfyui` waits until ComfyUI's queue is empty
before stopping it; a job in progress is never cut off.
- **No juggling.** Two engines at the same priority drain each other: the last one asked for
Expand Down
29 changes: 23 additions & 6 deletions internal/broker/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,7 @@ func (b *Broker) Tick(ctx context.Context) {
present[id] = true
scope := b.scopeOf(p.PID)
if l := b.owner(id, p, scope); l != nil {
if l.state != active && l.state != draining && b.runFor(p.PID) != nil {
if l.state != active && l.state != draining && b.leftBehind(p.PID) {
// A released lease keeps blocking while its processes hold
// memory, unless a run record says they were left behind on
// purpose (a keep-up drain): those processes fall through to
Expand Down Expand Up @@ -923,7 +923,10 @@ func (b *Broker) Tick(ctx context.Context) {
}
s := &squatter{id: id, proc: p, seen: now}
wrapper := ""
if run != nil {
if run != nil && run.Unprotected() {
// Only a run that says its engine is unleased is the squatter's
// owner. A leased run's stray process is not evidence that its
// berth run failed to re-attach.
s.run = run.Engine
wrapper = run.WrapperState(b.tree.StartTime)
}
Expand Down Expand Up @@ -1106,11 +1109,16 @@ func (b *Broker) runFor(pid int) *runs.Record {
return nil
}

// dueToReattach is true for a run that lost the previous daemon mid-run, or
// found none at its start, while this daemon is young enough that its berth
// run is still dialling, and it has not re-attached yet.
// dueToReattach is true for a run that may still hold the card from the
// last daemon: it has no lease here, and either the re-attach window is open
// or it is a training, whose card is its own until it returns. Every record
// counts, not only one whose berth run has already noticed the lost socket:
// the record is written when the engine starts, so a run that is slow to
// notice cannot hide its engine from a fresh daemon (#354).
func (b *Broker) dueToReattach(r runs.Record, now time.Time) bool {
if r.Reason != runs.ReasonLost && r.Reason != runs.ReasonStart {
if r.Reason == runs.ReasonKeepUp {
// A keep-up drain left the server up with its models unloaded: the
// card is free on purpose, so the record holds nothing.
return false
}
// A training waits as long as its process lives: the card is its own
Expand All @@ -1137,6 +1145,15 @@ func (b *Broker) reattaching(now time.Time) int {
return n
}

// leftBehind is true for a process whose record says its engine runs
// without a lease (a keep-up drain, or a run that lost its daemon). A
// record with no reason belongs to a run whose lease is live; its processes
// keep blocking until the driver shows the memory free.
func (b *Broker) leftBehind(pid int) bool {
r := b.runFor(pid)
return r != nil && r.Unprotected()
}

func holding(l *lease) string {
parts := make([]string, 0, len(l.gpu))
for _, p := range l.gpu {
Expand Down
64 changes: 64 additions & 0 deletions internal/broker/lostrun_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,70 @@ func TestRefusalNamesTheWaitersOwnUnleasedRun(t *testing.T) {
})
}

// #354: a restarted daemon granted a second whole-card lease while the
// first run's engine was still alive. Its berth run had not yet noticed the
// lost socket, so no unprotected record existed. Every run now records its
// engine from the moment the child starts, so a fresh daemon holds the card
// until the run re-attaches or the window closes, whatever its berth run is
// doing.
func TestLiveRunHoldsTheCardUntilItReattaches(t *testing.T) {
b, _, _ := setup(t, procs.Fake{Starts: map[int]uint64{100: 1, 99: 5}})
b.cfg.RunsDir = t.TempDir()
b.cfg.ReattachWindow = time.Hour
// No reason: its berth run still believes the lease is live.
if _, err := runs.Write(b.cfg.RunsDir, runs.Record{
Engine: "qualification-active", PID: 100, Start: 1,
Wrapper: 99, WrapperStart: 5, Started: time.Now(),
}); err != nil {
t.Fatal(err)
}
b.Tick(context.Background())

_, err := b.Acquire(context.Background(),
Request{Engine: "qualification-next", Pinned: true, Wait: 100 * time.Millisecond}, nil)
if err == nil {
t.Fatal("granted a second whole-card lease while the first run's engine is alive")
}
if !strings.Contains(err.Error(), "berthd restarted") || !strings.Contains(err.Error(), "1 running engine") {
t.Fatalf("refusal = %q, want the restart window named", err)
}

// Once it re-attaches, its own lease is what keeps the contender out.
if _, err := b.Reattach(Request{Engine: "qualification-active", Pinned: true}, 100, 1); err != nil {
t.Fatalf("re-attach: %v", err)
}
_, err = b.Acquire(context.Background(),
Request{Engine: "qualification-next", Pinned: true, Wait: 100 * time.Millisecond}, nil)
if err == nil {
t.Fatal("granted beside a live pinned lease")
}
if strings.Contains(err.Error(), "berthd restarted") {
t.Fatalf("refusal = %q; the re-attach window should not be the reason any more", err)
}
}

// A record for a run whose lease is live holds nothing: the engine is
// accounted for by the lease, and the daemon grants as usual.
func TestRecordForALeasedRunHoldsNothing(t *testing.T) {
b, _, _ := setup(t, procs.Fake{Starts: map[int]uint64{100: 1}})
b.cfg.RunsDir = t.TempDir()
b.cfg.ReattachWindow = time.Hour

l := must(t, acquire(b, Request{Engine: "a", Priority: Batch, Needs: GiB}))
l.Attach(100)
if _, err := runs.Write(b.cfg.RunsDir, runs.Record{
Engine: "a", PID: 100, Start: 1, Started: time.Now(),
}); err != nil {
t.Fatal(err)
}
b.Tick(context.Background())
if n := b.reattaching(b.now()); n != 0 {
t.Fatalf("a leased run counts as due back %d time(s)", n)
}

must(t, acquire(b, Request{Engine: "b", Priority: Batch, Needs: GiB}))
}

// #300: an engine whose berth run has exited has nobody left to re-attach
// it, and one whose berth run is alive should have. The daemon could not
// tell the two apart, so the report could not say which one happened.
Expand Down
5 changes: 5 additions & 0 deletions internal/broker/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ func (b *Broker) Status() proto.Status {
st.Claims = append(st.Claims, c)
}
for _, r := range b.runs {
if !r.Unprotected() {
// A leased run's record is the daemon's witness after a restart,
// not an unprotected run.
continue
}
st.Unprotected = append(st.Unprotected, proto.Run{Engine: r.Engine, PID: r.PID, Reason: r.Reason, Age: now.Sub(r.Started).Seconds()})
}
return st
Expand Down
44 changes: 28 additions & 16 deletions internal/broker/training_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,17 @@ func TestTrainingLocksOutAQueuedGang(t *testing.T) {
}
}

// trainingLost is a node whose training (pid 200) lost the last daemon: its
// record is on disk, and this daemon's re-attach window is long past.
func trainingLost(t *testing.T) *Broker {
// trainingLost is a node whose training (pid 200) ran under the last
// daemon: its record is on disk, and this daemon's re-attach window is long
// past. reason is the record's state, runs.ReasonLost once its berth run has
// noticed the lost daemon and "" before that.
func trainingLost(t *testing.T, reason string) *Broker {
t.Helper()
b, _, _ := setup(t, procs.Fake{Starts: map[int]uint64{200: 9}})
b.cfg.RunsDir = t.TempDir()
b.cfg.ReattachWindow = time.Nanosecond
if _, err := runs.Write(b.cfg.RunsDir, runs.Record{
Engine: "train-a", PID: 200, Start: 9, Started: time.Now(), Reason: runs.ReasonLost, Training: true,
Engine: "train-a", PID: 200, Start: 9, Started: time.Now(), Reason: reason, Training: true,
}); err != nil {
t.Fatal(err)
}
Expand All @@ -175,24 +177,34 @@ func trainingLost(t *testing.T) *Broker {
// A training that has not re-attached yet still locks the card after a
// daemon restart, with no time limit: other requests are refused at once.
func TestTrainingLocksTheCardUntilItReattaches(t *testing.T) {
b := trainingLost(t)
why := refusedNow(t, "a request before the training re-attaches", acquire(b, Request{Engine: "chat", Priority: Foreground, Wait: time.Hour}))
if !strings.Contains(why, "locked for training by train-a") {
t.Errorf("refusal %q does not name the training", why)
}

l, err := b.Reattach(Request{Engine: "train-a", Training: true}, 200, 9)
if err != nil {
t.Fatalf("the training's re-attach: %v", err)
for _, tc := range []struct {
name string
reason string
}{
{"its berth run noticed the lost daemon", runs.ReasonLost},
{"its berth run has not noticed yet", ""},
} {
t.Run(tc.name, func(t *testing.T) {
b := trainingLost(t, tc.reason)
why := refusedNow(t, "a request before the training re-attaches", acquire(b, Request{Engine: "chat", Priority: Foreground, Wait: time.Hour}))
if !strings.Contains(why, "locked for training by train-a") {
t.Errorf("refusal %q does not name the training", why)
}

l, err := b.Reattach(Request{Engine: "train-a", Training: true}, 200, 9)
if err != nil {
t.Fatalf("the training's re-attach: %v", err)
}
refusedNow(t, "a request after the training re-attached", acquire(b, Request{Engine: "chat", Priority: Foreground, Wait: time.Hour}))
l.Release()
})
}
refusedNow(t, "a request after the training re-attached", acquire(b, Request{Engine: "chat", Priority: Foreground, Wait: time.Hour}))
l.Release()
}

// The lock ends with the training: once its process is gone, the record
// goes and the card serves again.
func TestTrainingRecordLocksOnlyWhileItsProcessLives(t *testing.T) {
b := trainingLost(t)
b := trainingLost(t, runs.ReasonLost)
b.tree = procs.Fake{Starts: map[int]uint64{}}
b.Tick(context.Background())
must(t, acquire(b, Request{Engine: "chat", Priority: Foreground}))
Expand Down
50 changes: 31 additions & 19 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,32 @@ func Run(o Options) int {
return 127
}
afterStart(cmd)

// The record covers the whole life of the engine, not only the hours no
// daemon answers. berthd reads these records before it grants anything,
// so an engine still on the card keeps the card even when its run has not
// yet noticed the lost socket: the record is the only witness to it
// (#354). reason is "" while a lease holds.
started := time.Now()
childStart := procs.System{}.StartTime(cmd.Process.Pid)
self, selfStart := os.Getpid(), procs.System{}.StartTime(os.Getpid())
dir := runs.Dir(o.Socket)
writeRecord := func(reason string) {
_, err := runs.Write(dir, runs.Record{
Engine: o.Engine, PID: cmd.Process.Pid, Start: childStart, Started: started,
Reason: reason, Wrapper: self, WrapperStart: selfStart, Training: o.Training,
})
if err != nil {
fmt.Fprintf(o.Stderr, "berth: could not record the run: %v\n", err)
}
}
if conn == nil {
writeRecord(runs.ReasonStart)
} else {
writeRecord("")
}
defer runs.Remove(dir, cmd.Process.Pid)

if conn != nil {
_ = conn.Send(proto.Msg{Op: proto.OpAttach, PID: cmd.Process.Pid})
}
Expand Down Expand Up @@ -361,8 +387,9 @@ func Run(o Options) int {
}()
}

// Run returns only after the listener does, so an unprotected-run record
// it wrote is gone by then.
// Every iteration of the re-attach loop rewrites the record: the reason
// says whether the engine is unleased right now. Run removes it after the
// listener returns.
listening := make(chan struct{})
if raw != nil {
go func(c net.Conn) { <-done; c.Close() }(raw)
Expand Down Expand Up @@ -408,11 +435,10 @@ func Run(o Options) int {
say("UNPROTECTED: lost berthd (%v); %s keeps running without a lease, retrying", err, o.Engine)
reason = runs.ReasonLost
}
remove := record(o, cmd, reason)
writeRecord(reason)
line.adoptLends(o, say)
var lease string
conn, raw, lease = reattach(o, cmd, done, &cid, line)
remove()
if conn == nil {
return
}
Expand All @@ -423,6 +449,7 @@ func Run(o Options) int {
if ids := cid.list(); len(ids) > 0 {
_ = conn.Send(proto.Msg{Op: proto.OpAttach, PID: cmd.Process.Pid, Containers: ids})
}
writeRecord("")
say("re-attached %s as %s", o.Engine, lease)
}
}()
Expand Down Expand Up @@ -771,21 +798,6 @@ func slotsBusy(url, key string) (int, error) {
return n, nil
}

// record leaves a note beside the socket that this engine runs without a
// lease, so berthd lists it instead of it being an anonymous squatter. It
// returns the func that removes the note.
func record(o Options, cmd *exec.Cmd, reason string) func() {
pid, self := cmd.Process.Pid, os.Getpid()
remove, err := runs.Write(runs.Dir(o.Socket), runs.Record{
Engine: o.Engine, PID: pid, Start: procs.System{}.StartTime(pid), Started: time.Now(), Reason: reason,
Wrapper: self, WrapperStart: procs.System{}.StartTime(self), Training: o.Training,
})
if err != nil {
fmt.Fprintf(o.Stderr, "berth: could not record the unprotected run: %v\n", err)
}
return remove
}

// visibleDevices is the CUDA_VISIBLE_DEVICES=UUID entry that keeps the
// engine on the cards the run named, "" when the run named none, when the
// environment already picks the devices, or when a card has no UUID (an
Expand Down
31 changes: 25 additions & 6 deletions internal/runs/runs.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// Copyright 2026 Trevin Tindall (T-Crypt)
// SPDX-License-Identifier: Apache-2.0

// Package runs records engines that started without a lease: berthd was
// down (fail-open), or went away mid-run. The wrapper writes one small file
// per run beside the socket, and berthd lists the live ones, so an
// unprotected engine is never invisible.
// Package runs records the engines a berth run starts, so a berthd that
// starts beside them knows they exist. The wrapper writes one small file per
// run beside the socket, and berthd lists the live ones. A run that lost its
// daemon, or found none, is unprotected: its record carries a Reason and
// status shows it. A run whose lease is live is recorded too, so a restarted
// daemon can never miss an engine that may still hold the card.
package runs

import (
Expand All @@ -19,13 +21,19 @@ import (
"github.com/T-Crypt/berth/internal/fsx"
)

// Record is one unprotected run, identified by PID plus start time.
// Record is one engine that a berth run started, identified by PID plus
// start time.
type Record struct {
Engine string `json:"engine"`
PID int `json:"pid"`
Start uint64 `json:"pid_start"`
Started time.Time `json:"started"`
Reason string `json:"reason"`
// Reason says the engine runs without a lease: berthd went away mid-run,
// none answered at the start, or a keep-up drain left the server up.
// Empty while a lease holds it. A record with no reason is still read
// after a restart: its engine may hold the card, and berthd holds new
// grants until the run re-attaches or the window closes.
Reason string `json:"reason"`
// Wrapper is the berth run that wrote the record, the one process that
// can re-attach the engine. 0 in a record from before v0.5.1.
Wrapper int `json:"wrapper_pid,omitempty"`
Expand All @@ -36,6 +44,11 @@ type Record struct {
Training bool `json:"training,omitempty"`
}

// Unprotected is true for a record whose engine runs without a lease. A
// record with no reason belongs to a run that holds, or held, a lease; it is
// on disk so a daemon that starts later can see the engine.
func (r Record) Unprotected() bool { return r.Reason != "" }

// WrapperState is "alive" while the berth run that wrote r still runs,
// "exited" once it is gone (or its PID is someone else's), and "" when the
// record does not say which berth run wrote it.
Expand Down Expand Up @@ -87,6 +100,12 @@ func Write(dir string, r Record) (func(), error) {
return func() { os.Remove(p) }, nil
}

// Remove deletes the record for pid, if there is one. It is how a run that
// recorded its engine for its whole life clears the record when it ends.
func Remove(dir string, pid int) {
os.Remove(path(dir, pid))
}

// Training is a live training record in dir, and whether there is one.
func Training(dir string, alive func(pid int) uint64) (Record, bool) {
for _, r := range List(dir, alive) {
Expand Down
Loading