diff --git a/CHANGELOG.md b/CHANGELOG.md index fdc66de..e02008f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -130,6 +130,90 @@ and the project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2. ### Fixed +- An hf:// download whose branch moved since the cache was filled no longer + starts at 100% and climbs past it. The budget seeded `bytes_completed` + from the snapshot the local `refs/` still named, matching files + by name, so an image shipping the old model counted every old file as done + and the transfer of the new one stacked on top: a Qwen3.8-27B upgrade read + "36 GB of 18 GB" while still downloading. The tree is now listed at the + commit the revision resolves to, and a file counts as on disk only when + `snapshots//` or `blobs/` (the LFS sha256, or the + git blob id for small files) holds it at the listed size. The snapshot + check is what works behind mirrors that omit `X-Linked-ETag`, such as the + Olares one, where hf names blobs by the mirror's ETag. A new version + already in the cache is still reused, partial `.incomplete` blobs are + still left to tqdm, and no file is hashed. The pass then downloads at + that same commit and writes + `refs/` itself once it lands, so a push between the estimate + and the transfer cannot leave progress describing one revision and the + bytes another. `MODEL_SOURCE` is untouched; the next pass resolves the + branch anew, and if the revision cannot be resolved the pass downloads + at the revision as given, as before. With the total pinned, `bytes_completed` is also capped at + `bytes_total`, with one warning per pass if a producer overruns it. +- An hf:// source that cannot reach the remote no longer runs a stale model + without a word. `hf download` answers from the snapshot `refs/` + names when its own lookup fails and exits 0, so a moved branch behind a + flaky mirror kept serving the old model as if the remote had confirmed + it. The revision is now looked up three times, two and then four seconds + apart, before the remote counts as unreachable, falling back to the + `X-Repo-Commit` of a HEAD on the requested file when the revision API + refuses. Once the remote is unreachable the cached snapshot is still + used, but the log says so twice: when the lookups give up, and when hf + returns the commit the cache already held. +- An hf:// source that names one file is now sized by a HEAD on that file, + which also gives the commit, instead of the revision and tree APIs. The + Olares mirror was answering `/api/` with a 401 after fifteen seconds while + serving the HEAD, so a Qwen3.8-27B upgrade sat on "Estimating size" for + two minutes and then listed only the projector it was downloading. A + repo and revision is also resolved once per pass, so a main GGUF and its + projector come from one commit for one lookup. Pattern and `--subdir` + sources still list the tree. +- A download whose size cannot be fully estimated now lists every file it + will fetch from the start, with the ones the remote would not size shown + without a size, instead of listing nothing until each file began. The + mirror timing out the projector's HEAD used to leave the page on + "Estimating size", then show the projector alone at 100% for a minute + before the main GGUF appeared. The total is still left unpinned, and the + log now says which source could not be sized. +- An engine still serving the previous model is now restarted when a pass + moves `model_path` to a new one, and the model is only called ready once + it is back. On an upgrade the engine started on the previous sentinel + while the new revision downloaded, and since the wrapper reads the + sentinel once (and llama.cpp `-hf` picks its revision at start), it kept + serving the old model under a ready status. The restart goes through the + `engine_restart` handoff. When the request fails, or no supervise loop + acts on it, the model is marked failed with "the engine still serves the + previous model" rather than ready, and the restart stays pending: the + next pass (`/api/retry` or a re-registration) asks for it again even + though the run dir already names the new model. llama.cpp is asked + which file it loaded (`model_path` in `/props`) rather than trusted to + match the run dir, so an llm-init restart no longer forgets an engine + still on the previous model, an engine restarted by hand onto the new + one is not restarted again, and one that comes back on the previous + model is not called ready. Other engines, and a change to the projector + alone, still compare the run dir before and after the pass. llama.cpp + is asked again once it is alive, even when the pass restarted nothing, + since `/props` answers 503 while a model loads: an engine that llm-init + found still loading the previous model is restarted within the same + pass. A build without `model_path` in `/props` is called ready after + about 10s of unanswered queries. +- The OpenWebUI alias `/api/chat/completions` now reaches vLLM, llama.cpp + and SGLang as `/v1/chat/completions`. It was forwarded as is, and none of + them serves that path, so llama.cpp answered 404 "File Not Found". The + compat suite that covers it had been skipping on main, its compose stack + never coming up. +- With no pinned total, files already on disk now count toward the overall + progress as well as their own rows. A cached projector of 100 bytes plus + 500 downloaded of the main file read 500 overall against rows adding up + to 600. +- Looking up an hf revision before a download no longer takes up to two + minutes against an unreachable remote. Each attempt now asks the file + HEAD and the revision API at once instead of one after the other, and + everything asked before the download shares a 90-second budget, after + which the download starts without a pinned total. The warning when hf + returns the cached commit no longer claims the remote was unreachable: + the same commit comes back when nothing changed upstream. + - The model card's `extensions.capacity` now follows an engine whose pod an upgrade replaced. The capacity reporter re-read the engine only on a readiness dip or a relaunch this process asked for, and a replaced pod diff --git a/cmd/llm-init/main.go b/cmd/llm-init/main.go index f3da2b3..6fc938f 100644 --- a/cmd/llm-init/main.go +++ b/cmd/llm-init/main.go @@ -285,6 +285,7 @@ func run(args []string, stdout, stderr *os.File, getenv config.Getenv) int { MaxDownloadBytes: cfg.Runtime.MaxDownloadBytes, RelaunchInFlight: tracker.Relaunching, RelaunchRequested: relaunchWake, + Relauncher: tracker, }) if err != nil { fmt.Fprintf(stderr, "lifecycle init: %v\n", err) diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index a984b4f..c8369ba 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -241,6 +241,16 @@ type ModelInstaller interface { Register(ctx context.Context, files []string, known map[string]string, sink progress.Sink) error } +// ServedModelReporter is an engine that can say which model file it has +// loaded. llama.cpp reports it in /props. The path is the engine's own, +// so it is in the namespace the run dir's model_path is written for. +type ServedModelReporter interface { + // ServedModelPath returns the main model file the running engine + // loaded. An error means the engine could not answer (down, still + // loading, or an older build), not that it serves nothing. + ServedModelPath(ctx context.Context) (string, error) +} + // InstallerFor resolves the installer once, here, so no caller has to // ask an Adapter what else it might be. An engine with nothing to // install gets one that does nothing, rather than a nil to check at diff --git a/internal/adapter/hfwrap/estimate.go b/internal/adapter/hfwrap/estimate.go index ef0c03f..ada0f07 100644 --- a/internal/adapter/hfwrap/estimate.go +++ b/internal/adapter/hfwrap/estimate.go @@ -3,10 +3,12 @@ package hfwrap import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" + "strconv" "strings" "time" ) @@ -24,6 +26,11 @@ type RepoEstimate struct { // Entries is each matched file, in tree order. Used to seed the // dashboard file list before the first transfer starts. Entries []TreeEntry + // Commit is the commit Entries were listed at: cfg.Revision when it + // is one, "" for a branch or tag. Neither the Hub nor the Olares + // mirror puts X-Repo-Commit on tree responses, so a caller that needs + // it resolves the revision first (ResolveCommit) and lists at that. + Commit string } // EstimateRepo sums remote sizes for the files an hf:// source will @@ -58,14 +65,169 @@ func EstimateRepo(ctx context.Context, cfg Config, include, exclude []string, su for _, e := range matched { bytes += e.Size } + var commit string + if isHexSHA(cfg.Revision) { + commit = cfg.Revision + } return RepoEstimate{ Bytes: bytes, Files: len(matched), Complete: bytes > 0 && everyExactIncludeMatched(include, matched), Entries: matched, + Commit: commit, }, nil } +// ResolveCommit returns the commit cfg.Revision names on the Hub now. A +// revision that already is a full commit is returned without a request. +// +// When the revision API does not answer and cfg.HFFile names one file, +// the X-Repo-Commit of a HEAD on that file decides instead. That is the +// request `hf download` itself makes, so a lookup fails here only when +// hf cannot reach the revision either -- and hf then quietly serves +// whatever snapshot refs/ points at. +func ResolveCommit(ctx context.Context, cfg Config) (string, error) { + if isHexSHA(cfg.Revision) { + return cfg.Revision, nil + } + endpoint := hubEndpoint(cfg) + rev := cfg.Revision + if rev == "" { + rev = defaultHFRef + } + client := &http.Client{Timeout: resolveTimeout} + sha, err := revisionCommit(ctx, client, cfg.Token, endpoint, cfg.Repo, rev) + if err == nil { + return sha, nil + } + if cfg.HFFile == "" || looksLikeGlob(cfg.HFFile) { + return "", err + } + head, headErr := headFile(ctx, client, cfg.Token, endpoint, cfg.Repo, rev, cfg.HFFile) + if headErr != nil { + return "", errors.Join(err, headErr) + } + return head.Commit, nil +} + +// FileHead is what one HEAD on a file's resolve URL says about it. +type FileHead struct { + // Commit is the X-Repo-Commit the revision resolved to. + Commit string + // Entry is the file as a tree listing would describe it. Size is 0 + // when the response carried no usable length, and BlobID is empty + // unless the ETag is one the cache names blobs by. + Entry TreeEntry +} + +// HeadFile asks about cfg.HFFile at cfg.Revision with a single HEAD: +// the commit, the size, and the blob id. For a source that names one +// file this is everything the budget needs, in the one request `hf +// download` itself makes, and it does not touch /api/, which the +// Olares mirror has been seen answering with a 401 after fifteen +// seconds while serving this HEAD in one. +func HeadFile(ctx context.Context, cfg Config) (FileHead, error) { + if cfg.HFFile == "" || looksLikeGlob(cfg.HFFile) { + return FileHead{}, fmt.Errorf("hfwrap head: %q names no single file", cfg.HFFile) + } + rev := cfg.Revision + if rev == "" { + rev = defaultHFRef + } + return headFile(ctx, &http.Client{Timeout: resolveTimeout}, cfg.Token, hubEndpoint(cfg), cfg.Repo, rev, cfg.HFFile) +} + +// hubEndpoint is cfg.Endpoint without a trailing slash, or the Hub. +func hubEndpoint(cfg Config) string { + if e := strings.TrimSuffix(cfg.Endpoint, "/"); e != "" { + return e + } + return "https://huggingface.co" +} + +// resolveTimeout bounds one lookup. It is short next to httpTimeout +// because a lookup is retried, and a hung one holds the pass in +// phase=download. +const resolveTimeout = 20 * time.Second + +func revisionCommit(ctx context.Context, client *http.Client, token, endpoint, repo, rev string) (string, error) { + apiURL := fmt.Sprintf("%s/api/models/%s/revision/%s", endpoint, repo, url.PathEscape(rev)) + var info struct { + SHA string `json:"sha"` + } + if _, err := getTreePage(ctx, client, token, apiURL, &info); err != nil { + return "", err + } + if !isHexSHA(info.SHA) { + return "", fmt.Errorf("hfwrap revision: %s resolved to %q", rev, info.SHA) + } + return info.SHA, nil +} + +// headFile reads a HEAD on the file's resolve URL. The Hub answers it +// with a redirect to the CDN, which carries X-Repo-Commit and the +// X-Linked-* headers and is not followed; the Olares mirror answers +// 200 with a Content-Length and its own ETag. +func headFile(ctx context.Context, client *http.Client, token, endpoint, repo, rev, file string) (FileHead, error) { + segs := strings.Split(file, "/") + for i := range segs { + segs[i] = url.PathEscape(segs[i]) + } + fileURL := fmt.Sprintf("%s/%s/resolve/%s/%s", endpoint, repo, url.PathEscape(rev), strings.Join(segs, "/")) + req, err := http.NewRequestWithContext(ctx, http.MethodHead, fileURL, http.NoBody) + if err != nil { + return FileHead{}, err + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + req.Header.Set("Accept-Encoding", "identity") + noFollow := *client + noFollow.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + resp, err := noFollow.Do(req) + if err != nil { + return FileHead{}, err + } + _ = resp.Body.Close() + if resp.StatusCode >= http.StatusBadRequest { + return FileHead{}, fmt.Errorf("hfwrap revision: HEAD %s: status %d", fileURL, resp.StatusCode) + } + sha := resp.Header.Get("X-Repo-Commit") + if !isHexSHA(sha) { + return FileHead{}, fmt.Errorf("hfwrap revision: HEAD %s: X-Repo-Commit %q", fileURL, sha) + } + entry := TreeEntry{Path: file} + if n, err := strconv.ParseInt(resp.Header.Get("X-Linked-Size"), 10, 64); err == nil && n > 0 { + entry.Size = n + } else if resp.StatusCode == http.StatusOK && resp.ContentLength > 0 { + // A redirect's Content-Length is its own body's, not the file's. + entry.Size = resp.ContentLength + } + etag := resp.Header.Get("X-Linked-ETag") + if etag == "" { + etag = resp.Header.Get("ETag") + } + if id := strings.Trim(strings.TrimPrefix(etag, "W/"), `"`); isSHA256(id) || isHexSHA(id) { + entry.BlobID = id + if isSHA256(id) { + entry.SHA256 = id + } + } + return FileHead{Commit: sha, Entry: entry}, nil +} + +func isSHA256(s string) bool { + if len(s) != 64 { + return false + } + for _, r := range s { + if (r < '0' || r > '9') && (r < 'a' || r > 'f') { + return false + } + } + return true +} + func everyExactIncludeMatched(include []string, matched []TreeEntry) bool { for _, p := range include { p = strings.TrimSpace(p) @@ -119,6 +281,12 @@ type TreeEntry struct { // leave this empty; the Hub only offers their git blob id, which is // a sha1 over different bytes and no use as a content digest. SHA256 string + // BlobID is the name the local HF cache files this content under in + // blobs/: the LFS sha256 when there is one, the git blob id + // otherwise. Two revisions share a blob exactly when they share + // this id, so it says whether a file is already on disk without + // reading it. + BlobID string } // RepoTree lists what the Hub serves for a revision, and the commit that @@ -154,10 +322,7 @@ func RepoTree(ctx context.Context, cfg Config) (entries []TreeEntry, commit stri // maxTreePages bounds the loop rather than trusting the server to stop // offering a next page. func fetchTree(ctx context.Context, cfg Config, recursive bool) (entries []TreeEntry, commit string, err error) { - endpoint := strings.TrimSuffix(cfg.Endpoint, "/") - if endpoint == "" { - endpoint = "https://huggingface.co" - } + endpoint := hubEndpoint(cfg) rev := cfg.Revision if rev == "" { rev = defaultHFRef @@ -178,9 +343,10 @@ func fetchTree(ctx context.Context, cfg Config, recursive bool) (entries []TreeE if e.Type != "" && e.Type != "file" { continue } - te := TreeEntry{Path: e.Path, Size: e.Size} + te := TreeEntry{Path: e.Path, Size: e.Size, BlobID: e.OID} if e.LFS != nil { te.SHA256 = e.LFS.OID + te.BlobID = e.LFS.OID } entries = append(entries, te) } @@ -204,6 +370,7 @@ type treeItem struct { Path string `json:"path"` Size int64 `json:"size"` Type string `json:"type"` + OID string `json:"oid"` LFS *struct { OID string `json:"oid"` } `json:"lfs"` diff --git a/internal/adapter/hfwrap/estimate_test.go b/internal/adapter/hfwrap/estimate_test.go index aea3b02..8cbb021 100644 --- a/internal/adapter/hfwrap/estimate_test.go +++ b/internal/adapter/hfwrap/estimate_test.go @@ -4,6 +4,9 @@ import ( "context" "net/http" "net/http/httptest" + "os" + "path/filepath" + "runtime" "testing" ) @@ -32,6 +35,34 @@ func TestEstimateRepoFiles_SumsMatchingFiles(t *testing.T) { } } +func TestRepoTree_BlobIDFollowsCacheNaming(t *testing.T) { + t.Parallel() + const lfs = "4f2a8b0e3c1d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[ + {"type":"file","path":"model.gguf","size":100,"oid":"1111111111111111111111111111111111111111", + "lfs":{"oid":"` + lfs + `","size":100}}, + {"type":"file","path":"config.json","size":10,"oid":"2222222222222222222222222222222222222222"} + ]`)) + })) + defer srv.Close() + + entries, _, err := RepoTree(context.Background(), Config{Repo: "o/r", Endpoint: srv.URL}) + if err != nil { + t.Fatal(err) + } + if len(entries) != 2 { + t.Fatalf("entries=%+v", entries) + } + if entries[0].BlobID != lfs || entries[0].SHA256 != lfs { + t.Errorf("lfs entry=%+v, want BlobID and SHA256 = lfs oid", entries[0]) + } + if entries[1].BlobID != "2222222222222222222222222222222222222222" || entries[1].SHA256 != "" { + t.Errorf("plain entry=%+v, want BlobID = git oid and no SHA256", entries[1]) + } +} + func TestEstimateRepo_WholeRepoAndFilters(t *testing.T) { t.Parallel() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -103,6 +134,195 @@ func TestEstimateRepo_WholeRepoAndFilters(t *testing.T) { } } +func TestResolveCommit(t *testing.T) { + t.Parallel() + const commit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + var calls int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + switch r.URL.Path { + case "/api/models/o/r/revision/main": + _, _ = w.Write([]byte(`{"id":"o/r","sha":"` + commit + `"}`)) + case "/api/models/o/r/revision/bad": + _, _ = w.Write([]byte(`{"sha":"../../x"}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + ctx := context.Background() + + if got, err := ResolveCommit(ctx, Config{Repo: "o/r", Endpoint: srv.URL}); err != nil || got != commit { + t.Fatalf("branch: %q %v, want %s", got, err, commit) + } + if got, err := ResolveCommit(ctx, Config{Repo: "o/r", Revision: commit, Endpoint: srv.URL}); err != nil || got != commit || calls != 1 { + t.Fatalf("pinned: %q %v calls=%d, want %s and no request", got, err, calls, commit) + } + if _, err := ResolveCommit(ctx, Config{Repo: "o/r", Revision: "bad", Endpoint: srv.URL}); err == nil { + t.Error("a non-commit sha must be an error") + } + if _, err := ResolveCommit(ctx, Config{Repo: "o/r", Revision: "gone", Endpoint: srv.URL}); err == nil { + t.Error("a missing revision API must be an error") + } +} + +// The Olares mirror has refused the revision API while serving the +// file HEAD hf makes; the lookup must agree with what hf would see. +func TestResolveCommit_FallsBackToFileHead(t *testing.T) { + t.Parallel() + const commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/api/models/o/r/revision/main": + http.Error(w, "unauthorized", http.StatusUnauthorized) + case r.Method == http.MethodHead && r.URL.Path == "/o/r/resolve/main/dir/m.gguf": + w.Header().Set("X-Repo-Commit", commit) + w.Header().Set("Location", "/cdn/blob") + w.WriteHeader(http.StatusFound) + case r.Method == http.MethodHead && r.URL.Path == "/o/r/resolve/main/nocommit.gguf": + w.WriteHeader(http.StatusOK) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + ctx := context.Background() + + if got, err := ResolveCommit(ctx, Config{Repo: "o/r", Endpoint: srv.URL, HFFile: "dir/m.gguf"}); err != nil || got != commit { + t.Fatalf("head fallback: %q %v, want %s", got, err, commit) + } + if _, err := ResolveCommit(ctx, Config{Repo: "o/r", Endpoint: srv.URL}); err == nil { + t.Error("with no file to HEAD, a refused revision API must be an error") + } + if _, err := ResolveCommit(ctx, Config{Repo: "o/r", Endpoint: srv.URL, HFFile: "nocommit.gguf"}); err == nil { + t.Error("a HEAD without X-Repo-Commit must be an error") + } + if _, err := ResolveCommit(ctx, Config{Repo: "o/r", Endpoint: srv.URL, HFFile: "*.gguf"}); err == nil { + t.Error("a glob names no file to HEAD") + } +} + +func TestHeadFile(t *testing.T) { + t.Parallel() + const ( + commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + lfs = "2a5f3565f39cf885103da591182c1266da64745737b42b452fd3e675369f1211" + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Repo-Commit", commit) + switch r.URL.Path { + case "/hub/r/resolve/main/m.gguf": + w.Header().Set("X-Linked-Size", "17659407264") + w.Header().Set("X-Linked-ETag", `"`+lfs+`"`) + w.Header().Set("Location", "/cdn") + w.WriteHeader(http.StatusFound) + case "/mirror/r/resolve/main/m.gguf": + w.Header().Set("ETag", `"cea1c0a4a12e28b117e5137684d9fe85-10"`) + w.Header().Set("Content-Length", "17659407264") + case "/bare/r/resolve/main/m.gguf": + w.Header().Set("Location", "/cdn") + w.WriteHeader(http.StatusFound) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + ctx := context.Background() + + hub, err := HeadFile(ctx, Config{Repo: "hub/r", Endpoint: srv.URL, HFFile: "m.gguf"}) + if err != nil || hub.Commit != commit || hub.Entry.Size != 17659407264 || hub.Entry.BlobID != lfs || hub.Entry.SHA256 != lfs { + t.Errorf("hub redirect: %+v %v", hub, err) + } + mirror, err := HeadFile(ctx, Config{Repo: "mirror/r", Endpoint: srv.URL, HFFile: "m.gguf"}) + if err != nil || mirror.Commit != commit || mirror.Entry.Size != 17659407264 || mirror.Entry.BlobID != "" { + t.Errorf("mirror 200: %+v %v, want the size and no blob id", mirror, err) + } + bare, err := HeadFile(ctx, Config{Repo: "bare/r", Endpoint: srv.URL, HFFile: "m.gguf"}) + if err != nil || bare.Entry.Size != 0 { + t.Errorf("a redirect's own length is not the file's: %+v %v", bare, err) + } + if _, err := HeadFile(ctx, Config{Repo: "hub/r", Endpoint: srv.URL, HFFile: "*.gguf"}); err == nil { + t.Error("a glob names no file to HEAD") + } +} + +func TestEstimateRepo_CommitOnlyWhenListedAtOne(t *testing.T) { + t.Parallel() + const commit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/models/o/r/tree/main", "/api/models/o/r/tree/" + commit: + _, _ = w.Write([]byte(`[{"type":"file","path":"m.gguf","size":9}]`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + + at, err := EstimateRepo(context.Background(), Config{Repo: "o/r", Revision: commit, Endpoint: srv.URL}, nil, nil, "") + if err != nil || at.Commit != commit || at.Bytes != 9 { + t.Fatalf("at commit: %+v %v", at, err) + } + branch, err := EstimateRepo(context.Background(), Config{Repo: "o/r", Endpoint: srv.URL}, nil, nil, "") + if err != nil || branch.Commit != "" || branch.Bytes != 9 { + t.Fatalf("branch: %+v %v, want no commit", branch, err) + } +} + +func TestWriteRefCommit(t *testing.T) { + t.Parallel() + const commit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + cache := t.TempDir() + for _, ref := range []string{"", "v1.0", "refs/pr/1"} { + if err := WriteRefCommit(cache, "o/r", ref, commit); err != nil { + t.Fatalf("ref %q: %v", ref, err) + } + if got, err := ReadRefCommit(cache, "o/r", ref); err != nil || got != commit { + t.Errorf("ref %q read back %q %v", ref, got, err) + } + } + if err := WriteRefCommit(cache, "o/r", "../../escape", commit); err == nil { + t.Error("a ref leaving refs/ must be refused") + } + if err := WriteRefCommit(cache, "o/r", "main", "not-a-commit"); err == nil { + t.Error("a non-commit must be refused") + } + if err := WriteRefCommit(cache, "o/r", commit, commit); err != nil { + t.Errorf("a commit revision needs no ref: %v", err) + } +} + +func TestWriteRefCommit_ReadableByOtherUsers(t *testing.T) { + t.Parallel() + if runtime.GOOS == "windows" { + t.Skip("POSIX permission bits") + } + const commit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + cache := t.TempDir() + refs := filepath.Join(HFRepoCacheDir(cache, "o/r"), "refs") + + if err := WriteRefCommit(cache, "o/r", "main", commit); err != nil { + t.Fatal(err) + } + if info, err := os.Stat(filepath.Join(refs, "main")); err != nil || info.Mode().Perm() != 0o644 { + t.Fatalf("new ref mode = %v (%v), want 0644", info.Mode().Perm(), err) + } + + existing := filepath.Join(refs, "v1") + if err := os.WriteFile(existing, []byte("old"), 0o640); err != nil { + t.Fatal(err) + } + if err := os.Chmod(existing, 0o664); err != nil { + t.Fatal(err) + } + if err := WriteRefCommit(cache, "o/r", "v1", commit); err != nil { + t.Fatal(err) + } + if info, err := os.Stat(existing); err != nil || info.Mode().Perm() != 0o664 { + t.Fatalf("overwritten ref mode = %v (%v), want the existing 0664", info.Mode().Perm(), err) + } +} + func TestEstimateRepo_EmptyRepoAndNoRepo(t *testing.T) { t.Parallel() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { diff --git a/internal/adapter/hfwrap/refs_reader.go b/internal/adapter/hfwrap/refs_reader.go index 1febc86..0487fe6 100644 --- a/internal/adapter/hfwrap/refs_reader.go +++ b/internal/adapter/hfwrap/refs_reader.go @@ -2,6 +2,7 @@ package hfwrap import ( "errors" + "fmt" "os" "path/filepath" "strings" @@ -62,6 +63,59 @@ func ReadRefCommit(cacheRoot, repo, ref string) (string, error) { return sha, nil } +// WriteRefCommit records sha under refs/, the file `hf download` +// writes when it resolves a branch or tag itself. A download run at a +// commit resolved beforehand leaves that write to the caller, and +// without it the next boot cannot find the snapshot by its branch. +func WriteRefCommit(cacheRoot, repo, ref, sha string) error { + if isHexSHA(ref) { + return nil + } + if ref == "" { + ref = defaultHFRef + } + if !isHexSHA(sha) { + return fmt.Errorf("hfwrap refs: %q is not a commit", sha) + } + rel := filepath.FromSlash(ref) + if !filepath.IsLocal(rel) { + return fmt.Errorf("hfwrap refs: unsafe ref %q", ref) + } + path := filepath.Join(HFRepoCacheDir(cacheRoot, repo), "refs", rel) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + // CreateTemp makes the file 0600; an engine or app reading a shared + // cache under another uid needs the ref readable, as hf leaves it. + perm := os.FileMode(0o644) + if info, err := os.Stat(path); err == nil { + perm = info.Mode().Perm() + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".ref-*") + if err != nil { + return err + } + if err := tmp.Chmod(perm); err != nil { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + return err + } + if _, err := tmp.WriteString(sha); err != nil { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + return err + } + if err := tmp.Close(); err != nil { + _ = os.Remove(tmp.Name()) + return err + } + if err := os.Rename(tmp.Name(), path); err != nil { + _ = os.Remove(tmp.Name()) + return err + } + return nil +} + // isHexSHA reports whether s is a 40-char lowercase hex string. // huggingface_hub canonicalises commit SHAs to lower hex, so we accept // only that one form (uppercase would be the operator's typo, not the diff --git a/internal/adapter/proxy/adapter.go b/internal/adapter/proxy/adapter.go index 4a10ab4..df9d437 100644 --- a/internal/adapter/proxy/adapter.go +++ b/internal/adapter/proxy/adapter.go @@ -133,9 +133,16 @@ func writeEngineNotListening(w http.ResponseWriter, err error) { // director runs in the reverse-proxy hot path: it rewrites Host / // Scheme so the request is sent to cfg.Engine.URL, drops the // Authorization header, and rewrites the JSON model field. +// +// The OpenWebUI alias is sent on as /v1/chat/completions: it is +// llm-init's route, and none of vLLM, llama.cpp or SGLang serves it. func (a *Adapter) director(req *http.Request) { req.URL.Scheme = a.target.Scheme req.URL.Host = a.target.Host + if req.URL.Path == pathAPIChatCompletions { + req.URL.Path = pathChatCompletions + req.URL.RawPath = "" + } // Preserve the full inbound path/query as the upstream path. Don't // prepend a.target.Path because the engines mount /v1 at root and // dataplane.Mount routes /v1 in. @@ -225,6 +232,38 @@ func (a *Adapter) Ready(ctx context.Context) (adapter.ReadyState, error) { return adapter.ReadyState{Alive: true, ModelExists: exists}, nil } +// ServedModelPath reads model_path from llama.cpp's /props. Engines +// that do not report it return an error, which callers read as unknown. +func (a *Adapter) ServedModelPath(ctx context.Context) (string, error) { + if a.kind != config.EngineLlamaCpp { + return "", fmt.Errorf("proxy: %s does not report its model path", a.kind) + } + probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(probeCtx, http.MethodGet, joinPath(a.cfg.Engine.URL, "/props"), nil) + if err != nil { + return "", err + } + resp, err := a.httpClient.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("proxy: GET /props status %d", resp.StatusCode) + } + var body struct { + ModelPath string `json:"model_path"` + } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return "", fmt.Errorf("proxy: decode /props: %w", err) + } + if body.ModelPath == "" { + return "", errors.New("proxy: /props has no model_path") + } + return body.ModelPath, nil +} + // These adapters install nothing, so they do not implement // adapter.ModelInstaller. vLLM, llama.cpp and SGLang are launched with a // path and read it: llm-init puts the files there and the engine's own diff --git a/internal/adapter/proxy/adapter_test.go b/internal/adapter/proxy/adapter_test.go index 0f9c4dd..c5ac4f3 100644 --- a/internal/adapter/proxy/adapter_test.go +++ b/internal/adapter/proxy/adapter_test.go @@ -4,11 +4,13 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net" "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "time" @@ -432,6 +434,9 @@ func TestProxy_VisionBodyForwarded(t *testing.T) { if len(u.gotRequests) != 1 { t.Fatalf("upstream requests = %d, want 1 (body was not forwarded)", len(u.gotRequests)) } + if got := u.gotRequests[0].path; got != "/v1/chat/completions" { + t.Errorf("upstream path = %q, want /v1/chat/completions (no engine serves the alias)", got) + } var obj struct { Model string `json:"model"` } @@ -781,6 +786,40 @@ func TestProxy_InstallsNothing(t *testing.T) { } } +// llama.cpp reports the file it loaded in /props; the other engines are +// not asked, and an engine still loading answers unknown. +func TestProxy_ServedModelPath(t *testing.T) { + t.Parallel() + const path = "/cache/hf/hub/models--o--r/snapshots/c1/m.gguf" + var loading atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/props" { + http.NotFound(w, r) + return + } + if loading.Load() { + http.Error(w, `{"error":{"message":"Loading model"}}`, http.StatusServiceUnavailable) + return + } + _, _ = fmt.Fprintf(w, `{"model_path":%q,"total_slots":2}`, path) + })) + t.Cleanup(srv.Close) + + a, _ := NewAdapter(config.Config{Engine: config.Engine{URL: srv.URL}, Model: config.Model{Name: "m"}}, config.EngineLlamaCpp) + got, err := a.ServedModelPath(context.Background()) + if err != nil || got != path { + t.Errorf("ServedModelPath = %q, %v; want %q", got, err, path) + } + loading.Store(true) + if _, err := a.ServedModelPath(context.Background()); err == nil { + t.Error("an engine still loading must answer unknown") + } + v, _ := NewAdapter(config.Config{Engine: config.Engine{URL: srv.URL}, Model: config.Model{Name: "m"}}, config.EngineVLLM) + if _, err := v.ServedModelPath(context.Background()); err == nil { + t.Error("vLLM was asked for a path it does not report") + } +} + func TestProxy_ImplementsAdapter(t *testing.T) { t.Parallel() var _ adapter.Adapter = (*Adapter)(nil) diff --git a/internal/lifecycle/download_budget.go b/internal/lifecycle/download_budget.go index 7df6759..4f61cbb 100644 --- a/internal/lifecycle/download_budget.go +++ b/internal/lifecycle/download_budget.go @@ -2,9 +2,12 @@ package lifecycle import ( "context" + "errors" + "log/slog" "os" "path/filepath" "strings" + "time" "github.com/llm-init/llm-init/internal/adapter/hfwrap" "github.com/llm-init/llm-init/internal/config" @@ -37,10 +40,21 @@ type passState struct { // repository file rather than after the file name it shares with // its namesakes in other directories. hfTrees map[int][]hfwrap.TreeEntry + // hfCommits is the commit each hf:// source's revision resolved to + // while the budget was estimated, by segment index. runHF downloads + // at it, so the progress seeded from that commit's listing describes + // the bytes hf fetches even if the branch moves in between. + hfCommits map[int]string // driftNotes is one remote verdict per source, and driftNote is // what they last rendered to. See Manager.setDriftNote. driftNotes map[string]string driftNote string + // prevModel is what the run dir told the engine to load when the + // pass began. See Manager.relaunchIfModelChanged. + prevModel string + // relaunched is set once this pass restarted the engine, so it is + // not restarted again when it comes back on another model. + relaunched bool } // hfTree returns the listing recorded for one source, or nil when the @@ -52,6 +66,15 @@ func (p *passState) hfTree(ms config.ModelSource) []hfwrap.TreeEntry { return p.hfTrees[ms.Index] } +// hfCommit returns the commit recorded for one source, or "" when its +// revision was not resolved. +func (p *passState) hfCommit(ms config.ModelSource) string { + if p == nil { + return "" + } + return p.hfCommits[ms.Index] +} + // enterDownloadPhase moves the pass into phase=download and pins the // byte budget, and does it the first time this pass finds it actually // has something to fetch rather than on the way in. @@ -79,8 +102,18 @@ func (m *Manager) enterDownloadPhase(ctx context.Context) { } p.entered = true m.setPhase(progress.PhaseDownload) - b := m.estimateDownloadBudget(ctx, p.cfg, p.main, p.mmproj, p.extras) + budgetCtx, cancel := ctx, context.CancelFunc(func() {}) + if m.opts.MetadataBudget > 0 { + budgetCtx, cancel = context.WithTimeout(ctx, m.opts.MetadataBudget) + } + b := m.estimateDownloadBudget(budgetCtx, p.cfg, p.main, p.mmproj, p.extras) + if errors.Is(budgetCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { + slog.Warn("download metadata lookups ran past their budget; downloading with what they found", + slog.Duration("budget", m.opts.MetadataBudget)) + } + cancel() p.hfTrees = b.trees + p.hfCommits = b.commits if b.canPin && b.bytes > 0 { m.opts.Manager.SeedDownloadBudget(b.bytes, seedCompletedForPass(p.force, b.bytesCached)) if queue := fileListForPass(p.force, b.queue); len(queue) > 0 { @@ -88,9 +121,23 @@ func (m *Manager) enterDownloadPhase(ctx context.Context) { } else if b.files > 0 { m.opts.Manager.SeedDownloadFiles(b.files, seedCompletedFiles(p.force, b.filesCached)) } + } else if queue := fileListForPass(p.force, b.queue); len(queue) > 0 { + m.opts.Manager.SeedCachedBytes(cachedRowBytes(queue)) + m.opts.Manager.SeedDownloadFileList(queue) } } +// cachedRowBytes is what the rows already on disk hold. +func cachedRowBytes(queue []progress.FileProgress) int64 { + var n int64 + for _, f := range queue { + if f.Status == progress.FileDone { + n += f.BytesCompleted + } + } + return n +} + func fileListForPass(force bool, queue []progress.FileProgress) []progress.FileProgress { if len(queue) == 0 { return nil @@ -133,6 +180,8 @@ type downloadBudget struct { // survives the early returns that give up on pinning a denominator: // naming a tqdm bar needs the listing, not a complete estimate. trees map[int][]hfwrap.TreeEntry + // commits is the resolved commit per hf:// source, by segment index. + commits map[int]string } // estimateDownloadBudget sums what this pass will fetch across every @@ -152,9 +201,13 @@ func (m *Manager) estimateDownloadBudget(ctx context.Context, cfg config.Config, if main != nil { sources = append(sources, *main) } + // Resolved ahead of everything that can give up on the estimate: + // runHF needs the commit whether or not a denominator gets pinned. + targets := m.resolveHFTargets(ctx, cfg, sources) + out.commits = commitsOf(targets) for i := range sources { if sources[i].Kind == config.KindOllama { - return downloadBudget{} + return downloadBudget{commits: out.commits} } if u := urlForSource(sources[i]); u != "" { urlList = append(urlList, u) @@ -172,75 +225,330 @@ func (m *Manager) estimateDownloadBudget(ctx context.Context, cfg config.Config, } if sources[i].Kind == config.KindHF { hfSources = append(hfSources, sources[i]) - b, n := cachedHFSnapshot(m.hfCacheRoot(), sources[i]) - out.bytesCached += b - out.filesCached += n } } + // A source that cannot be sized gives up the pin but not the list: + // the page should name every file the pass will fetch from the + // start, even while some of them have no size yet. + sized, listed := true, true if len(urlList) > 0 { if sum, complete := estimateHFResolveURLList(ctx, cfg, urlList); complete { out.bytes += sum out.files += len(urlList) - out.queue = append(out.queue, urlQueue...) } else if sum, ok, allKnown := fetch.SumProbeContentLength(ctx, nil, urlList); ok && allKnown { out.bytes += sum out.files += len(urlList) if len(urlQueue) == 1 { urlQueue[0].BytesTotal = sum } - out.queue = append(out.queue, urlQueue...) } else { - return out.givenUp() + slog.Warn("download size unknown: a URL source could not be sized, so progress shows no total", + slog.Int("urls", len(urlList))) + sized = false } + out.queue = append(out.queue, urlQueue...) } for i := range hfSources { - est, err := estimateHFSource(ctx, cfg, hfSources[i]) - if len(est.Entries) > 0 { - if out.trees == nil { - out.trees = make(map[int][]hfwrap.TreeEntry, len(hfSources)) + s, l := m.budgetHFSource(ctx, cfg, &out, hfSources[i], targets[hfSources[i].Index], sized) + sized = sized && s + listed = listed && l + } + + if !sized { + return out.givenUp(listed) + } + out.canPin = out.bytes > 0 + return out +} + +// budgetHFSource adds one hf:// source to the budget. It reports whether +// the source was sized and whether its files were all named. Once an +// earlier source has given up the total (sized false), a source naming +// one file is listed by name without asking the remote again. +func (m *Manager) budgetHFSource(ctx context.Context, cfg config.Config, out *downloadBudget, src config.ModelSource, t hfTarget, sized bool) (bool, bool) { + file := singleHFFile(src) + if !sized && t.entry == nil && file != "" { + out.queue = append(out.queue, m.unsizedHFRow(src, t.commit, file)) + return false, true + } + est, err := estimateHFTarget(ctx, cfg, src, t) + if len(est.Entries) > 0 { + if out.trees == nil { + out.trees = make(map[int][]hfwrap.TreeEntry) + } + out.trees[src.Index] = est.Entries + } + if err != nil || !est.Complete || est.Bytes <= 0 { + if sized { + attrs := []any{slog.Int("source_index", src.Index), slog.String("repo", src.HFRepo)} + if err != nil { + attrs = append(attrs, slog.String("err", err.Error())) } - out.trees[hfSources[i].Index] = est.Entries + slog.Warn("download size unknown: an hf source could not be sized, so progress shows no total", attrs...) } - if err != nil || !est.Complete || est.Bytes <= 0 { - return out.givenUp() + if file == "" { + return false, false } - out.bytes += est.Bytes - out.files += est.Files - cached := cachedHFSnapshotFiles(m.hfCacheRoot(), hfSources[i]) - for _, e := range est.Entries { - fp := progress.FileProgress{Path: e.Path, BytesTotal: e.Size, Status: progress.FileWaiting} - if n := cached[e.Path]; n > 0 { - fp.Status = progress.FileDone - fp.BytesCompleted = n - if fp.BytesTotal > 0 && fp.BytesCompleted > fp.BytesTotal { - fp.BytesCompleted = fp.BytesTotal - } - } - out.queue = append(out.queue, fp) + out.queue = append(out.queue, m.unsizedHFRow(src, t.commit, file)) + return false, true + } + out.bytes += est.Bytes + out.files += est.Files + for _, e := range est.Entries { + fp := progress.FileProgress{Path: e.Path, BytesTotal: e.Size, Status: progress.FileWaiting} + if hasHFFile(m.hfCacheRoot(), src.HFRepo, est.Commit, e) { + fp.Status = progress.FileDone + fp.BytesCompleted = e.Size + out.bytesCached += e.Size + out.filesCached++ } + out.queue = append(out.queue, fp) } + return true, true +} - out.canPin = out.bytes > 0 - return out +// unsizedHFRow is the row for a file the budget could not size. hf links +// snapshots// only once the file is complete, so a link at +// the resolved commit means there is nothing left to fetch. +func (m *Manager) unsizedHFRow(src config.ModelSource, commit, file string) progress.FileProgress { + fp := progress.FileProgress{Path: file, Status: progress.FileWaiting} + if root := m.hfCacheRoot(); root != "" && isResolvedCommit(commit) && filepath.IsLocal(filepath.FromSlash(file)) { + p := filepath.Join(hfwrap.SnapshotPath(root, src.HFRepo, commit), filepath.FromSlash(file)) + if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() && info.Size() > 0 { + fp.Status = progress.FileDone + fp.BytesTotal = info.Size() + fp.BytesCompleted = info.Size() + } + } + return fp } // givenUp is the budget to return when one source could not be sized: // no denominator to pin, but the cached counts and whatever listings -// were fetched before giving up are still worth carrying out. -func (b downloadBudget) givenUp() downloadBudget { - return downloadBudget{ +// were fetched are still worth carrying out, and so is the file list +// when it names every file the pass fetches. +func (b downloadBudget) givenUp(listed bool) downloadBudget { + out := downloadBudget{ bytesCached: b.bytesCached, filesCached: b.filesCached, trees: b.trees, + commits: b.commits, + } + if listed { + out.queue = b.queue + } + return out +} + +// hfTarget is what the budget learned about one hf:// source before +// sizing it: the commit its revision resolved to ("" when it did not), +// and for a source naming one file, that file as the HEAD described it. +type hfTarget struct { + commit string + entry *hfwrap.TreeEntry +} + +func commitsOf(targets map[int]hfTarget) map[int]string { + var commits map[int]string + for idx, t := range targets { + if t.commit == "" { + continue + } + if commits == nil { + commits = make(map[int]string, len(targets)) + } + commits[idx] = t.commit } + return commits } -func estimateHFSource(ctx context.Context, cfg config.Config, source config.ModelSource) (hfwrap.RepoEstimate, error) { +// resolveHFTargets resolves every hf:// source, by segment index. +// +// A repo and revision is resolved once per pass. A main GGUF and its +// projector usually share one, and the second source then only needs +// its size, asked at the commit the first resolved to so both files +// come from one revision. A revision that could not be resolved is not +// tried again for the next source: the remote just failed every attempt. +func (m *Manager) resolveHFTargets(ctx context.Context, cfg config.Config, sources []config.ModelSource) map[int]hfTarget { + targets := make(map[int]hfTarget) + resolved := make(map[string]string) + for i := range sources { + src := sources[i] + if src.Kind != config.KindHF { + continue + } + key := src.HFRepo + "@" + src.HFRevision + commit, done := resolved[key] + if !done { + targets[src.Index] = m.resolveHFTarget(ctx, cfg, src) + resolved[key] = targets[src.Index].commit + continue + } + t := hfTarget{commit: commit} + if file := singleHFFile(src); file != "" && commit != "" { + if h, err := hfwrap.HeadFile(ctx, hfLookupConfig(cfg, src, commit, file)); err == nil && h.Commit == commit { + t.entry = sizedEntry(h.Entry) + } + } + targets[src.Index] = t + } + return targets +} + +// hfResolveAttempts is how many lookups a revision gets before the +// remote counts as unreachable for this pass. +const hfResolveAttempts = 3 + +// hfHeadGrace is how long an attempt that already has the commit from +// the revision API still waits for the HEAD, whose answer also sizes +// the file. +const hfHeadGrace = 3 * time.Second + +// resolveHFTarget looks up the commit a source's revision names now. +// A target without a commit means every attempt failed: runHF then +// downloads at the revision as given, and hf falls back to the snapshot +// refs/ points at if it cannot reach the remote either. +func (m *Manager) resolveHFTarget(ctx context.Context, cfg config.Config, source config.ModelSource) hfTarget { + file := singleHFFile(source) + wait := m.opts.HFResolveBackoff + for attempt := 1; ; attempt++ { + t, err := lookupHFTarget(ctx, cfg, source, file) + if err == nil { + return t + } + if attempt == hfResolveAttempts { + slog.Warn("remote unreachable: hf revision not resolved; a cached snapshot may be used instead", + slog.String("repo", source.HFRepo), + slog.String("revision", source.HFRevision), + slog.Int("attempts", attempt), + slog.String("err", err.Error())) + return hfTarget{} + } + slog.Warn("hf revision lookup failed, retrying", + slog.String("repo", source.HFRepo), + slog.String("revision", source.HFRevision), + slog.Int("attempt", attempt), + slog.Int("attempts", hfResolveAttempts), + slog.String("err", err.Error())) + select { + case <-ctx.Done(): + return hfTarget{} + case <-time.After(wait): + } + wait *= 2 + } +} + +// lookupHFTarget is one attempt. It asks the revision API and, when the +// source names one file, HEADs that file, both at once: asked one after +// the other, an unreachable remote cost two timeouts per attempt. +func lookupHFTarget(ctx context.Context, cfg config.Config, source config.ModelSource, file string) (hfTarget, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + type answer struct { + target hfTarget + err error + head bool + } + answers := make(chan answer, 2) + pending := 1 + go func() { + c, err := hfwrap.ResolveCommit(ctx, hfLookupConfig(cfg, source, source.HFRevision, "")) + answers <- answer{target: hfTarget{commit: c}, err: err} + }() + if file != "" { + pending++ + go func() { + h, err := hfwrap.HeadFile(ctx, hfLookupConfig(cfg, source, source.HFRevision, file)) + answers <- answer{target: hfTarget{commit: h.Commit, entry: sizedEntry(h.Entry)}, err: err, head: true} + }() + } + + var fromAPI *hfTarget + var errs []error + var grace <-chan time.Time + for pending > 0 { + select { + case a := <-answers: + pending-- + switch { + case a.err != nil: + errs = append(errs, a.err) + case a.head || pending == 0: + return a.target, nil + default: + fromAPI = &a.target + grace = time.After(hfHeadGrace) + } + case <-grace: + return *fromAPI, nil + } + } + if fromAPI != nil { + return *fromAPI, nil + } + return hfTarget{}, errors.Join(errs...) +} + +// singleHFFile is the one file a source downloads by name, or "" when +// a HEAD on it would not describe everything the source fetches: a +// pattern, a --subdir the tree walk filters by, or an --exclude that +// drops it. +func singleHFFile(ms config.ModelSource) string { + if len(ms.HFInclude) != 1 || ms.HFSubdir != "" { + return "" + } + f := strings.TrimPrefix(strings.TrimSpace(ms.HFInclude[0]), "/") + if f == "" || strings.ContainsAny(f, "*?[") || !hfwrap.MatchPatterns(f, nil, ms.HFExclude) { + return "" + } + return f +} + +func hfLookupConfig(cfg config.Config, src config.ModelSource, revision, file string) hfwrap.Config { + return hfwrap.Config{ + Repo: src.HFRepo, + Revision: revision, + Token: cfg.HFToken, + Endpoint: cfg.HFEndpoint, + HFFile: file, + } +} + +// sizedEntry keeps a HEAD's description only when it carried a size; +// without one the budget lists the tree instead. +func sizedEntry(e hfwrap.TreeEntry) *hfwrap.TreeEntry { + if e.Size <= 0 { + return nil + } + return &e +} + +// estimateHFTarget sizes one source from its HEAD when that answered, +// and from the tree at the resolved commit otherwise. +func estimateHFTarget(ctx context.Context, cfg config.Config, source config.ModelSource, t hfTarget) (hfwrap.RepoEstimate, error) { + if t.entry != nil { + return hfwrap.RepoEstimate{ + Bytes: t.entry.Size, + Files: 1, + Complete: true, + Entries: []hfwrap.TreeEntry{*t.entry}, + Commit: t.commit, + }, nil + } + return estimateHFSource(ctx, cfg, source, t.commit) +} + +func estimateHFSource(ctx context.Context, cfg config.Config, source config.ModelSource, commit string) (hfwrap.RepoEstimate, error) { + rev := source.HFRevision + if commit != "" { + rev = commit + } wrap := hfwrap.Config{ Repo: source.HFRepo, - Revision: source.HFRevision, + Revision: rev, Token: cfg.HFToken, Endpoint: cfg.HFEndpoint, } @@ -323,53 +631,47 @@ func regularFileSize(path string) int64 { return info.Size() } -// cachedHFSnapshot sums finished snapshot files for an hf:// source -// using the same include / exclude / subdir rules as EstimateRepo. -// Hub `.incomplete` blobs are ignored — their names are etag+uuid and -// are not reliably resumable across hf CLI reruns. -func cachedHFSnapshot(cacheRoot string, ms config.ModelSource) (bytes int64, files int) { - sizes := cachedHFSnapshotFiles(cacheRoot, ms) - for _, n := range sizes { - bytes += n - files++ - } - return bytes, files +// hasHFFile reports whether the content the target commit lists for one +// file is already in the local cache. +// +// The local refs/ is no guide here: it names the snapshot an +// earlier pass fetched, and when the branch has moved since, that +// snapshot holds files with the same names and different bytes. Seeding +// those as done counted the old model toward the new one, and the +// transfer of the new one on top of that drove bytes_completed past +// bytes_total. Both checks below are keyed by the target, so an old +// version never matches: +// +// - snapshots// exists only once hf finished that file +// for that commit, however it named the blob. Mirrors that omit +// X-Linked-ETag (the Olares one) make hf name blobs by the mirror's +// ETag, which no Hub id predicts. +// - blobs/ catches content the target shares with a revision +// fetched earlier, which hf skips without linking it in yet. +// +// A `.incomplete` partial is not counted: hf resumes it and the +// first tqdm tick already carries the bytes it holds. +func hasHFFile(cacheRoot, repo, commit string, e hfwrap.TreeEntry) bool { + if hasHFBlob(cacheRoot, repo, e) { + return true + } + if cacheRoot == "" || repo == "" || !isResolvedCommit(commit) || !filepath.IsLocal(filepath.FromSlash(e.Path)) { + return false + } + p := filepath.Join(hfwrap.SnapshotPath(cacheRoot, repo, commit), filepath.FromSlash(e.Path)) + info, err := os.Stat(p) + return err == nil && info.Mode().IsRegular() && info.Size() == e.Size } -func cachedHFSnapshotFiles(cacheRoot string, ms config.ModelSource) map[string]int64 { - out := make(map[string]int64) - if ms.Kind != config.KindHF || ms.HFRepo == "" || cacheRoot == "" { - return out - } - sha, err := hfwrap.ReadRefCommit(cacheRoot, ms.HFRepo, ms.HFRevision) - if err != nil || sha == "" { - return out +// hasHFBlob looks the content up under blobs/ by the id the Hub gave it. +func hasHFBlob(cacheRoot, repo string, e hfwrap.TreeEntry) bool { + if cacheRoot == "" || repo == "" || !isHFBlobID(e.BlobID) { + return false } - snap := hfwrap.SnapshotPath(cacheRoot, ms.HFRepo, sha) - _ = filepath.WalkDir(snap, func(p string, d os.DirEntry, err error) error { - if err != nil || d.IsDir() { - return err - } - rel, rerr := filepath.Rel(snap, p) - if rerr != nil { - return nil - } - rel = filepath.ToSlash(rel) - if strings.HasSuffix(rel, ".incomplete") { - return nil - } - if !hfwrap.UnderSubdir(rel, ms.HFSubdir) { - return nil - } - if !hfwrap.MatchPatterns(rel, ms.HFInclude, ms.HFExclude) { - return nil - } - n := regularFileSize(p) - if n <= 0 { - return nil - } - out[rel] = n - return nil - }) - return out + info, err := os.Stat(filepath.Join(hfwrap.HFRepoCacheDir(cacheRoot, repo), "blobs", e.BlobID)) + return err == nil && info.Mode().IsRegular() && info.Size() == e.Size } + +// isHFBlobID accepts the two forms the cache names blobs by, which also +// keeps an id from a misbehaving endpoint from naming a path elsewhere. +func isHFBlobID(s string) bool { return isSHA256Hex(s) || isResolvedCommit(s) } diff --git a/internal/lifecycle/download_budget_phase_test.go b/internal/lifecycle/download_budget_phase_test.go index 3671002..4016621 100644 --- a/internal/lifecycle/download_budget_phase_test.go +++ b/internal/lifecycle/download_budget_phase_test.go @@ -1,12 +1,16 @@ package lifecycle import ( + "bytes" "context" "fmt" + "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" + "strings" + "sync/atomic" "testing" "time" @@ -79,18 +83,18 @@ func TestEnterDownloadPhase_TreeFailureLeavesDynamic(t *testing.T) { func TestEnterDownloadPhase_ResumeSeedsCachedSnapshot(t *testing.T) { t.Parallel() - cache, repo := writeHFSnapshot(t, "owner/full", "main", map[string]int{ - "a.bin": 100, + cache, repo := writeHFBlobs(t, "owner/full", map[string]int{ + blobA: 100, }) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/models/owner/full/tree/main" { http.NotFound(w, r) return } - fmt.Fprint(w, `[ - {"path":"a.bin","size":100,"type":"file"}, - {"path":"b.bin","size":200,"type":"file"} - ]`) + fmt.Fprintf(w, `[ + {"path":"a.bin","size":100,"type":"file","oid":"%s","lfs":{"oid":"%s"}}, + {"path":"b.bin","size":200,"type":"file","oid":"%s","lfs":{"oid":"%s"}} + ]`, gitOID1, blobA, gitOID2, blobB) })) t.Cleanup(server.Close) @@ -158,11 +162,11 @@ func TestEnterDownloadPhase_SeedsWaitingFileList(t *testing.T) { func TestEnterDownloadPhase_ForceDropsCachedSeed(t *testing.T) { t.Parallel() - cache, repo := writeHFSnapshot(t, "owner/full", "main", map[string]int{ - "a.bin": 100, + cache, repo := writeHFBlobs(t, "owner/full", map[string]int{ + blobA: 100, }) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - fmt.Fprint(w, `[{"path":"a.bin","size":100,"type":"file"}]`) + fmt.Fprintf(w, `[{"path":"a.bin","size":100,"type":"file","oid":"%s","lfs":{"oid":"%s"}}]`, gitOID1, blobA) })) t.Cleanup(server.Close) @@ -183,6 +187,539 @@ func TestEnterDownloadPhase_ForceDropsCachedSeed(t *testing.T) { if st.FilesCompleted != 0 { t.Errorf("force: FilesCompleted=%d, want 0", st.FilesCompleted) } + if len(st.Files) != 1 || st.Files[0].Status != progress.FileWaiting || st.Files[0].BytesCompleted != 0 { + t.Errorf("force: files=%+v, want one waiting row at 0", st.Files) + } +} + +// An image ships the old model with refs/main pointing at it; main has +// since moved and every file kept its name. None of the old bytes are +// the new model, so the pass starts from zero rather than full. +func TestEnterDownloadPhase_MovedBranchDoesNotSeedOldSnapshot(t *testing.T) { + t.Parallel() + cache, repo := writeHFSnapshot(t, "unsloth/Qwen-GGUF", "main", map[string]int{ + "model.gguf": 250, + "mmproj.gguf": 50, + }) + writeBlobsInto(t, cache, repo, map[string]int{blobA: 250, blobB: 50}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, `[ + {"path":"model.gguf","size":260,"type":"file","oid":"%s","lfs":{"oid":"%s"}}, + {"path":"mmproj.gguf","size":50,"type":"file","oid":"%s","lfs":{"oid":"%s"}} + ]`, gitOID1, blobC, gitOID2, blobD) + })) + t.Cleanup(server.Close) + + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, cache) + main := config.ModelSource{Kind: config.KindHF, HFRepo: repo, HFRevision: "main", HFInclude: []string{"model.gguf"}} + mmproj := config.ModelSource{Kind: config.KindHF, Role: config.RoleMmproj, HFRepo: repo, HFRevision: "main", HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, mmproj: &mmproj} + m.enterDownloadPhase(context.Background()) + + st := pm.Snapshot() + if st.BytesTotal != 310 || st.BytesCompleted != 0 { + t.Errorf("bytes %d/%d, want 0/310", st.BytesCompleted, st.BytesTotal) + } + if st.FilesTotal != 2 || st.FilesCompleted != 0 { + t.Errorf("files %d/%d, want 0/2", st.FilesCompleted, st.FilesTotal) + } + for _, f := range st.Files { + if f.Status != progress.FileWaiting || f.BytesCompleted != 0 { + t.Errorf("row %+v, want waiting at 0", f) + } + } +} + +// Only the projector moved: the weights' blob is the one main still +// lists, so it is seeded done and only the projector is left to count. +func TestEnterDownloadPhase_SeedsOnlyUnchangedBlobs(t *testing.T) { + t.Parallel() + cache, repo := writeHFBlobs(t, "owner/gguf", map[string]int{ + blobA: 250, + blobB: 50, + blobD + ".incomplete": 20, + "not-a-blob-id-whatever": 50, + }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, `[ + {"path":"model.gguf","size":250,"type":"file","oid":"%s","lfs":{"oid":"%s"}}, + {"path":"mmproj.gguf","size":50,"type":"file","oid":"%s","lfs":{"oid":"%s"}} + ]`, gitOID1, blobA, gitOID2, blobD) + })) + t.Cleanup(server.Close) + + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, cache) + main := config.ModelSource{Kind: config.KindHF, HFRepo: repo, HFInclude: []string{"model.gguf"}} + mmproj := config.ModelSource{Kind: config.KindHF, Role: config.RoleMmproj, HFRepo: repo, HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, mmproj: &mmproj} + m.enterDownloadPhase(context.Background()) + + st := pm.Snapshot() + if st.BytesTotal != 300 || st.BytesCompleted != 250 { + t.Errorf("bytes %d/%d, want 250/300", st.BytesCompleted, st.BytesTotal) + } + if st.FilesCompleted != 1 { + t.Errorf("FilesCompleted=%d, want 1", st.FilesCompleted) + } + want := map[string]progress.FileStatus{"model.gguf": progress.FileDone, "mmproj.gguf": progress.FileWaiting} + for _, f := range st.Files { + if f.Status != want[f.Path] { + t.Errorf("%s status=%q, want %q", f.Path, f.Status, want[f.Path]) + } + } +} + +// The Olares mirror omits X-Linked-ETag, so hf names blobs by the +// mirror's ETag and no Hub id finds them. The target commit's snapshot +// still does; a same-named file in an older snapshot does not count. +func TestEnterDownloadPhase_SeedsTargetSnapshotWithMirrorBlobNames(t *testing.T) { + t.Parallel() + const ( + oldCommit = "0a9186325ff86b0b5eada4af2182542f96b6ac80" + newCommit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + ) + cache := t.TempDir() + repo := "unsloth/Qwen-GGUF" + writeBlobsInto(t, cache, repo, map[string]int{"96a2783ccf0e573991f4f85fb18e210f-10": 250, "2dcaa90923175f6d8a9146132c660bfc-10": 50}) + writeSnapshotAt(t, cache, repo, newCommit, map[string]int{"model.gguf": 250}) + writeSnapshotAt(t, cache, repo, oldCommit, map[string]int{"model.gguf": 250, "mmproj.gguf": 50}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/models/" + repo + "/revision/main": + fmt.Fprintf(w, `{"sha":%q}`, newCommit) + case "/api/models/" + repo + "/tree/" + newCommit: + fmt.Fprintf(w, `[ + {"path":"model.gguf","size":250,"type":"file","oid":"%s","lfs":{"oid":"%s"}}, + {"path":"mmproj.gguf","size":50,"type":"file","oid":"%s","lfs":{"oid":"%s"}} + ]`, gitOID1, blobC, gitOID2, blobD) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, cache) + main := config.ModelSource{Kind: config.KindHF, HFRepo: repo, HFInclude: []string{"model.gguf"}} + mmproj := config.ModelSource{Kind: config.KindHF, Role: config.RoleMmproj, HFRepo: repo, HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, mmproj: &mmproj} + m.enterDownloadPhase(context.Background()) + + st := pm.Snapshot() + if st.BytesTotal != 300 || st.BytesCompleted != 250 { + t.Errorf("bytes %d/%d, want 250/300", st.BytesCompleted, st.BytesTotal) + } + want := map[string]progress.FileStatus{"model.gguf": progress.FileDone, "mmproj.gguf": progress.FileWaiting} + for _, f := range st.Files { + if f.Status != want[f.Path] { + t.Errorf("%s status=%q, want %q", f.Path, f.Status, want[f.Path]) + } + } +} + +// main moves between the estimate and the download. hf must fetch the +// commit the progress was seeded from, and refs/main must name it once +// it lands so the next boot finds the download record through it. +func TestEnsure_DownloadsAtTheEstimatedCommit(t *testing.T) { + t.Parallel() + const ( + estimated = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + movedTo = "1111111111111111111111111111111111111111" + repo = "owner/moving" + ) + var resolves atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/models/" + repo + "/revision/main": + sha := estimated + if resolves.Add(1) > 1 { + sha = movedTo + } + fmt.Fprintf(w, `{"sha":%q}`, sha) + case "/api/models/" + repo + "/tree/" + estimated: + fmt.Fprintf(w, `[{"path":"model.gguf","size":4,"type":"file","oid":"%s","lfs":{"oid":"%s"}}]`, gitOID1, blobA) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + + cache := t.TempDir() + o := baseOptions(t, []config.ModelSource{hfSource(repo, "", "model.gguf")}) + o.HFCacheRoot = cache + o.Config.HFEndpoint = server.URL + var got hfwrap.Config + o.HFRun = func(_ context.Context, c hfwrap.Config, _ progress.Sink) (hfwrap.Result, error) { + got = c + writeSnapshotAt(t, cache, repo, c.Revision, map[string]int{"model.gguf": 4}) + return hfwrap.Result{Status: "ok", Commit: c.Revision, + Path: filepath.Join(hfwrap.SnapshotPath(cache, repo, c.Revision), "model.gguf")}, nil + } + mgr, err := New(o) + if err != nil { + t.Fatal(err) + } + if err := mgr.ensure(context.Background()); err != nil { + t.Fatalf("ensure: %v", err) + } + if got.Revision != estimated { + t.Errorf("hf ran at %q, want the estimated commit %s", got.Revision, estimated) + } + if n := resolves.Load(); n != 1 { + t.Errorf("revision resolved %d times, want once", n) + } + if sha, _ := hfwrap.ReadRefCommit(cache, repo, ""); sha != estimated { + t.Errorf("refs/main = %q, want %s", sha, estimated) + } + if _, ok := mgr.reuseHFDownload(context.Background(), o.Config, o.Config.Sources[0], "size"); !ok { + t.Error("the next pass must reuse the record through refs/main") + } +} + +func TestResolveHFCommit_TriesThreeTimes(t *testing.T) { + t.Parallel() + const commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + var flaky, down atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/models/o/flaky/revision/main": + if flaky.Add(1) < 3 { + http.Error(w, "gateway timeout", http.StatusGatewayTimeout) + return + } + fmt.Fprintf(w, `{"sha":%q}`, commit) + case "/api/models/o/down/revision/main": + down.Add(1) + http.Error(w, "gateway timeout", http.StatusGatewayTimeout) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + + m := &Manager{opts: Options{HFResolveBackoff: time.Millisecond}} + cfg := config.Config{HFEndpoint: server.URL} + if got := m.resolveHFTarget(context.Background(), cfg, config.ModelSource{Kind: config.KindHF, HFRepo: "o/flaky"}); got.commit != commit { + t.Errorf("third attempt answered: got %q, want %s", got.commit, commit) + } + if got := m.resolveHFTarget(context.Background(), cfg, config.ModelSource{Kind: config.KindHF, HFRepo: "o/down"}); got.commit != "" { + t.Errorf("unreachable: got %q, want none", got.commit) + } + if n := down.Load(); n != hfResolveAttempts { + t.Errorf("unreachable remote asked %d times, want %d", n, hfResolveAttempts) + } +} + +// The HEAD and the revision API are asked at once. A HEAD that hangs +// costs the attempt hfHeadGrace once the API has answered, not the +// HEAD's own timeout on top of the API's. +func TestResolveHFTarget_DoesNotWaitOutAHungHead(t *testing.T) { + t.Parallel() + const commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/models/o/r/revision/main" { + fmt.Fprintf(w, `{"sha":%q}`, commit) + return + } + <-r.Context().Done() + })) + t.Cleanup(server.Close) + + m := &Manager{opts: Options{HFResolveBackoff: time.Millisecond}} + src := config.ModelSource{Kind: config.KindHF, HFRepo: "o/r", HFInclude: []string{"model.gguf"}} + start := time.Now() + got := m.resolveHFTarget(context.Background(), config.Config{HFEndpoint: server.URL}, src) + if got.commit != commit || got.entry != nil { + t.Errorf("target %+v, want the API's commit without a size", got) + } + if took := time.Since(start); took > hfHeadGrace+2*time.Second { + t.Errorf("took %s, want about hfHeadGrace (%s)", took, hfHeadGrace) + } +} + +// Everything the pass asks before downloading shares one deadline. A +// remote that never answers ends the estimate there, and the files are +// still listed. +func TestEnterDownloadPhase_StopsAtTheMetadataBudget(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + t.Cleanup(server.Close) + + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, t.TempDir()) + m.opts.MetadataBudget = 300 * time.Millisecond + m.opts.HFResolveBackoff = time.Millisecond + main := config.ModelSource{Kind: config.KindHF, HFRepo: "o/r", HFInclude: []string{"model.gguf"}} + mmproj := config.ModelSource{Kind: config.KindHF, Role: config.RoleMmproj, HFRepo: "o/r", HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, mmproj: &mmproj} + + start := time.Now() + m.enterDownloadPhase(context.Background()) + if took := time.Since(start); took > 3*time.Second { + t.Errorf("estimate took %s, want it bounded by the 300ms budget", took) + } + st := pm.Snapshot() + if st.BytesTotal != 0 || len(st.Files) != 2 { + t.Errorf("bytes_total=%d files=%+v, want no total and both files listed", st.BytesTotal, st.Files) + } +} + +// The Olares mirror answered /api/ with a 401 after fifteen seconds +// while serving file HEADs. A main GGUF and its projector from one repo +// must still be listed and sized up front, from one revision, without +// the API. +func TestEnterDownloadPhase_SizesSingleFileSourcesByHead(t *testing.T) { + t.Parallel() + const ( + commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + repo = "unsloth/vlm" + ) + var api, heads atomic.Int32 + sizes := map[string]int64{"model.gguf": 1000, "mmproj.gguf": 100} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/") { + api.Add(1) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + heads.Add(1) + var rev, file string + if _, err := fmt.Sscanf(strings.ReplaceAll(strings.TrimPrefix(r.URL.Path, "/"+repo+"/resolve/"), "/", " "), "%s %s", &rev, &file); err != nil || r.Method != http.MethodHead || sizes[file] == 0 { + http.NotFound(w, r) + return + } + if rev != "main" && rev != commit { + http.NotFound(w, r) + return + } + w.Header().Set("X-Repo-Commit", commit) + w.Header().Set("ETag", `"0a6cc728b3879babffd375bdba8cafd0-10"`) + w.Header().Set("Content-Length", fmt.Sprint(sizes[file])) + })) + t.Cleanup(server.Close) + + cache := t.TempDir() + writeSnapshotAt(t, cache, repo, commit, map[string]int{"mmproj.gguf": 100}) + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, cache) + main := config.ModelSource{Index: 1, Kind: config.KindHF, HFRepo: repo, HFInclude: []string{"model.gguf"}} + extra := config.ModelSource{Index: 2, Kind: config.KindHF, Role: config.RoleExtra, HFRepo: repo, HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, extras: []config.ModelSource{extra}} + m.enterDownloadPhase(context.Background()) + + st := pm.Snapshot() + if st.BytesTotal != 1100 || st.BytesCompleted != 100 { + t.Errorf("bytes %d/%d, want 100/1100", st.BytesCompleted, st.BytesTotal) + } + want := map[string]progress.FileStatus{"model.gguf": progress.FileWaiting, "mmproj.gguf": progress.FileDone} + if len(st.Files) != len(want) { + t.Fatalf("files %+v, want both listed", st.Files) + } + for _, f := range st.Files { + if f.Status != want[f.Path] { + t.Errorf("%s status=%q, want %q", f.Path, f.Status, want[f.Path]) + } + } + if c := m.pass.hfCommit(main); c != commit { + t.Errorf("main commit %q, want %s", c, commit) + } + if c := m.pass.hfCommit(extra); c != commit { + t.Errorf("extra commit %q, want %s", c, commit) + } + if n := api.Load(); n > 1 { + t.Errorf("/api/ asked %d times, want only the revision lookup beside the first HEAD", n) + } + if n := heads.Load(); n != 2 { + t.Errorf("%d HEADs, want one per file", n) + } +} + +// The mirror times out the projector's HEAD and its tree listing, so the +// pass has no total. The page still lists both files from the start; +// the one without a size reads done when its snapshot link is there. +func TestEnterDownloadPhase_ListsEveryFileWhenOneCannotBeSized(t *testing.T) { + t.Parallel() + const ( + commit = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + repo = "unsloth/vlm" + ) + for _, cached := range []bool{false, true} { + t.Run(fmt.Sprintf("projector_cached=%v", cached), func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/api/models/"+repo+"/revision/main": + fmt.Fprintf(w, `{"sha":%q}`, commit) + case r.URL.Path == "/"+repo+"/resolve/"+commit+"/model.gguf" && r.Method == http.MethodHead: + w.Header().Set("X-Repo-Commit", commit) + w.Header().Set("Content-Length", "1000") + case strings.HasPrefix(r.URL.Path, "/api/"): + http.Error(w, "unauthorized", http.StatusUnauthorized) + default: + http.Error(w, "gateway timeout", http.StatusGatewayTimeout) + } + })) + t.Cleanup(server.Close) + + cache := t.TempDir() + if cached { + writeSnapshotAt(t, cache, repo, commit, map[string]int{"mmproj.gguf": 100}) + } + pm := progress.New(time.Now()) + m := newBudgetManager(t, pm, server.URL, cache) + main := config.ModelSource{Index: 1, Kind: config.KindHF, HFRepo: repo, HFInclude: []string{"model.gguf"}} + extra := config.ModelSource{Index: 2, Kind: config.KindHF, Role: config.RoleExtra, HFRepo: repo, HFInclude: []string{"mmproj.gguf"}} + m.pass = &passState{cfg: config.Config{HFEndpoint: server.URL}, main: &main, extras: []config.ModelSource{extra}} + m.enterDownloadPhase(context.Background()) + + st := pm.Snapshot() + var onDisk int64 + if cached { + onDisk = 100 + } + if st.BytesTotal != onDisk || st.BytesCompleted != onDisk { + t.Errorf("bytes %d/%d, want %d/%d: only what is on disk, no pinned total", + st.BytesCompleted, st.BytesTotal, onDisk, onDisk) + } + want := map[string]progress.FileProgress{ + "mmproj.gguf": {Path: "mmproj.gguf", Status: progress.FileWaiting}, + "model.gguf": {Path: "model.gguf", BytesTotal: 1000, Status: progress.FileWaiting}, + } + if cached { + want["mmproj.gguf"] = progress.FileProgress{Path: "mmproj.gguf", BytesTotal: 100, BytesCompleted: 100, Status: progress.FileDone} + } + if len(st.Files) != len(want) || st.FilesTotal != len(want) { + t.Fatalf("files_total=%d files=%+v, want both listed", st.FilesTotal, st.Files) + } + for _, f := range st.Files { + if f != want[f.Path] { + t.Errorf("row %+v, want %+v", f, want[f.Path]) + } + } + if c := m.pass.hfCommit(extra); c != commit { + t.Errorf("extra commit %q, want %s", c, commit) + } + + sink := pm.Sink() + sink.OnFileStart("model.gguf", 1000) + sink.OnBytes(500) + st = pm.Snapshot() + if st.BytesCompleted != onDisk+500 || st.BytesTotal != onDisk+1000 { + t.Errorf("mid-download bytes %d/%d, want %d/%d", st.BytesCompleted, st.BytesTotal, onDisk+500, onDisk+1000) + } + var rows int64 + for _, f := range st.Files { + rows += f.BytesCompleted + } + if rows != st.BytesCompleted { + t.Errorf("rows add up to %d, the total reads %d", rows, st.BytesCompleted) + } + }) + } +} + +// With the remote unreachable, hf answers from refs/main and exits 0. +// The pass goes on with that snapshot, and says so. Not parallel: it +// swaps the default logger. +func TestEnsure_WarnsWhenHFServesTheCachedSnapshot(t *testing.T) { + const ( + old = "4ca720788d1e01f1bff70c033e0d0028fd02e502" + repo = "owner/offline" + ) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "gateway timeout", http.StatusGatewayTimeout) + })) + t.Cleanup(server.Close) + + cache := t.TempDir() + writeSnapshotAt(t, cache, repo, old, map[string]int{"model.gguf": 4}) + if err := hfwrap.WriteRefCommit(cache, repo, "", old); err != nil { + t.Fatal(err) + } + + var logs bytes.Buffer + restore := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn}))) + t.Cleanup(func() { slog.SetDefault(restore) }) + + o := baseOptions(t, []config.ModelSource{hfSource(repo, "", "model.gguf")}) + o.HFCacheRoot = cache + o.Config.HFEndpoint = server.URL + var got hfwrap.Config + o.HFRun = func(_ context.Context, c hfwrap.Config, _ progress.Sink) (hfwrap.Result, error) { + got = c + return hfwrap.Result{Status: "ok", Commit: old, + Path: filepath.Join(hfwrap.SnapshotPath(cache, repo, old), "model.gguf")}, nil + } + mgr, err := New(o) + if err != nil { + t.Fatal(err) + } + if err := mgr.ensure(context.Background()); err != nil { + t.Fatalf("ensure: %v", err) + } + if got.Revision != "" { + t.Errorf("hf ran at %q, want the revision as given", got.Revision) + } + out := logs.String() + for _, want := range []string{ + `"msg":"remote unreachable: hf revision not resolved; a cached snapshot may be used instead"`, + `"attempts":3`, + `"msg":"hf revision not confirmed before the download; hf returned the cached commit, which may be out of date"`, + `"cached_commit":"` + old + `"`, + } { + if !strings.Contains(out, want) { + t.Errorf("logs lack %s:\n%s", want, out) + } + } +} + +// hf reaching the remote on its own and landing a newer commit is not +// a fallback, and must not be reported as one. +func TestEnsure_NoCacheWarningWhenHFFetchesANewCommit(t *testing.T) { + const ( + old = "4ca720788d1e01f1bff70c033e0d0028fd02e502" + fresh = "4af51b3542f775b0a8e4b310bfb3f17e01c306c9" + repo = "owner/recovered" + ) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "gateway timeout", http.StatusGatewayTimeout) + })) + t.Cleanup(server.Close) + + cache := t.TempDir() + writeSnapshotAt(t, cache, repo, old, map[string]int{"model.gguf": 4}) + if err := hfwrap.WriteRefCommit(cache, repo, "", old); err != nil { + t.Fatal(err) + } + + var logs bytes.Buffer + restore := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn}))) + t.Cleanup(func() { slog.SetDefault(restore) }) + + o := baseOptions(t, []config.ModelSource{hfSource(repo, "", "model.gguf")}) + o.HFCacheRoot = cache + o.Config.HFEndpoint = server.URL + o.HFRun = func(_ context.Context, _ hfwrap.Config, _ progress.Sink) (hfwrap.Result, error) { + writeSnapshotAt(t, cache, repo, fresh, map[string]int{"model.gguf": 5}) + return hfwrap.Result{Status: "ok", Commit: fresh, + Path: filepath.Join(hfwrap.SnapshotPath(cache, repo, fresh), "model.gguf")}, nil + } + mgr, err := New(o) + if err != nil { + t.Fatal(err) + } + if err := mgr.ensure(context.Background()); err != nil { + t.Fatalf("ensure: %v", err) + } + if strings.Contains(logs.String(), "hf returned the cached commit") { + t.Errorf("hf fetched %s, yet the pass reported the cache:\n%s", fresh, logs.String()) + } } func TestEstimateDownloadBudget_ExcludeAndMissingExact(t *testing.T) { @@ -243,30 +780,6 @@ func TestEstimateDownloadBudget_Subdir(t *testing.T) { } } -func TestCachedHFSnapshot_ExcludeAndMissingRef(t *testing.T) { - t.Parallel() - cache, repo := writeHFSnapshot(t, "owner/r", "main", map[string]int{ - "README.md": 10, - "model.gguf": 90, - }) - ms := config.ModelSource{ - Kind: config.KindHF, HFRepo: repo, HFRevision: "main", - HFExclude: []string{"*.md"}, - } - got, n := cachedHFSnapshot(cache, ms) - if got != 90 || n != 1 { - t.Errorf("exclude: %d/%d, want 90/1", got, n) - } - - ms.HFRevision = "does-not-exist" - if got, n = cachedHFSnapshot(cache, ms); got != 0 || n != 0 { - t.Errorf("missing ref: %d/%d, want 0/0", got, n) - } - if got, n = cachedHFSnapshot("", ms); got != 0 || n != 0 { - t.Errorf("empty cache: %d/%d, want 0/0", got, n) - } -} - func newBudgetManager(t *testing.T, pm progress.Manager, endpoint, cache string) *Manager { t.Helper() return &Manager{ @@ -302,3 +815,48 @@ func writeHFSnapshot(t *testing.T, repo, ref string, files map[string]int) (cach } return cache, repo } + +func writeSnapshotAt(t *testing.T, cache, repo, commit string, files map[string]int) { + t.Helper() + snap := hfwrap.SnapshotPath(cache, repo, commit) + for rel, size := range files { + p := filepath.Join(snap, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, make([]byte, size), 0o644); err != nil { + t.Fatal(err) + } + } +} + +const ( + blobA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + blobB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + blobC = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + blobD = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + gitOID1 = "1111111111111111111111111111111111111111" + gitOID2 = "2222222222222222222222222222222222222222" +) + +// writeHFBlobs lays files out under a repo's blobs/ by name, the way the +// HF cache stores content. +func writeHFBlobs(t *testing.T, repo string, blobs map[string]int) (cache, repoID string) { + t.Helper() + cache = t.TempDir() + writeBlobsInto(t, cache, repo, blobs) + return cache, repo +} + +func writeBlobsInto(t *testing.T, cache, repo string, blobs map[string]int) { + t.Helper() + dir := filepath.Join(hfwrap.HFRepoCacheDir(cache, repo), "blobs") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + for name, size := range blobs { + if err := os.WriteFile(filepath.Join(dir, name), make([]byte, size), 0o644); err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/lifecycle/download_budget_test.go b/internal/lifecycle/download_budget_test.go index ba5bb6a..97c3954 100644 --- a/internal/lifecycle/download_budget_test.go +++ b/internal/lifecycle/download_budget_test.go @@ -191,58 +191,62 @@ func TestCachedURLResumeBytes_URLAndOllamaURL(t *testing.T) { } } -func TestCachedHFBytes_FinishedSnapshotOnly(t *testing.T) { +func TestHasHFBlob(t *testing.T) { t.Parallel() - cache := t.TempDir() repo := "owner/repo" - sha := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - refs := filepath.Join(hfwrap.HFRepoCacheDir(cache, repo), "refs") - if err := os.MkdirAll(refs, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(refs, "main"), []byte(sha+"\n"), 0o644); err != nil { - t.Fatal(err) - } - snap := hfwrap.SnapshotPath(cache, repo, sha) - if err := os.MkdirAll(snap, 0o755); err != nil { - t.Fatal(err) - } - file := filepath.Join(snap, "model.gguf") - if err := os.WriteFile(file, make([]byte, 2500), 0o644); err != nil { - t.Fatal(err) - } - // Orphan incomplete must not inflate the seed. - blobs := filepath.Join(hfwrap.HFRepoCacheDir(cache, repo), "blobs") - if err := os.MkdirAll(blobs, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(blobs, "deadbeef.uuid.incomplete"), make([]byte, 9999), 0o644); err != nil { - t.Fatal(err) - } - - ms := config.ModelSource{ - Kind: config.KindHF, - HFRepo: repo, - HFRevision: "main", - HFInclude: []string{"model.gguf"}, - } - if got, n := cachedHFSnapshot(cache, ms); got != 2500 || n != 1 { - t.Errorf("finished snapshot: got %d/%d want 2500/1", got, n) - } - - ms.HFInclude = []string{"*.gguf"} - if got, n := cachedHFSnapshot(cache, ms); got != 2500 || n != 1 { - t.Errorf("glob include: got %d/%d want 2500/1", got, n) + cache, _ := writeHFBlobs(t, repo, map[string]int{ + blobA: 2500, + gitOID1: 10, + blobB + ".incomplete": 9999, + }) + cases := []struct { + name string + e hfwrap.TreeEntry + want bool + }{ + {"lfs blob present", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500, BlobID: blobA}, true}, + {"git blob present", hfwrap.TreeEntry{Path: "config.json", Size: 10, BlobID: gitOID1}, true}, + {"size differs", hfwrap.TreeEntry{Path: "model.gguf", Size: 2600, BlobID: blobA}, false}, + {"only a partial", hfwrap.TreeEntry{Path: "model.gguf", Size: 9999, BlobID: blobB}, false}, + {"absent", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500, BlobID: blobC}, false}, + {"no id", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500}, false}, + {"id names a path", hfwrap.TreeEntry{Path: "x", Size: 0, BlobID: "../refs"}, false}, + } + for _, tc := range cases { + if got := hasHFBlob(cache, repo, tc.e); got != tc.want { + t.Errorf("%s: got %v want %v", tc.name, got, tc.want) + } } - - ms.HFInclude = nil - if got, n := cachedHFSnapshot(cache, ms); got != 2500 || n != 1 { - t.Errorf("whole repo: got %d/%d want 2500/1", got, n) + if hasHFBlob("", repo, cases[0].e) { + t.Error("empty cache root must report nothing cached") } +} - ms.HFInclude = []string{"missing.gguf"} - if got, n := cachedHFSnapshot(cache, ms); got != 0 || n != 0 { - t.Errorf("missing file: got %d/%d want 0/0", got, n) +func TestHasHFFile_TargetSnapshot(t *testing.T) { + t.Parallel() + const commit = "50968a4468ef4233ed78cd7c3de230dd1d61a56b" + repo := "owner/repo" + cache := t.TempDir() + writeSnapshotAt(t, cache, repo, commit, map[string]int{"model.gguf": 2500, "sub/a.json": 7}) + writeBlobsInto(t, cache, repo, map[string]int{"refs-escape": 1}) + cases := []struct { + name string + commit string + e hfwrap.TreeEntry + want bool + }{ + {"in target snapshot", commit, hfwrap.TreeEntry{Path: "model.gguf", Size: 2500, BlobID: blobC}, true}, + {"nested path", commit, hfwrap.TreeEntry{Path: "sub/a.json", Size: 7}, true}, + {"size differs", commit, hfwrap.TreeEntry{Path: "model.gguf", Size: 2600}, false}, + {"other commit", "1111111111111111111111111111111111111111", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500}, false}, + {"no commit", "", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500}, false}, + {"branch name", "main", hfwrap.TreeEntry{Path: "model.gguf", Size: 2500}, false}, + {"path escapes", commit, hfwrap.TreeEntry{Path: "../../blobs/refs-escape", Size: 1}, false}, + } + for _, tc := range cases { + if got := hasHFFile(cache, repo, tc.commit, tc.e); got != tc.want { + t.Errorf("%s: got %v want %v", tc.name, got, tc.want) + } } } @@ -256,36 +260,6 @@ func TestSeedCompletedForPass_ForceDropsResumeBytes(t *testing.T) { } } -func TestCachedHFBytes_Subdir(t *testing.T) { - t.Parallel() - cache := t.TempDir() - repo := "org/embed" - sha := "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" - refs := filepath.Join(hfwrap.HFRepoCacheDir(cache, repo), "refs") - if err := os.MkdirAll(refs, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(refs, "main"), []byte(sha), 0o644); err != nil { - t.Fatal(err) - } - snap := filepath.Join(hfwrap.SnapshotPath(cache, repo, sha), "onnx") - if err := os.MkdirAll(snap, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(snap, "model.onnx"), make([]byte, 120), 0o644); err != nil { - t.Fatal(err) - } - ms := config.ModelSource{ - Kind: config.KindHF, - HFRepo: repo, - HFInclude: []string{"model.onnx"}, - HFSubdir: "onnx", - } - if got, n := cachedHFSnapshot(cache, ms); got != 120 || n != 1 { - t.Errorf("subdir snapshot: got %d/%d want 120/1", got, n) - } -} - func TestEstimateDownloadBudget_WholeHFRepo(t *testing.T) { t.Parallel() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/lifecycle/ensure.go b/internal/lifecycle/ensure.go index 9d53f50..94668a4 100644 --- a/internal/lifecycle/ensure.go +++ b/internal/lifecycle/ensure.go @@ -41,7 +41,12 @@ func (m *Manager) ensure(ctx context.Context) error { return m.fail("no main MODEL_SOURCE configured", false) } - m.pass = &passState{cfg: cfg, main: main, mmproj: mmproj, extras: extras, force: opts.Force} + prevModel := loadedModel(cfg.Runtime.RunDir) + if m.pendingRelaunch != "" { + prevModel = m.pendingRelaunch + } + m.pass = &passState{cfg: cfg, main: main, mmproj: mmproj, extras: extras, force: opts.Force, + prevModel: prevModel} extraPaths := make([]string, 0, len(extras)) for i := range extras { @@ -320,11 +325,24 @@ func (m *Manager) runHF(ctx context.Context, cfg config.Config, ms config.ModelS allow = nil } + // Download at the commit the budget was estimated against, so the + // seeded progress and the bytes hf fetches describe one revision. + // MODEL_SOURCE is untouched: the next pass resolves the branch anew. + rev := ms.HFRevision + commit := m.pass.hfCommit(ms) + var cached string + if commit != "" { + rev = commit + } else { + cached, _ = hfwrap.ReadRefCommit(m.hfCacheRoot(), ms.HFRepo, ms.HFRevision) + } + slog.Info("hf download starting", slog.Int("source_index", ms.Index), slog.String("role", ms.Role), slog.String("repo", ms.HFRepo), slog.String("revision", ms.HFRevision), + slog.String("commit", commit), slog.String("cache_dir", m.hfCacheRoot()), slog.Bool("force", opts.Force), slog.Any("allow_patterns", allow), @@ -333,7 +351,7 @@ func (m *Manager) runHF(ctx context.Context, cfg config.Config, ms config.ModelS wrapCfg := hfwrap.Config{ Repo: ms.HFRepo, - Revision: ms.HFRevision, + Revision: rev, CacheDir: m.hfCacheRoot(), HFFile: hfFile, AllowPatterns: allow, @@ -362,6 +380,27 @@ func (m *Manager) runHF(ctx context.Context, cfg config.Config, ms config.ModelS } return hfwrap.Result{}, m.fail(hfUserMessage(err), retriable) } + if cached != "" && res.Commit == cached { + // hf answers from refs/ when it cannot reach the + // remote, and exits 0 as if it had confirmed the snapshot. It + // says nothing either way, and the same commit also comes back + // when hf did reach the remote and nothing changed, so this + // states what is known rather than which one happened. + slog.Warn("hf revision not confirmed before the download; hf returned the cached commit, which may be out of date", + slog.Int("source_index", ms.Index), + slog.String("repo", ms.HFRepo), + slog.String("revision", ms.HFRevision), + slog.String("cached_commit", cached), + slog.Int("resolve_attempts", hfResolveAttempts)) + } + if rev != ms.HFRevision { + // hf only writes refs/ when it resolves the branch + // itself, and reuseHFDownload finds the snapshot through it. + if err := hfwrap.WriteRefCommit(m.hfCacheRoot(), ms.HFRepo, ms.HFRevision, rev); err != nil { + slog.Warn("could not record the downloaded commit under its revision; the next boot downloads again", + slog.String("repo", ms.HFRepo), slog.String("revision", ms.HFRevision), slog.String("err", err.Error())) + } + } m.writeHFSidecar(cfg, ms, res) return res, nil } diff --git a/internal/lifecycle/manager.go b/internal/lifecycle/manager.go index dd5bbc3..ab1cd64 100644 --- a/internal/lifecycle/manager.go +++ b/internal/lifecycle/manager.go @@ -97,6 +97,15 @@ type Options struct { // channel of one; nil leaves the loop on its own schedule. RelaunchRequested <-chan struct{} + // Relauncher restarts an engine still serving the model a pass has + // just replaced. Nil leaves that engine running. See + // Manager.relaunchIfModelChanged. + Relauncher Relauncher + + // ServedModelRetryInterval is the wait between queries asking an + // alive engine which model it serves. Defaults to 2s. + ServedModelRetryInterval time.Duration + // MaxConcurrentDownloads caps the parallel fan-out for URL fetches // and the hf wrapper's --max-workers flag. 0 → 4. MaxConcurrentDownloads int @@ -116,6 +125,17 @@ type Options struct { // regardless of this value. RetriableBackoff time.Duration + // HFResolveBackoff is the wait after the first failed lookup of an + // hf:// revision, doubled after the second. Defaults to 2s. + HFResolveBackoff time.Duration + + // MetadataBudget bounds everything a pass asks the remote before it + // starts downloading: resolving revisions and sizing the files. When + // it runs out the pass downloads without a pinned total. New defaults + // it to 90s, which covers hfResolveAttempts lookups that each time + // out; zero on a Manager built without New means no budget. + MetadataBudget time.Duration + // NowFunc is the time source. Defaults to time.Now. NowFunc func() time.Time @@ -162,6 +182,11 @@ type Manager struct { // it. See passState. pass *passState + // pendingRelaunch is the model an engine was last seen serving when a + // restart onto a newer one did not happen, or "". Owned by the Run + // goroutine. See relaunchIfModelChanged. + pendingRelaunch string + mu sync.Mutex retry chan struct{} pendingOpts RetryOptions @@ -212,6 +237,15 @@ func New(opts Options) (*Manager, error) { if opts.RetriableBackoff == 0 { opts.RetriableBackoff = 30 * time.Second } + if opts.HFResolveBackoff == 0 { + opts.HFResolveBackoff = 2 * time.Second + } + if opts.MetadataBudget == 0 { + opts.MetadataBudget = 90 * time.Second + } + if opts.ServedModelRetryInterval == 0 { + opts.ServedModelRetryInterval = 2 * time.Second + } if opts.NowFunc == nil { opts.NowFunc = time.Now } @@ -252,6 +286,22 @@ func (m *Manager) Run(ctx context.Context) error { err := m.ensure(ctx) if err == nil { if !aliveBeforeBoot { + if relaunchErr := m.relaunchIfModelChanged(ctx); relaunchErr != nil { + if ctx.Err() != nil { + return ctx.Err() + } + // Ready would claim the new model while the old one + // serves. The next pass, from /api/retry or a + // re-registration, asks for the restart again. + m.opts.Manager.Update(func(s *progress.State) { + s.Phase = progress.PhaseFailed + s.LastError = relaunchErr.Error() + }) + if retryErr := m.waitForRetryOrCtx(ctx, 0); retryErr != nil { + return retryErr + } + continue + } if waitErr := m.opts.Adapter.WaitAlive(ctx); waitErr != nil { if errors.Is(waitErr, context.Canceled) || errors.Is(waitErr, context.DeadlineExceeded) { @@ -270,6 +320,19 @@ func (m *Manager) Run(ctx context.Context) error { } continue } + if verifyErr := m.verifyServedModel(ctx); verifyErr != nil { + if ctx.Err() != nil { + return ctx.Err() + } + m.opts.Manager.Update(func(s *progress.State) { + s.Phase = progress.PhaseFailed + s.LastError = verifyErr.Error() + }) + if retryErr := m.waitForRetryOrCtx(ctx, 0); retryErr != nil { + return retryErr + } + continue + } if rs, readyErr := m.opts.Adapter.Ready(ctx); readyErr == nil { m.lastReady.Store(&rs) } diff --git a/internal/lifecycle/manager_test.go b/internal/lifecycle/manager_test.go index 2cc0aed..778f7fe 100644 --- a/internal/lifecycle/manager_test.go +++ b/internal/lifecycle/manager_test.go @@ -231,13 +231,15 @@ func baseOptions(t *testing.T, sources []config.ModelSource) Options { }, } return Options{ - Config: cfg, - Adapter: &fakeAdapter{kind: cfg.Engine.Kind}, - Manager: progress.New(time.Now()), - Downloader: &fakeDownloader{}, - MaxConcurrentDownloads: 2, - RetriableBackoff: 10 * time.Millisecond, - NowFunc: time.Now, + Config: cfg, + Adapter: &fakeAdapter{kind: cfg.Engine.Kind}, + Manager: progress.New(time.Now()), + Downloader: &fakeDownloader{}, + MaxConcurrentDownloads: 2, + RetriableBackoff: 10 * time.Millisecond, + HFResolveBackoff: time.Millisecond, + ServedModelRetryInterval: time.Millisecond, + NowFunc: time.Now, } } diff --git a/internal/lifecycle/relaunch.go b/internal/lifecycle/relaunch.go new file mode 100644 index 0000000..d8dd778 --- /dev/null +++ b/internal/lifecycle/relaunch.go @@ -0,0 +1,255 @@ +package lifecycle + +import ( + "context" + "errors" + "fmt" + "log/slog" + "path/filepath" + "strings" + "time" + + "github.com/llm-init/llm-init/internal/adapter" + "github.com/llm-init/llm-init/internal/handoff" + "github.com/llm-init/llm-init/internal/sentinel" +) + +// Relauncher asks the engine's supervise loop to relaunch it and reports +// what became of the request. *handoff.Tracker implements it. +type Relauncher interface { + Request() (handoff.Receipt, error) + Status() handoff.Status +} + +// relaunchPollInterval is how often a pass looks at the tracker while +// waiting for its verdict on a relaunch. +const relaunchPollInterval = 500 * time.Millisecond + +// loadedModel is what the run dir currently tells an engine to load: +// model_path and the extra paths, or "" when there is no model_path. +func loadedModel(runDir string) string { + if runDir == "" { + return "" + } + path, err := sentinel.ReadModelPath(runDir) + if err != nil || path == "" { + return "" + } + extras, _ := sentinel.ReadExtraPaths(runDir) + return strings.Join(append([]string{path}, extras...), "\n") +} + +// errEngineServesPreviousModel is why a pass that replaced the model is +// not ready: the engine was not seen restarting onto the new one. +var errEngineServesPreviousModel = errors.New("the engine still serves the previous model; restart it to load the new one") + +// relaunchIfModelChanged restarts an engine that serves a model other +// than the one the run dir names, and fails when the engine was not seen +// to restart. +// +// A wrapper waits for the sentinel once and keeps the engine it started, +// and an engine that resolves the model by name (llama.cpp -hf) picks the +// revision when it starts. On an upgrade that engine started on the +// previous sentinel before the new revision was downloaded, so it serves +// the previous model, and WaitAlive would pass on it. +// +// An engine that reports its model path (adapter.ServedModelReporter) is +// asked directly, which holds across an llm-init restart and a restart +// done by hand. Otherwise, and when only an extra such as the projector +// changed, the run dir as the pass found it is compared with what it +// wrote, and a failed restart stays pending in m.pendingRelaunch: the run +// dir already names the new model, so the next pass would otherwise see +// no change. A first install has no previous model and an engine still +// waiting for the sentinel, so it is left alone. StateUnverified is left +// to WaitAlive, since it says nothing about which model is served. +func (m *Manager) relaunchIfModelChanged(ctx context.Context) error { + p := m.pass + if p == nil || m.opts.Relauncher == nil { + return nil + } + current := loadedModel(p.cfg.Runtime.RunDir) + if current == "" { + return nil + } + if served, ok := m.servedModelPath(ctx); ok { + if !sameModelFile(served, mainModel(current)) { + if err := m.relaunch(ctx, served, current); err != nil { + return err + } + m.pendingRelaunch = "" + return nil + } + if !extrasOnlyChange(p.prevModel, current) { + m.pendingRelaunch = "" + return nil + } + } + if p.prevModel == "" || current == p.prevModel { + m.pendingRelaunch = "" + return nil + } + if err := m.relaunch(ctx, p.prevModel, current); err != nil { + m.pendingRelaunch = p.prevModel + return err + } + m.pendingRelaunch = "" + return nil +} + +// relaunch asks the engine to restart onto current and waits for the +// tracker's verdict. +func (m *Manager) relaunch(ctx context.Context, previous, current string) error { + receipt, err := m.opts.Relauncher.Request() + if err != nil { + slog.Warn("the model changed but the engine could not be asked to restart; it still serves the previous model", + slog.String("previous", previous), + slog.String("current", current), + slog.String("err", err.Error())) + return fmt.Errorf("%w: %w", errEngineServesPreviousModel, err) + } + slog.Info("the model changed; restarting the engine so it loads the new one", + slog.String("previous", previous), + slog.String("current", current), + slog.String("generation", receipt.Generation)) + st := m.awaitRelaunchVerdict(ctx, receipt.Generation) + if err := ctx.Err(); err != nil { + return err + } + if st.State == handoff.StateNoSupervisor { + slog.Warn("the engine did not restart after the model changed and still serves the previous model; restart it to load the new one", + slog.String("previous", previous), + slog.String("current", current)) + return errEngineServesPreviousModel + } + m.pass.relaunched = true + return nil +} + +// servedModelAttempts is how many times verifyServedModel asks an alive +// engine which model it loaded before letting it through unanswered. +const servedModelAttempts = 6 + +// verifyServedModel asks an alive engine which model it loaded, whether +// or not the pass restarted it: a query before WaitAlive can fail while +// the engine loads, which hides an engine still on the previous model. +// One that serves another model than the run dir's is restarted once +// within the pass, and the pass fails when it comes back on another +// model again. +// +// An engine that does not answer after servedModelAttempts is let +// through, since WaitAlive passed and a llama.cpp build without /props +// would otherwise never be ready. +func (m *Manager) verifyServedModel(ctx context.Context) error { + p := m.pass + if p == nil || m.opts.Relauncher == nil { + return nil + } + if _, ok := m.opts.Adapter.(adapter.ServedModelReporter); !ok { + return nil + } + current := loadedModel(p.cfg.Runtime.RunDir) + want := mainModel(current) + if want == "" { + return nil + } + for { + served, ok := m.awaitServedModelPath(ctx) + if err := ctx.Err(); err != nil { + return err + } + if !ok { + slog.Warn("the engine is alive but did not say which model it serves; calling it ready", + slog.String("want", want)) + return nil + } + if sameModelFile(served, want) { + return nil + } + if p.relaunched { + slog.Warn("the engine restarted but loaded a model other than the one downloaded", + slog.String("served", served), + slog.String("want", want)) + return fmt.Errorf("the engine restarted on %s, not %s", served, want) + } + if err := m.relaunch(ctx, served, current); err != nil { + return err + } + if err := m.opts.Adapter.WaitAlive(ctx); err != nil { + return fmt.Errorf("engine never came alive: %w", err) + } + } +} + +// awaitServedModelPath is servedModelPath retried every +// ServedModelRetryInterval, up to servedModelAttempts times. +func (m *Manager) awaitServedModelPath(ctx context.Context) (string, bool) { + for attempt := 1; ; attempt++ { + if served, ok := m.servedModelPath(ctx); ok { + return served, true + } + if attempt == servedModelAttempts { + return "", false + } + select { + case <-ctx.Done(): + return "", false + case <-time.After(m.opts.ServedModelRetryInterval): + } + } +} + +// servedModelPath asks the engine which model file it loaded. ok is false +// when the engine cannot say. +func (m *Manager) servedModelPath(ctx context.Context) (string, bool) { + r, ok := m.opts.Adapter.(adapter.ServedModelReporter) + if !ok { + return "", false + } + path, err := r.ServedModelPath(ctx) + if err != nil || path == "" { + return "", false + } + return path, true +} + +// mainModel is the model_path line of a loadedModel value. +func mainModel(loaded string) string { + main, _, _ := strings.Cut(loaded, "\n") + return main +} + +// extrasOnlyChange reports whether the pass changed an extra path but +// kept the main model, which an engine's own report cannot show. +func extrasOnlyChange(prev, current string) bool { + return prev != "" && prev != current && mainModel(prev) == mainModel(current) +} + +// sameModelFile compares two paths to a model file. Paths into an HF +// cache are compared from the models---- directory on, since +// the engine and llm-init may mount the cache at different roots. +func sameModelFile(a, b string) bool { + a, b = filepath.ToSlash(filepath.Clean(a)), filepath.ToSlash(filepath.Clean(b)) + if a == b { + return true + } + ia, ib := strings.LastIndex(a, "/models--"), strings.LastIndex(b, "/models--") + return ia >= 0 && ib >= 0 && a[ia:] == b[ib:] +} + +// awaitRelaunchVerdict waits until the tracker stops watching the request +// it was given: the engine went down, or the window closed without it. +// WaitAlive then waits for the relaunched engine rather than passing on +// the one about to be stopped. +func (m *Manager) awaitRelaunchVerdict(ctx context.Context, generation string) handoff.Status { + for { + st := m.opts.Relauncher.Status() + if st.Generation != generation || st.State != handoff.StateWatching { + return st + } + select { + case <-ctx.Done(): + return st + case <-time.After(relaunchPollInterval): + } + } +} diff --git a/internal/lifecycle/relaunch_test.go b/internal/lifecycle/relaunch_test.go new file mode 100644 index 0000000..5a8b997 --- /dev/null +++ b/internal/lifecycle/relaunch_test.go @@ -0,0 +1,433 @@ +package lifecycle + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/llm-init/llm-init/internal/adapter" + "github.com/llm-init/llm-init/internal/adapter/hfwrap" + "github.com/llm-init/llm-init/internal/config" + "github.com/llm-init/llm-init/internal/handoff" + "github.com/llm-init/llm-init/internal/progress" + "github.com/llm-init/llm-init/internal/sentinel" +) + +// fakeRelauncher settles every request to the state it is given, as a +// tracker does once it has watched the engine. +type fakeRelauncher struct { + settle handoff.State + err error + onRequest func() + mu sync.Mutex + requests int + status handoff.Status +} + +func (f *fakeRelauncher) Request() (handoff.Receipt, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.requests++ + if f.err != nil { + return handoff.Receipt{}, f.err + } + if f.onRequest != nil && f.settle == handoff.StateConfirmed { + f.onRequest() + } + gen := time.Now().String() + f.status = handoff.Status{State: f.settle, Generation: gen} + return handoff.Receipt{Signaled: true, Generation: gen}, nil +} + +func (f *fakeRelauncher) Status() handoff.Status { + f.mu.Lock() + defer f.mu.Unlock() + return f.status +} + +func (f *fakeRelauncher) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.requests +} + +func (f *fakeRelauncher) set(settle handoff.State, err error) { + f.mu.Lock() + defer f.mu.Unlock() + f.settle, f.err = settle, err +} + +// An engine that did not restart onto the new model still serves the +// previous one, so the pass fails instead of calling it ready. The run +// dir already names the new model, yet the next pass asks for the +// restart again, and is ready once it happens. +func TestRun_FailsUntilTheEngineRestartsOntoTheNewModel(t *testing.T) { + t.Parallel() + cases := []struct { + name string + settle handoff.State + err error + }{ + {name: "no_supervisor", settle: handoff.StateNoSupervisor}, + {name: "request_failed", err: errors.New("run dir read-only")}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + runDir := t.TempDir() + mainPath := filepath.Join(t.TempDir(), "model.gguf") + if err := os.WriteFile(mainPath, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if err := sentinel.Write(runDir, "/cache/snapshots/old/model.gguf"); err != nil { + t.Fatal(err) + } + o := baseOptions(t, []config.ModelSource{ + hfSource("a/b", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "model.gguf"), + }) + o.Config.Runtime.RunDir = runDir + o.Config.Engine.Kind = config.EngineLlamaCpp + o.HFRun = func(context.Context, hfwrap.Config, progress.Sink) (hfwrap.Result, error) { + return hfwrap.Result{Status: "ok", Path: mainPath}, nil + } + rl := &fakeRelauncher{settle: tc.settle, err: tc.err} + o.Relauncher = rl + aliveBeforeBoot := false + var waits atomic.Int32 + o.Adapter = &fakeAdapter{ + kind: config.EngineLlamaCpp, + aliveBeforeBoot: &aliveBeforeBoot, + readyState: adapter.ReadyState{Alive: true, ModelExists: true}, + waitFn: func(context.Context) error { + waits.Add(1) + return nil + }, + } + mgr, err := New(o) + if err != nil { + t.Fatalf("New: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = mgr.Run(ctx) }() + + waitPhase(t, o.Manager, progress.PhaseFailed) + if st := o.Manager.Snapshot(); !strings.Contains(st.LastError, "still serves the previous model") { + t.Errorf("last_error = %q, want it to say the previous model is served", st.LastError) + } + if n := waits.Load(); n != 0 { + t.Errorf("WaitAlive ran %d times on the engine serving the previous model", n) + } + + rl.set(handoff.StateConfirmed, nil) + mgr.Retry() + waitPhase(t, o.Manager, progress.PhaseReady) + if got := rl.count(); got != 2 { + t.Errorf("relaunch requests = %d, want the retry to ask again", got) + } + }) + } +} + +// reportingAdapter is an engine that says which model file it loaded, +// as llama.cpp does in /props. An empty path is an engine that cannot +// answer, and so are the first failFirst queries, as /props answers 503 +// while a model loads. +type reportingAdapter struct { + *fakeAdapter + mu sync.Mutex + served string + failFirst int + queries int +} + +func (r *reportingAdapter) ServedModelPath(context.Context) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.queries++ + if r.queries <= r.failFirst { + return "", errors.New("503 loading model") + } + if r.served == "" { + return "", errors.New("engine down") + } + return r.served, nil +} + +func (r *reportingAdapter) serve(path string) { + r.mu.Lock() + defer r.mu.Unlock() + r.served = path +} + +// An engine that reports its model is asked rather than trusted to match +// the run dir. That holds when llm-init restarted after a failed engine +// restart (the run dir already names the new model) and when the engine +// was restarted by hand, and it catches an engine that came back on the +// previous model. +func TestRun_AsksTheEngineWhichModelItServes(t *testing.T) { + t.Parallel() + const oldPath = "/cache/hf/hub/models--a--b/snapshots/old/model.gguf" + cases := []struct { + name string + sentinel string // "new" seeds the path this pass writes + served string // "new" is the path this pass writes + settle handoff.State + loadsNew bool // a confirmed restart comes back on the new model + wantPhase progress.Phase + wantReqs int + wantErrHas string + }{ + {name: "llm_init_restarted", sentinel: "new", served: oldPath, settle: handoff.StateConfirmed, loadsNew: true, wantPhase: progress.PhaseReady, wantReqs: 1}, + {name: "engine_already_on_new", sentinel: oldPath, served: "new", settle: handoff.StateConfirmed, wantPhase: progress.PhaseReady, wantReqs: 0}, + {name: "came_back_on_old", sentinel: oldPath, served: oldPath, settle: handoff.StateConfirmed, wantPhase: progress.PhaseFailed, wantReqs: 1, wantErrHas: "restarted on"}, + {name: "no_supervisor", sentinel: oldPath, served: oldPath, settle: handoff.StateNoSupervisor, wantPhase: progress.PhaseFailed, wantReqs: 1, wantErrHas: "still serves the previous model"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + o, rl, ra, newPath := reportingSetup(t, tc.sentinel, tc.served, tc.settle, tc.loadsNew) + mgr, err := New(o) + if err != nil { + t.Fatalf("New: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = mgr.Run(ctx) }() + + waitPhase(t, o.Manager, tc.wantPhase) + if got := rl.count(); got != tc.wantReqs { + t.Errorf("relaunch requests = %d, want %d", got, tc.wantReqs) + } + if tc.wantErrHas != "" && !strings.Contains(o.Manager.Snapshot().LastError, tc.wantErrHas) { + t.Errorf("last_error = %q, want it to contain %q", o.Manager.Snapshot().LastError, tc.wantErrHas) + } + if tc.wantPhase != progress.PhaseFailed { + return + } + // Restarted by hand onto the new model: the retry finds it + // there and asks for nothing more. + ra.serve(newPath) + mgr.Retry() + waitPhase(t, o.Manager, progress.PhaseReady) + if got := rl.count(); got != tc.wantReqs { + t.Errorf("relaunch requests after a restart by hand = %d, want still %d", got, tc.wantReqs) + } + }) + } +} + +// The engine is checked once alive even when the pass asked for no +// restart. llm-init restarted while the engine was still loading the +// previous model onto a run dir that already named the new one, so the +// first queries fail and nothing looks changed; the engine that comes +// alive is on the previous model and is restarted within the same pass. +// An engine that never says is ready, since WaitAlive passed and a +// llama.cpp without /props would otherwise never be. +func TestRun_ChecksTheServedModelOnceAlive(t *testing.T) { + t.Parallel() + const oldPath = "/cache/hf/hub/models--a--b/snapshots/old/model.gguf" + cases := []struct { + name string + served string + failFirst int + loadsNew bool + wantPhase progress.Phase + wantReqs int + wantErrHas string + }{ + {name: "loading_previous_when_llm_init_restarted", served: oldPath, failFirst: 2, loadsNew: true, wantPhase: progress.PhaseReady, wantReqs: 1}, + {name: "comes_back_on_previous", served: oldPath, failFirst: 2, wantPhase: progress.PhaseFailed, wantReqs: 1, wantErrHas: "restarted on"}, + {name: "never_says", served: "", wantPhase: progress.PhaseReady, wantReqs: 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + o, rl, ra, _ := reportingSetup(t, "new", tc.served, handoff.StateConfirmed, tc.loadsNew) + ra.failFirst = tc.failFirst + mgr, err := New(o) + if err != nil { + t.Fatalf("New: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = mgr.Run(ctx) }() + + waitPhase(t, o.Manager, tc.wantPhase) + if got := rl.count(); got != tc.wantReqs { + t.Errorf("relaunch requests = %d, want %d", got, tc.wantReqs) + } + if tc.wantErrHas != "" && !strings.Contains(o.Manager.Snapshot().LastError, tc.wantErrHas) { + t.Errorf("last_error = %q, want it to contain %q", o.Manager.Snapshot().LastError, tc.wantErrHas) + } + }) + } +} + +func reportingSetup(t *testing.T, sentinelPath, served string, settle handoff.State, loadsNew bool) (Options, *fakeRelauncher, *reportingAdapter, string) { + t.Helper() + runDir := t.TempDir() + newPath := filepath.Join(t.TempDir(), "model.gguf") + if err := os.WriteFile(newPath, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if sentinelPath == "new" { + sentinelPath = newPath + } + if served == "new" { + served = newPath + } + if err := sentinel.Write(runDir, sentinelPath); err != nil { + t.Fatal(err) + } + o := baseOptions(t, []config.ModelSource{ + hfSource("a/b", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "model.gguf"), + }) + o.Config.Runtime.RunDir = runDir + o.Config.Engine.Kind = config.EngineLlamaCpp + o.HFRun = func(context.Context, hfwrap.Config, progress.Sink) (hfwrap.Result, error) { + return hfwrap.Result{Status: "ok", Path: newPath}, nil + } + aliveBeforeBoot := false + ra := &reportingAdapter{ + fakeAdapter: &fakeAdapter{ + kind: config.EngineLlamaCpp, + aliveBeforeBoot: &aliveBeforeBoot, + readyState: adapter.ReadyState{Alive: true, ModelExists: true}, + }, + served: served, + } + o.Adapter = ra + rl := &fakeRelauncher{settle: settle} + if loadsNew { + rl.onRequest = func() { ra.serve(newPath) } + } + o.Relauncher = rl + return o, rl, ra, newPath +} + +func TestSameModelFile(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + a, b string + want bool + }{ + {"/cache/hf/hub/models--o--r/snapshots/c1/m.gguf", "/cache/hf/hub/models--o--r/snapshots/c1/m.gguf", true}, + {"/root/.cache/huggingface/hub/models--o--r/snapshots/c1/m.gguf", "/cache/hf/hub/models--o--r/snapshots/c1/m.gguf", true}, + {"/cache/hf/hub/models--o--r/snapshots/c1/m.gguf", "/cache/hf/hub/models--o--r/snapshots/c2/m.gguf", false}, + {"/models/a/m.gguf", "/models/b/m.gguf", false}, + {"/models/a/./m.gguf", "/models/a/m.gguf", true}, + } { + if got := sameModelFile(tc.a, tc.b); got != tc.want { + t.Errorf("sameModelFile(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want) + } + } + if !extrasOnlyChange("/m.gguf\n/old-mmproj.gguf", "/m.gguf\n/new-mmproj.gguf") { + t.Error("a new projector under the same main model is an extras-only change") + } + if extrasOnlyChange("", "/m.gguf") || extrasOnlyChange("/a.gguf", "/b.gguf") { + t.Error("a first install or a new main model is not an extras-only change") + } +} + +func waitPhase(t *testing.T, pm progress.Manager, want progress.Phase) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for pm.Snapshot().Phase != want { + if time.Now().After(deadline) { + t.Fatalf("phase = %v, want %v", pm.Snapshot().Phase, want) + } + time.Sleep(5 * time.Millisecond) + } +} + +// An upgrade leaves the previous model_path behind, and the engine that +// started on it serves the previous model. When the pass moves the run +// dir to a new model, the engine is asked to relaunch before the pass +// waits for it to come alive; when the pass lands on the same model, or +// there was no model before, it is not. +func TestRun_RelaunchesTheEngineWhenTheModelChanged(t *testing.T) { + t.Parallel() + cases := []struct { + name string + previous string // "" seeds no sentinel; "same" seeds the new path + settle handoff.State + want int + }{ + {name: "upgrade", previous: "/cache/snapshots/old/model.gguf", settle: handoff.StateConfirmed, want: 1}, + {name: "upgrade_unverified", previous: "/cache/snapshots/old/model.gguf", settle: handoff.StateUnverified, want: 1}, + {name: "same_model", previous: "same", settle: handoff.StateConfirmed, want: 0}, + {name: "first_install", previous: "", settle: handoff.StateConfirmed, want: 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + runDir := t.TempDir() + mainPath := filepath.Join(t.TempDir(), "model.gguf") + if err := os.WriteFile(mainPath, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + switch tc.previous { + case "": + case "same": + if err := sentinel.Write(runDir, mainPath); err != nil { + t.Fatal(err) + } + default: + if err := sentinel.Write(runDir, tc.previous); err != nil { + t.Fatal(err) + } + } + + o := baseOptions(t, []config.ModelSource{ + hfSource("a/b", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "model.gguf"), + }) + o.Config.Runtime.RunDir = runDir + o.Config.Engine.Kind = config.EngineLlamaCpp + o.HFRun = func(context.Context, hfwrap.Config, progress.Sink) (hfwrap.Result, error) { + return hfwrap.Result{Status: "ok", Path: mainPath}, nil + } + rl := &fakeRelauncher{settle: tc.settle} + o.Relauncher = rl + aliveBeforeBoot := false + var requestsAtWait atomic.Int32 + requestsAtWait.Store(-1) + o.Adapter = &fakeAdapter{ + kind: config.EngineLlamaCpp, + aliveBeforeBoot: &aliveBeforeBoot, + readyState: adapter.ReadyState{Alive: true, ModelExists: true}, + waitFn: func(context.Context) error { + requestsAtWait.CompareAndSwap(-1, int32(rl.count())) + return nil + }, + } + mgr, err := New(o) + if err != nil { + t.Fatalf("New: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = mgr.Run(ctx) }() + + deadline := time.Now().Add(2 * time.Second) + for o.Manager.Snapshot().Phase != progress.PhaseReady { + if time.Now().After(deadline) { + t.Fatalf("phase = %v, want ready", o.Manager.Snapshot().Phase) + } + time.Sleep(5 * time.Millisecond) + } + if got := rl.count(); got != tc.want { + t.Errorf("relaunch requests = %d, want %d", got, tc.want) + } + if got := int(requestsAtWait.Load()); got != tc.want { + t.Errorf("relaunch requests before WaitAlive = %d, want %d", got, tc.want) + } + }) + } +} diff --git a/internal/progress/progress.go b/internal/progress/progress.go index 4aa4623..697276c 100644 --- a/internal/progress/progress.go +++ b/internal/progress/progress.go @@ -220,6 +220,13 @@ type Manager interface { // While active, Sink.OnFileStart does not grow bytes_total. SeedDownloadBudget(total, completed int64) + // SeedCachedBytes counts bytes already on disk when the pass total is + // unknown: bytes_completed and bytes_total both start at bytes, and + // nothing is pinned, so OnFileStart still adds each file that + // transfers. A file already on disk never starts, so seeding + // bytes_completed alone would end the pass above 100%. + SeedCachedBytes(bytes int64) + // SeedDownloadFiles pins files_total and optional files_completed // (finished HF snapshot files) for a multi-file pass. While active, // OnFileStart does not grow files_total. OnFilesTotal never shrinks @@ -326,6 +333,8 @@ type memoryManager struct { // bytesBudgetActive: OnFileStart must not add to BytesTotal (set by // SeedDownloadBudget for multi-file passes). bytesBudgetActive bool + // overrunLogged keeps addCompleted to one warning per pinned pass. + overrunLogged bool // filesBudgetActive: OnFileStart must not raise FilesTotal // (set only by SeedDownloadFiles). OnFilesTotal never sets this: // a CLI "Fetching N files" is one batch, not the whole pass. @@ -483,10 +492,26 @@ func (m *memoryManager) SeedDownloadBudget(total, completed int64) { }) m.mu.Lock() m.bytesBudgetActive = total > 0 + m.overrunLogged = false m.lastBytes = completed m.mu.Unlock() } +func (m *memoryManager) SeedCachedBytes(bytes int64) { + if bytes < 0 { + bytes = 0 + } + m.Update(func(st *State) { + st.BytesTotal = bytes + st.BytesCompleted = bytes + }) + m.mu.Lock() + m.bytesBudgetActive = false + m.overrunLogged = false + m.lastBytes = bytes + m.mu.Unlock() +} + func (m *memoryManager) SeedDownloadFileList(files []FileProgress) { cloned := make([]FileProgress, len(files)) done := 0 @@ -540,6 +565,7 @@ func (m *memoryManager) SeedDownloadFiles(total, completed int) { func (m *memoryManager) ClearDownloadBudget() { m.mu.Lock() m.bytesBudgetActive = false + m.overrunLogged = false m.filesBudgetActive = false m.seenFiles = make(map[string]struct{}) m.doneFiles = make(map[string]struct{}) diff --git a/internal/progress/sink.go b/internal/progress/sink.go index b665ed0..8956c70 100644 --- a/internal/progress/sink.go +++ b/internal/progress/sink.go @@ -1,5 +1,7 @@ package progress +import "log/slog" + // Sink is the producer-facing interface used by fetch and adapter packages. // // Implementations route events into a Manager (typical) or aggregate child @@ -85,7 +87,7 @@ func (s *managerSink) OnBytes(delta int64) { pinned := s.m.filesBudgetActive s.m.mu.Unlock() s.m.Update(func(st *State) { - st.BytesCompleted += delta + s.m.addCompleted(st, delta) if st.CurrentFile != "" { addFileBytes(st, st.CurrentFile, delta, !pinned) } @@ -104,7 +106,7 @@ func (s *managerSink) OnFileBytes(path string, delta int64) { s.m.mu.Unlock() s.m.Update(func(st *State) { if delta != 0 { - st.BytesCompleted += delta + s.m.addCompleted(st, delta) } if path != "" { st.CurrentFile = path @@ -113,6 +115,24 @@ func (s *managerSink) OnFileBytes(path string, delta int64) { }) } +// addCompleted moves BytesCompleted by delta. Once SeedDownloadBudget has +// pinned the total it covers the whole pass, so a count past it is a +// producer miscounting: it is capped, and logged once per pass. Must be +// called under m.mu, which Update holds while running its callback. +func (m *memoryManager) addCompleted(st *State, delta int64) { + st.BytesCompleted += delta + if !m.bytesBudgetActive || st.BytesTotal <= 0 || st.BytesCompleted <= st.BytesTotal { + return + } + if !m.overrunLogged { + m.overrunLogged = true + slog.Warn("download progress ran past the pinned total; capping it", + slog.Int64("bytes_completed", st.BytesCompleted), + slog.Int64("bytes_total", st.BytesTotal)) + } + st.BytesCompleted = st.BytesTotal +} + func (s *managerSink) OnFileDone(path string) { if path != "" { s.m.mu.Lock() diff --git a/internal/progress/sink_budget_test.go b/internal/progress/sink_budget_test.go index b1adb4e..c879acd 100644 --- a/internal/progress/sink_budget_test.go +++ b/internal/progress/sink_budget_test.go @@ -21,6 +21,29 @@ func TestSeedDownloadBudget_OnFileStartIgnored(t *testing.T) { } } +func TestSeedDownloadBudget_CapsCompletedAtTotal(t *testing.T) { + t.Parallel() + m := New(time.Now()).(*memoryManager) + m.SeedDownloadBudget(1000, 900) + sink := m.Sink() + sink.OnBytes(300) + if got := m.Snapshot().BytesCompleted; got != 1000 { + t.Errorf("OnBytes: BytesCompleted = %d, want capped at 1000", got) + } + sink.(FileByteSink).OnFileBytes("a", 500) + if got := m.Snapshot().BytesCompleted; got != 1000 { + t.Errorf("OnFileBytes: BytesCompleted = %d, want capped at 1000", got) + } + + // Without a pinned total the stream is the only measure there is. + m.ClearDownloadBudget() + m.Update(func(st *State) { st.BytesTotal, st.BytesCompleted = 100, 100 }) + sink.OnBytes(50) + if got := m.Snapshot().BytesCompleted; got != 150 { + t.Errorf("unpinned: BytesCompleted = %d, want 150", got) + } +} + func TestClearDownloadBudget_RestoresOnFileStart(t *testing.T) { t.Parallel() m := New(time.Now()).(*memoryManager) diff --git a/tests/download/harness_test.go b/tests/download/harness_test.go index f45ad78..aad2301 100644 --- a/tests/download/harness_test.go +++ b/tests/download/harness_test.go @@ -125,6 +125,9 @@ func startManager(t *testing.T, opts lifecycle.Options) *rig { if opts.RetriableBackoff == 0 { opts.RetriableBackoff = 30 * time.Millisecond } + if opts.HFResolveBackoff == 0 { + opts.HFResolveBackoff = time.Millisecond + } if opts.HealthInterval == 0 { opts.HealthInterval = time.Hour } diff --git a/tests/download/hf_test.go b/tests/download/hf_test.go index 2241f7b..f913b6b 100644 --- a/tests/download/hf_test.go +++ b/tests/download/hf_test.go @@ -334,10 +334,11 @@ func TestHF_Subprocess_DuplicateBasenameProgress(t *testing.T) { } st := mgr.Snapshot() - // tqdm's three significant digits round both totals up; what matters + // tqdm's three significant digits round both totals up past the + // pinned budget, which caps the sum at the Hub's total; what matters // is that the second file contributed at all. It used to contribute // nothing, leaving this at 8480000000. - if want := int64(8480000000 + 3780000000); st.BytesCompleted != want { + if want := instructSize + redaeSize; st.BytesCompleted != want { t.Errorf("bytes_completed = %d, want %d", st.BytesCompleted, want) } if st.FilesCompleted != 2 {