Carry a download's progress to where somebody is looking at it
CI / test (push) Successful in 1m28s

The agent has always logged a percentage as it fetches weights, with a comment
saying a replica pulling a hundred gigabytes and one that is wedged look
identical from the control plane. They still did: the log is on the node, and
the node is not where anyone is looking when a replica has been starting for
ten minutes.

Progress now rides on the shard status and appears under the replica in `ctl
replicas` — a line rather than a column, because most replicas are not
downloading anything and a column would be empty for all of them.

It is deliberately not a state transition. Treating each chunk as one would
re-mark the shard as starting on every report and reset the timer that decides
when a slow start has become a failed one, so an hour-long download would keep
a doomed replica alive indefinitely. It arrives on its own method for that
reason, and a real transition clears it — otherwise a finished download sits in
the listing at ninety-nine percent under a shard that has been serving for an
hour.

Watchers are keyed by source rather than by shard, because a fetch is
single-flight: eight shards starting together produce one download and all
eight are waiting on it.

No percentage is invented when the server sent no length. One that stops moving
is worse than a byte count that keeps rising, so the field is absent and the
listing says "so far".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5 committed 2026-09-27 07:49:08 +02:00
1 parent 100f10ac17
commit a35e8796d2
11 files changed
+447 -60

No files matched your search

