From 54425cd4cad6d12e7440254e36e336d54cf4fc74 Mon Sep 17 00:00:00 2001 From: T-Crypt <132922589+T-Crypt@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:51:10 -0700 Subject: [PATCH] fix(runner): record a run for the life of its engine A berthd that restarted while a pinned or training engine was alive could grant a second whole-card lease. The runner wrote its record only after it noticed the lost socket, so a run that was stopped, or slow to read EOF, left the new daemon nothing to see, and it granted at once. #354 has the reproducer. The record now covers the whole life of the engine. It is written when the child starts, rewritten with the reason when the daemon goes away, cleared when the run re-attaches, and removed when the child exits. berthd counts every live record it has no lease for as due back, so the card stays held until the run re-attaches or the window closes. A training still holds with no timer, and a keep-up record holds nothing because that drain freed the card on purpose. The new tests failed before the change: TestLiveRunHoldsTheCardUntilItReattaches, TestRecordForALeasedRunHoldsNothing, the two-record table in TestTrainingLocksTheCardUntilItReattaches, and the reattach e2e, which now asserts the record before the daemon stops and its cleared state after the re-attach. One interval remains: a daemon that dies between the grant and the child start. No process exists there for a runner record to describe, so closing it needs a durable grant record in berthd. --- CHANGELOG.md | 4 ++ docs/leasing.md | 8 ++-- internal/broker/broker.go | 29 ++++++++++++--- internal/broker/lostrun_test.go | 64 ++++++++++++++++++++++++++++++++ internal/broker/status.go | 5 +++ internal/broker/training_test.go | 44 ++++++++++++++-------- internal/runner/runner.go | 50 +++++++++++++++---------- internal/runs/runs.go | 31 +++++++++++++--- internal/server/e2e_test.go | 25 +++++++++++-- 9 files changed, 207 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a70560..9c5202c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,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) diff --git a/docs/leasing.md b/docs/leasing.md index 84e50d9..fe8985d 100644 --- a/docs/leasing.md +++ b/docs/leasing.md @@ -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 diff --git a/internal/broker/broker.go b/internal/broker/broker.go index e575419..4c97074 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -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 @@ -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) } @@ -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 @@ -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 { diff --git a/internal/broker/lostrun_test.go b/internal/broker/lostrun_test.go index 258a5f8..8f45711 100644 --- a/internal/broker/lostrun_test.go +++ b/internal/broker/lostrun_test.go @@ -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. diff --git a/internal/broker/status.go b/internal/broker/status.go index 0fa0a8d..9e529a0 100644 --- a/internal/broker/status.go +++ b/internal/broker/status.go @@ -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 diff --git a/internal/broker/training_test.go b/internal/broker/training_test.go index a7288dc..ee86f9b 100644 --- a/internal/broker/training_test.go +++ b/internal/broker/training_test.go @@ -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) } @@ -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})) diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 0876b83..32f355a 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -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}) } @@ -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) @@ -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 } @@ -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) } }() @@ -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 diff --git a/internal/runs/runs.go b/internal/runs/runs.go index 56127ad..7b42a9c 100644 --- a/internal/runs/runs.go +++ b/internal/runs/runs.go @@ -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 ( @@ -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"` @@ -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. @@ -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) { diff --git a/internal/server/e2e_test.go b/internal/server/e2e_test.go index 222c82d..ff7dd19 100644 --- a/internal/server/e2e_test.go +++ b/internal/server/e2e_test.go @@ -363,10 +363,18 @@ func TestReattachAfterDaemonRestart(t *testing.T) { eng, out := launch(runner.Options{Socket: sock, Engine: "llamacpp", Priority: "foreground", Retry: 50 * time.Millisecond, Grace: 200 * time.Millisecond, Argv: []string{"sleep", "30"}}) waitFor(t, "grant", func() bool { return strings.Contains(out.String(), "granted") }) + // The record covers the whole life of the engine (#354), so it exists + // before anything goes wrong: a daemon that restarts while this berth + // run has not yet noticed the lost socket still sees the engine. + waitFor(t, "live run record", func() bool { + list := runs.List(runs.Dir(sock), procs.System{}.StartTime) + return len(list) == 1 && list[0].Reason == "" && list[0].Wrapper == os.Getpid() + }) stop() waitFor(t, "unprotected record", func() bool { - return len(runs.List(runs.Dir(sock), procs.System{}.StartTime)) == 1 + list := runs.List(runs.Dir(sock), procs.System{}.StartTime) + return len(list) == 1 && list[0].Reason == runs.ReasonLost }) if rec := runs.List(runs.Dir(sock), procs.System{}.StartTime)[0]; rec.WrapperState(procs.System{}.StartTime) != "alive" || rec.Wrapper != os.Getpid() { t.Fatalf("record = %+v, want it to name this berth run (pid %d) as alive", rec, os.Getpid()) @@ -378,7 +386,12 @@ func TestReattachAfterDaemonRestart(t *testing.T) { if len(st.Leases) != 1 || st.Leases[0].Engine != "llamacpp" || st.Leases[0].State != "active" || st.Leases[0].PID == 0 { t.Fatalf("leases after re-attach = %+v", st.Leases) } - waitFor(t, "record removed", func() bool { return len(runs.List(runs.Dir(sock), procs.System{}.StartTime)) == 0 }) + // The record stays for the life of the run, no longer flagged lost: the + // next daemon restart needs it before the re-attach window closes again. + waitFor(t, "record cleared", func() bool { + list := runs.List(runs.Dir(sock), procs.System{}.StartTime) + return len(list) == 1 && list[0].Reason == "" + }) // The re-attached lease still drains like any other. second, out2 := launch(runner.Options{Socket: sock, Engine: "comfyui", Priority: "foreground", Argv: []string{"true"}}) @@ -410,7 +423,12 @@ func TestRunStartedBeforeDaemonReattaches(t *testing.T) { if len(st.Leases) != 1 || st.Leases[0].Engine != "gemma4" || st.Leases[0].State != "active" || st.Leases[0].PID == 0 { t.Fatalf("leases after re-attach = %+v", st.Leases) } - waitFor(t, "record removed", func() bool { return len(runs.List(runs.Dir(sock), procs.System{}.StartTime)) == 0 }) + // The record stays for the life of the run, no longer flagged + // unprotected: the next daemon restart needs it too. + waitFor(t, "record cleared", func() bool { + list := runs.List(runs.Dir(sock), procs.System{}.StartTime) + return len(list) == 1 && list[0].Reason == "" + }) second, out2 := launch(runner.Options{Socket: sock, Engine: "comfyui", Priority: "foreground", Argv: []string{"true"}}) if code := <-eng; code != 128+15 { @@ -419,6 +437,7 @@ func TestRunStartedBeforeDaemonReattaches(t *testing.T) { if code := <-second; code != 0 { t.Fatalf("second exit = %d; stderr:\n%s", code, out2.String()) } + waitFor(t, "record removed", func() bool { return len(runs.List(runs.Dir(sock), procs.System{}.StartTime)) == 0 }) } // A run that found no daemon at its start holds new grants in the window