Hub: reuse commit trees, ask for SHAs only, stream the model card
- listFiles() keeps the last trees it fetched by repo@SHA (a commit's files never change; capped at 50,000 files): adding a model right after the lookup no longer downloads the whole tree again. Callers get copies. - addModel() fetches the author's avatar in parallel with the file list. - The Hub check resolves revisions with resolveRevision(): /revision/<rev> with expand=sha, as huggingface_hub's model_info(expand=...) does, instead of the full model info (file list, card data, the Spaces using the model). Falls back to the full request if an answer comes without a SHA. - The Model card tab renders inside <Suspense>: the page no longer waits for the README to arrive from the Hub (up to the 20 s timeout when it's slow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
7 files changed
+189
-34
No files matched your search
@@ -30,6 +30,10 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
every found folder's file list each time, every 2 minutes by default), and download progress
|
||||
no longer re-checks files that are already complete, which matters on network shares. A
|
||||
benchmark's current step is written when it changes, not for every line BetterBench prints.
|
||||
- **Fewer and smaller Hugging Face requests**: adding a model right after looking it up reuses the
|
||||
file list it just fetched (a commit's files never change), the author's avatar loads alongside,
|
||||
and the regular Hub check asks only for the commit SHA instead of the full model info.
|
||||
- The **Model card** tab shows the page at once and the card when it arrives from the Hub.
|
||||
|
||||
## [0.16.0] - 2026-10-30
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import "server-only";
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { shortSha } from "@/lib/format";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
|
||||
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
|
||||
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
|
||||
@@ -17,6 +22,55 @@ const schema = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The Model card tab: the README at the pinned commit, fetched from the Hub (cached per commit).
|
||||
* Rendered inside a Suspense boundary, so the rest of the page doesn't wait for the Hub.
|
||||
*/
|
||||
export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: string }) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
const card = await fetchModelCard(repoId, sha).catch(() => undefined);
|
||||
if (!card) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={repoId} sha={sha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${sha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(sha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelCardSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading the model card">
|
||||
<Skeleton className="h-7 w-2/5" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-11/12" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
<Skeleton className="mt-3 h-5 w-1/4" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
|
||||
const base = `https://huggingface.co/${repoId}`;
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
ArrowDownIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
@@ -27,7 +27,6 @@ import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { targetName } from "@/lib/benchmark-view";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModelByRepo, relatedModels } from "@/lib/library";
|
||||
@@ -39,7 +38,7 @@ import { DownloadCard } from "./download-card";
|
||||
import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
@@ -101,10 +100,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const hubTags = model.hubTags ?? [];
|
||||
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
|
||||
|
||||
const [tags, related, card, worker, recentJobs, runs] = await Promise.all([
|
||||
// The model card (a Hub request) isn't awaited here: it streams in behind its Suspense boundary.
|
||||
const [tags, related, worker, recentJobs, runs] = await Promise.all([
|
||||
modelTagList(model.id),
|
||||
relatedModels(model.id, baseModels),
|
||||
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
|
||||
getWorkerStatus(),
|
||||
listModelJobs(model.id, 1),
|
||||
listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all
|
||||
@@ -253,29 +252,9 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
{tab === "card" && (
|
||||
<div className="p-5 sm:p-6">
|
||||
{card ? (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${model.pinnedSha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(model.pinnedSha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
</Suspense>
|
||||
</div>
|
||||
)}
|
||||
{tab === "files" && (
|
||||
|
||||
@@ -6,7 +6,7 @@ import { and, asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema";
|
||||
import { computeUpdateDiff } from "@/lib/update-diff";
|
||||
import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
|
||||
import { HubError, listFiles, resolveRevision, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
@@ -45,7 +45,7 @@ const isGated = (err: unknown) => err instanceof HubError && (err.code === "gate
|
||||
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
|
||||
async function resolve(repoId: string, revision: string): Promise<string | null> {
|
||||
try {
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
return await resolveRevision(repoId, revision);
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "revision_not_found") return null;
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Hub client: the per-commit tree cache and the SHA-only revision lookup, against a stubbed fetch.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { after, beforeEach, describe, it } from "node:test";
|
||||
import { HubError, listFiles, resolveRevision } from "./client";
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
let requests: string[] = [];
|
||||
let respond: (url: string) => Response;
|
||||
|
||||
const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });
|
||||
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
requests.push(url);
|
||||
return respond(url);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
const SHA = "a".repeat(40);
|
||||
const tree = [
|
||||
{ type: "file", path: "b.gguf", size: 2, oid: "o2" },
|
||||
{ type: "directory", path: "sub", size: 0, oid: "d" },
|
||||
{ type: "file", path: "a.gguf", size: 1, oid: "o1", lfs: { oid: "f".repeat(64), size: 1 } },
|
||||
];
|
||||
|
||||
describe("listFiles", () => {
|
||||
it("downloads a commit's tree once and hands out copies", async () => {
|
||||
respond = () => json(tree);
|
||||
const first = await listFiles("org/cached", SHA);
|
||||
assert.deepEqual(first.map((f) => f.path), ["a.gguf", "b.gguf"]);
|
||||
first.pop();
|
||||
const second = await listFiles("org/cached", SHA);
|
||||
assert.equal(second.length, 2, "the cached list isn't changed by callers");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
|
||||
it("doesn't cache a branch name (it can move)", async () => {
|
||||
respond = () => json(tree);
|
||||
await listFiles("org/branch", "main");
|
||||
await listFiles("org/branch", "main");
|
||||
assert.equal(requests.length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveRevision", () => {
|
||||
it("asks only for the SHA", async () => {
|
||||
respond = () => json({ _id: "x", id: "org/repo", sha: SHA });
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, ["https://huggingface.co/api/models/org/repo/revision/main?expand=sha"]);
|
||||
});
|
||||
|
||||
it("falls back to the full model info when the answer has no SHA", async () => {
|
||||
respond = (url) => (url.endsWith("?expand=sha") ? json({ id: "org/repo" }) : json({ id: "org/repo", sha: SHA }));
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, [
|
||||
"https://huggingface.co/api/models/org/repo/revision/main?expand=sha",
|
||||
"https://huggingface.co/api/models/org/repo/revision/main",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a missing repo or revision like the full lookup", async () => {
|
||||
respond = () => json({ error: "nope" }, 404, { "x-error-code": "RevisionNotFound" });
|
||||
await assert.rejects(resolveRevision("org/repo", "gone"), (err) => err instanceof HubError && err.code === "revision_not_found");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
});
|
||||
+45
-2
@@ -160,9 +160,50 @@ type TreeEntry = {
|
||||
xetHash?: string;
|
||||
};
|
||||
|
||||
/** All files (recursive) at a commit. Follows the Link header for pagination. */
|
||||
/**
|
||||
* The commit a revision points to. Asks the Hub for just the SHA (`expand=sha`, as huggingface_hub's
|
||||
* model_info does): the full model info can be large (file list, card data, the Spaces using it).
|
||||
* Falls back to the full info if an answer comes without a SHA.
|
||||
*/
|
||||
export async function resolveRevision(repoId: string, revision: string): Promise<string> {
|
||||
assertRepoId(repoId);
|
||||
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}?expand=sha`);
|
||||
if (res.ok) {
|
||||
const j = (await res.json().catch(() => null)) as { sha?: unknown } | null;
|
||||
if (typeof j?.sha === "string" && SHA_RE.test(j.sha)) return j.sha;
|
||||
} else if (res.status !== 400) {
|
||||
throw await toHubError(res, repoId, revision);
|
||||
}
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
}
|
||||
|
||||
// A commit's file list never changes, so the last few are kept: adding a model right after looking
|
||||
// it up doesn't download its tree again. Capped by the number of files held.
|
||||
const treeCache = new Map<string, HubFile[]>();
|
||||
const TREE_CACHE_MAX_FILES = 50_000;
|
||||
let treeCacheFiles = 0;
|
||||
|
||||
function rememberTree(key: string, files: HubFile[]) {
|
||||
if (files.length > TREE_CACHE_MAX_FILES) return;
|
||||
treeCache.set(key, files);
|
||||
treeCacheFiles += files.length;
|
||||
for (const [k, v] of treeCache) {
|
||||
if (treeCacheFiles <= TREE_CACHE_MAX_FILES) break;
|
||||
treeCache.delete(k);
|
||||
treeCacheFiles -= v.length;
|
||||
}
|
||||
}
|
||||
|
||||
/** All files (recursive) at a commit, sorted by path. Follows the Link header for pagination. */
|
||||
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
|
||||
assertRepoId(repoId);
|
||||
const key = `${repoId}@${sha}`;
|
||||
const cached = treeCache.get(key);
|
||||
if (cached) {
|
||||
treeCache.delete(key); // most recently used last
|
||||
treeCache.set(key, cached);
|
||||
return [...cached];
|
||||
}
|
||||
const files: HubFile[] = [];
|
||||
let url: string | null =
|
||||
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
|
||||
@@ -181,7 +222,9 @@ export async function listFiles(repoId: string, sha: string): Promise<HubFile[]>
|
||||
}
|
||||
url = nextLink(res.headers.get("link"));
|
||||
}
|
||||
return files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
if (SHA_RE.test(sha)) rememberTree(key, files);
|
||||
return [...files];
|
||||
}
|
||||
|
||||
function nextLink(link: string | null): string | null {
|
||||
|
||||
+3
-2
@@ -51,7 +51,8 @@ export async function addModel(input: {
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
|
||||
|
||||
const files = await listFiles(repoId, info.sha);
|
||||
// Independent: the author's avatar loads while the file list does (usually cached from the lookup).
|
||||
const [files, avatar] = await Promise.all([listFiles(repoId, info.sha), getAuthorAvatar(repoId.split("/")[0])]);
|
||||
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
|
||||
if (selectedFiles.length === 0) {
|
||||
throw new ModelError("empty_selection", "No files selected.", 400);
|
||||
@@ -81,7 +82,7 @@ export async function addModel(input: {
|
||||
localPath,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
|
||||
...metadataColumns(info.metadata, avatar),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
|
||||
Reference in new issue
Block a user