+75 -9
View File
@@ -15,6 +15,7 @@ import (
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
@@ -219,6 +220,12 @@ type Agent struct {
// heartbeat carries the list only when it changed. Touched only by the
// heartbeat goroutine, which is the only thing that reads or writes it.
lastWeights string
// fetchWatchers are the shards waiting on each source, so progress on one
// download reaches every shard that asked for it. A fetch is single-flight
// — eight shards starting together produce one download — and all eight
// are waiting, so all eight should say so.
fetchWatchers map[string][]func(weights.Progress)
}
// connectHTTPClient is the HTTP client connect uses; an interface so tests can
@@ -456,12 +463,20 @@ func (a *Agent) weights() *weights.Fetcher {
CacheDir: cache,
Log: a.log,
OnProgress: func(p weights.Progress) {
// Logged rather than silent: a replica that is downloading a
// hundred gigabytes and one that is wedged look identical from the
// control plane, and the difference matters to whoever is waiting.
a.log.Info("fetching weights",
"source", p.Source, "percent", p.Percent(),
"bytes", p.BytesDone, "total", p.BytesTotal)
// And upward, to whoever is watching from the control plane. The
// log line above is on the node, which is where nobody is looking
// when a replica has been starting for ten minutes.
a.mu.Lock()
watchers := slices.Clone(a.fetchWatchers[p.Source])
a.mu.Unlock()
for _, w := range watchers {
if w != nil {
w(p)
}
}
},
}
return a.fetcher
@@ -763,6 +778,42 @@ func (a *Agent) handle(ctx context.Context, msg *llmgwv1.ControlMessage, out cha
//
// It runs in its own goroutine because model loading takes minutes, and the
// stream has to keep carrying heartbeats and other commands meanwhile.
// watchFetch registers interest in a source's download progress and returns
// the function that stops watching.
//
// Keyed by source rather than by shard because a fetch is single-flight: eight
// shards starting together produce one download, and every one of them is
// waiting on it.
func (a *Agent) watchFetch(source string, fn func(weights.Progress)) (stop func()) {
a.mu.Lock()
if a.fetchWatchers == nil {
a.fetchWatchers = map[string][]func(weights.Progress){}
}
a.fetchWatchers[source] = append(a.fetchWatchers[source], fn)
i := len(a.fetchWatchers[source]) - 1
a.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
a.mu.Lock()
defer a.mu.Unlock()
w := a.fetchWatchers[source]
if i < len(w) {
// Cleared rather than removed, so the indexes other watchers
// hold stay valid. The slice is dropped when the last one goes.
w[i] = nil
}
for _, f := range w {
if f != nil {
return
}
}
delete(a.fetchWatchers, source)
})
}
}
func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<- *llmgwv1.AgentMessage) {
shardID, replicaID := m.GetShardId(), m.GetReplicaId()
@@ -770,16 +821,18 @@ func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<
a.shardReplica[shardID] = replicaID
a.mu.Unlock()
report := func(st supervisor.State, errMsg string, tail []string) {
msg := &llmgwv1.AgentMessage{Msg: &llmgwv1.AgentMessage_Shard{Shard: &llmgwv1.ShardStatus{
NodeId: a.cfg.NodeID, ReplicaId: replicaID, ShardId: shardID,
State: agentsvc.StateToWire(st), Error: errMsg, LastOutput: tail,
}}}
send := func(s *llmgwv1.ShardStatus) {
s.NodeId, s.ReplicaId, s.ShardId = a.cfg.NodeID, replicaID, shardID
select {
case out <- msg:
case out <- &llmgwv1.AgentMessage{Msg: &llmgwv1.AgentMessage_Shard{Shard: s}}:
case <-ctx.Done():
}
}
report := func(st supervisor.State, errMsg string, tail []string) {
send(&llmgwv1.ShardStatus{
State: agentsvc.StateToWire(st), Error: errMsg, LastOutput: tail,
})
}
spec, timeout := agentsvc.ShardSpecFromStart(m)
@@ -808,10 +861,23 @@ func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<
// arrives minutes into a load, in its own words, on a node nobody is
// watching — and because eight shards starting together would otherwise
// each fetch the same file.
//
// Progress is reported upward while it runs, so the control plane can tell
// a download from a hang.
stop := a.watchFetch(spec.Profile.ModelPath, func(p weights.Progress) {
send(&llmgwv1.ShardStatus{
State: agentsvc.StateToWire(supervisor.Starting),
Fetch: &llmgwv1.FetchProgress{
Source: p.Source, BytesDone: p.BytesDone, BytesTotal: p.BytesTotal,
},
})
})
if path, err := a.weights().Ensure(ctx, spec.Profile.ModelPath); err != nil {
stop()
report(supervisor.Failed, err.Error(), nil)
return
} else {
stop()
spec.Profile.ModelPath = path
}
+20
View File
@@ -38,6 +38,7 @@ type statusRecorder struct {
calls []adoptCall
adopted []reconciler.AdoptedShard
unclaim []string // shard ids to report back as unclaimed
fetches []fetchReport
}
type status struct {
@@ -55,6 +56,25 @@ func (r *statusRecorder) OnShardStatus(replicaID, shardID string, st supervisor.
}
}
// fetches records download progress, so a test can assert that a fetch is
// visible from the control plane rather than only in the node's log.
func (r *statusRecorder) OnFetchProgress(replicaID, shardID, source string, done, total int64) {
r.mu.Lock()
defer r.mu.Unlock()
r.fetches = append(r.fetches, fetchReport{replicaID, shardID, source, done, total})
}
func (r *statusRecorder) fetchReports() []fetchReport {
r.mu.Lock()
defer r.mu.Unlock()
return append([]fetchReport(nil), r.fetches...)
}
type fetchReport struct {
replicaID, shardID, source string
done, total int64
}
func (r *statusRecorder) Adopt(nodeID string, shards []reconciler.AdoptedShard) []reconciler.AdoptedShard {
r.mu.Lock()
defer r.mu.Unlock()
+10
View File
@@ -335,6 +335,16 @@ func newReplicasCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
r.ID, r.Model, r.State, r.Pool, join(nodes),
(time.Duration(r.AgeSec) * time.Second).String(),
idleColumn(r.IdleSec), r.Endpoint)
// A line rather than a column, because most replicas are not
// downloading anything and a column would be empty for all of
// them. When one is, it is the only thing worth reading.
for _, s := range r.Shards {
if s.Fetch == nil {
continue
}
fmt.Fprintf(w, " %s: fetching %s\t\t\t\t\t\t\t\n",
s.Node, fetchColumn(s.Fetch))
}
}
_ = w.Flush()
+21
View File
@@ -3,6 +3,7 @@ package cli
import (
"encoding/json"
"fmt"
"strings"
"github.com/spf13/cobra"
@@ -151,3 +152,23 @@ func fileSize(b int64) string {
return "size unknown"
}
}
// fetchColumn renders a download's progress.
//
// A percentage when the size is known and a byte count when it is not, because
// a server that does not send Content-Length is common enough — and an
// invented percentage that stops moving is worse than a number that rises.
func fetchColumn(f *adminapi.FetchView) string {
if f.Percent != nil {
return fmt.Sprintf("%s %d%% of %s", shortSource(f.Source), *f.Percent, fileSize(f.BytesTotal))
}
return fmt.Sprintf("%s %s so far", shortSource(f.Source), fileSize(f.BytesDone))
}
// shortSource keeps the end of a source, which is the part that identifies it.
func shortSource(s string) string {
if i := strings.LastIndex(s, "/"); i >= 0 && i < len(s)-1 {
return s[i+1:]
}
return s
}
+27 -2
View File
@@ -131,6 +131,22 @@ type ShardView struct {
GPUs []int `json:"gpus"`
State string `json:"state"`
Err string `json:"error,omitempty"`
// Fetch is the download this shard is waiting on, absent when it is not
// waiting on one. It is what tells a replica pulling a hundred gigabytes
// apart from one that is wedged — which look identical without it.
Fetch *FetchView `json:"fetch,omitempty"`
}
// FetchView is a download in flight.
type FetchView struct {
Source string `json:"source"`
BytesDone int64 `json:"bytes_done"`
// BytesTotal is 0 when the server did not say how large the file is.
BytesTotal int64 `json:"bytes_total,omitempty"`
// Percent is absent rather than zero when the total is unknown: an
// invented percentage that stops moving is worse than a byte count that
// keeps rising.
Percent *int `json:"percent,omitempty"`
}
// ExplainView is why a model could not be placed.
@@ -262,10 +278,19 @@ func (a *API) Replicas(model string) []ReplicaView {
v.IdleSec = int64(time.Since(rep.LastUsedAt).Seconds())
}
for _, s := range rep.Shards {
v.Shards = append(v.Shards, ShardView{
sv := ShardView{
ID: s.ID, Node: s.NodeID, Rank: s.Rank,
GPUs: s.GPUIndices, State: s.State.String(), Err: s.Err,
})
}
if f := s.Fetch; f != nil {
sv.Fetch = &FetchView{
Source: f.Source, BytesDone: f.BytesDone, BytesTotal: f.BytesTotal,
}
if p, ok := f.Percent(); ok {
sv.Fetch.Percent = &p
}
}
v.Shards = append(v.Shards, sv)
}
out = append(out, v)
}
+12
View File
@@ -24,6 +24,10 @@ import (
// agents report they are already running. The reconciler implements it.
type StatusSink interface {
OnShardStatus(replicaID, shardID string, state supervisor.State, errMsg string)
// OnFetchProgress is separate because it is not a transition: the shard is
// still starting, and treating each report as a state change would reset
// the timers that decide when a slow start has become a failed one.
OnFetchProgress(replicaID, shardID, source string, done, total int64)
Adopt(nodeID string, shards []reconciler.AdoptedShard) (unclaimed []reconciler.AdoptedShard)
}
@@ -233,6 +237,14 @@ func (s *Service) handle(nodeID string, msg *llmgwv1.AgentMessage) {
s.applyHeartbeat(nodeID, m.Heartbeat)
case *llmgwv1.AgentMessage_Shard:
// Progress rather than a transition. Falling through to OnShardStatus
// would re-mark the shard as starting on every chunk, which is how a
// download that takes an hour would keep a start timer at zero.
if f := m.Shard.GetFetch(); f != nil {
s.status.OnFetchProgress(m.Shard.GetReplicaId(), m.Shard.GetShardId(),
f.GetSource(), f.GetBytesDone(), f.GetBytesTotal())
return
}
st := StateFromWire(m.Shard.GetState())
s.status.OnShardStatus(m.Shard.GetReplicaId(), m.Shard.GetShardId(), st, m.Shard.GetError())
if m.Shard.GetState() == llmgwv1.ShardStatus_STATE_FAILED {
+70
View File
@@ -0,0 +1,70 @@
package reconciler
import (
"testing"
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/supervisor"
)
func TestProgressIsVisibleWithoutBeingATransition(t *testing.T) {
// The failure this replaces: a replica pulling a hundred gigabytes and one
// that is wedged look identical from the control plane — both are a shard
// that has been starting for ten minutes.
//
// And progress must not count as a state change. Treating each chunk as
// one would reset the timer that decides when a slow start has become a
// failed one, so a download would keep a replica alive forever.
h := newHarness(t, testModel(1), gpuNode("n1", 8))
h.r.Reconcile(t.Context())
reps := h.r.Replicas()
if len(reps) != 1 || len(reps[0].Shards) == 0 {
t.Fatalf("expected a placed replica with shards, got %+v", reps)
}
rep, shard := reps[0].ID, reps[0].Shards[0].ID
h.r.OnFetchProgress(rep, shard, "hf:org/repo/model.gguf", 3<<30, 12<<30)
got := h.r.Replicas()[0].Shards[0]
if got.Fetch == nil {
t.Fatal("the download is not visible on the shard")
}
if got.Fetch.BytesDone != 3<<30 || got.Fetch.BytesTotal != 12<<30 {
t.Errorf("progress came back as %+v", got.Fetch)
}
if p, ok := got.Fetch.Percent(); !ok || p != 25 {
t.Errorf("percent = %d (known %v), want 25", p, ok)
}
}
func TestAnUnknownTotalHasNoPercentage(t *testing.T) {
// A server that sends no Content-Length is common. An invented percentage
// that stops moving is worse than a byte count that keeps rising.
f := FetchProgress{Source: "https://x/y.gguf", BytesDone: 500}
if _, ok := f.Percent(); ok {
t.Error("a percentage was invented from an unknown total")
}
}
func TestATransitionClearsTheDownload(t *testing.T) {
// Left in place it would sit in the listing at ninety-nine percent under
// a shard that has been serving for an hour.
h := newHarness(t, testModel(1), gpuNode("n1", 8))
h.r.Reconcile(t.Context())
reps := h.r.Replicas()
rep, shard := reps[0].ID, reps[0].Shards[0].ID
h.r.OnFetchProgress(rep, shard, "hf:org/repo/model.gguf", 1, 2)
h.r.OnShardStatus(rep, shard, supervisor.Ready, "")
if got := h.r.Replicas()[0].Shards[0]; got.Fetch != nil {
t.Errorf("a finished shard still shows a download: %+v", got.Fetch)
}
}
func TestProgressForAReplicaThatIsGoneIsIgnored(t *testing.T) {
// A download that finishes after its replica was torn down should not
// resurrect anything or panic.
h := newHarness(t, testModel(1), gpuNode("n1", 8))
h.r.OnFetchProgress("no-such-replica", "no-such-shard", "x", 1, 2)
}
+27
View File
@@ -1235,6 +1235,29 @@ type AdoptedShard struct {
Endpoint string
}
// OnFetchProgress records how far a shard's download has got.
//
// Separate from OnShardStatus because it is not a transition: the shard is
// still starting, and treating each progress report as a state change would
// reset the timers that decide when a slow start becomes a failed one.
func (r *Reconciler) OnFetchProgress(replicaID, shardID, source string, done, total int64) {
r.mu.Lock()
defer r.mu.Unlock()
rep, ok := r.replicas[replicaID]
if !ok {
return
}
for i := range rep.Shards {
if rep.Shards[i].ID != shardID {
continue
}
rep.Shards[i].Fetch = &FetchProgress{
Source: source, BytesDone: done, BytesTotal: total,
}
}
}
// OnShardStatus records a status report from an agent.
func (r *Reconciler) OnShardStatus(replicaID, shardID string, st supervisor.State, errMsg string) {
r.markShard(replicaID, shardID, st, errMsg)
@@ -1257,6 +1280,10 @@ func (r *Reconciler) markShard(replicaID, shardID string, st supervisor.State, e
if errMsg != "" {
rep.Shards[i].Err = errMsg
}
// A real transition means the download is over, one way or the other.
// Left in place it would sit in the listing at ninety-nine percent
// under a shard that has been serving for an hour.
rep.Shards[i].Fetch = nil
break
}
+29
View File
@@ -65,6 +65,35 @@ type Shard struct {
HTTPPort int
State supervisor.State
Err string
// Fetch is the download this shard is waiting on, if any. Cleared when the
// shard reaches any other state, so a finished download does not sit in
// the listing looking like one still running.
Fetch *FetchProgress
}
// FetchProgress is how far a shard's weights have got.
//
// Carried so an operator can tell a replica pulling a hundred gigabytes from
// one that is wedged. From outside they are the same thing — a shard that has
// been starting for ten minutes — and the difference is whether to wait or to
// go and look.
type FetchProgress struct {
Source string
BytesDone int64
// BytesTotal is 0 when the server did not say. A percentage would then be
// invented, and an invented one that stops moving is worse than a byte
// count that keeps rising.
BytesTotal int64
}
// Percent returns progress as a percentage, and false when the total is
// unknown.
func (f FetchProgress) Percent() (int, bool) {
if f.BytesTotal <= 0 {
return 0, false
}
return int(f.BytesDone * 100 / f.BytesTotal), true
}
// Leader reports whether this shard serves HTTP for the replica.