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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<revision>` 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/<that commit>/<path>` or `blobs/<id>` (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/<revision>` 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/<revision>`
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
Expand Down
1 change: 1 addition & 0 deletions cmd/llm-init/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions internal/adapter/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
177 changes: 172 additions & 5 deletions internal/adapter/hfwrap/estimate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package hfwrap
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
Expand All @@ -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
Expand Down Expand Up @@ -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/<revision> 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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
Expand All @@ -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"`
Expand Down
Loading
Loading