diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index 7d2b2faa..15980ed5 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -374,13 +374,23 @@ def collect_engine_info(): slim = {k: info.get(k) for k in kept} for f in MASKED_FIELDS: slim.pop(f, None) + # Which switch target these weights are: the selector must show what is serving, + # not the first option in the list. Derived from the registry pins, so a new pin + # is a new target with no extra table to keep in step. + var2target = {"STOCK_REV": "stock", "UNC_REV": "uncensored", "FP8_REV": "fp8", "FLASH_REV": "flash"} + served_target = None + for var, repo in rg.PIN_MODELS.items(): + if repo == slim.get("model_path") and var in var2target: + served_target = var2target[var] + break # the proxy's absolute prompt ceiling, as deployed in the keepalive unit (0 = pool share only) ceiling = 0 env = run(["systemctl", "show", "qwen38-keepalive.service", "-p", "Environment"], timeout=5) m = re.search(r"PROMPT_CEILING_TOKENS=(\d+)", env or "") if m: ceiling = int(m.group(1)) - return {"node_id": "local", "info": slim, "prompt_ceiling_tokens": ceiling} + return {"node_id": "local", "info": slim, "prompt_ceiling_tokens": ceiling, + "served_target": served_target} CANARY: dict = {"fails": 0, "last_ok": None, "last_err": "", "latency": None} @@ -527,6 +537,30 @@ def collect_opencode(): ok, why = lc.opencode_default_follows(out["real"]["default"], states) out["follows"] = ok out["why"] = why + # Do the declared limits fit the pool the engine actually booted with? A limit + # larger than the pool does not fail early: the conversation grows until the + # proxy refuses a prompt mid-session. + with STATE_LOCK: + info = ((STATE.get("engine_info") or {}).get("data") or {}).get("info") or {} + pool = int(info.get("max_total_num_tokens") or 0) + served = info.get("served_model_name") or "" + out["fit"] = None + if pool and served: + prov = {"qwen3.8-27b": "qwen38", "qwen3.8-flash-next": "flashnext"}.get(served) + lim = (out["real"]["limits"] or {}).get(f"{prov}/{served}") if prov else None + if lim and lim.get("context"): + ctx, outp = int(lim["context"]), int(lim.get("output") or 0) + usable = int(pool * USABLE_FRAC) + # two independent constraints: the prompt alone must pass the proxy (which + # also applies the lane's absolute ceiling), and prompt plus answer must fit + # the pool. The flash lane fails only the first, the FP8 lane only the second. + ceiling = ((STATE.get("engine_info") or {}).get("data") or {}).get("prompt_ceiling_tokens") or 0 + prompt_cap = min(usable, ceiling) if ceiling else usable + why = ("the prompt alone exceeds what the proxy relays" if ctx > prompt_cap + else "prompt plus answer exceeds the pool" if ctx + outp > usable else "") + out["fit"] = {"pool": pool, "worst": ctx + outp, "usable": usable, "served": served, + "prompt_cap": prompt_cap, "ok": not why, "why": why, + "context": ctx, "output": outp} return out @@ -852,7 +886,7 @@ ACTIONS = { # model switch (repo script, itself never restarts anything) "switch": { "danger": "medium", - "params": {"target": ["stock", "uncensored", "flash"]}, + "params": {"target": ["stock", "uncensored", "fp8", "flash"]}, "argv": lambda p: ["bash", str(REPO_DIR / "switch-model.sh"), p["target"]], "timeout": 1800, }, @@ -874,6 +908,13 @@ ACTIONS = { "argv": None, "timeout": 10, }, + # make opencode ask for no more than the served engine can hold + "fit_opencode": { + "danger": "low", + "params": {}, + "argv": lambda p: ["python3", str(REPO_DIR / "oc-fit-limits.py")], + "timeout": 60, + }, # diagnostics bundle for issue reports (logs, state, versions; key masked) "diag_bundle": { "danger": "low", @@ -1362,7 +1403,8 @@ class Handler(http.server.BaseHTTPRequestHandler): # ---- routes ---- def do_GET(self): - path = self.path.split("?", 1)[0] + path, _, query = self.path.partition("?") + fresh = "refresh=1" in query if path == "/api/health": return self.send_json({"ok": True, "version": VERSION}) if path == "/login" or path == "/favicon.ico" or path.startswith("/static/"): @@ -1382,17 +1424,20 @@ class Handler(http.server.BaseHTTPRequestHandler): for n, s in ACTIONS.items()}) if path == "/api/upstream": try: - return self.send_json(upstream_snapshot()) + return self.send_json(upstream_snapshot(max_age=0.0 if fresh else 3600.0)) except Exception as e: # noqa: BLE001 return self.send_json({"error": str(e)[:200]}, 500) if path == "/api/registry": try: - return self.send_json(registry_snapshot()) + # "scan" has to mean scan: the button sends refresh=1 and bypasses the cache + return self.send_json(registry_snapshot(max_age=0.0 if fresh else 300.0)) except Exception as e: # noqa: BLE001 (isolated endpoint) return self.send_json({"error": str(e)[:200]}, 500) if path == "/api/recipes": try: - return self.send_json(recipes_snapshot()) + if fresh: + registry_snapshot(max_age=0.0) # recipes read the registry for presence + return self.send_json(recipes_snapshot(max_age=0.0 if fresh else 60.0)) except Exception as e: # noqa: BLE001 (isolated endpoint) return self.send_json({"error": str(e)[:200]}, 500) if path == "/api/inventory": diff --git a/dashboard/recipes.py b/dashboard/recipes.py index 152ca566..a36a0d44 100644 --- a/dashboard/recipes.py +++ b/dashboard/recipes.py @@ -51,7 +51,7 @@ DRAFT_FLAGS = { "steps": ("--speculative-num-steps", int), "draft_tokens": ("--speculative-num-draft-tokens", int), } -BUILTIN_IDS = ("stock", "uncensored", "flash") +BUILTIN_IDS = ("stock", "uncensored", "fp8", "flash") def parse_assignments(text: str) -> dict[str, str]: @@ -121,7 +121,7 @@ def builtin(recipe_id: str, assigns: dict[str, str], templates: dict[str, str]) base = assigns.get("FLASH_IMAGE") overlay = "flash-sglang" else: - pfx = "STOCK" if recipe_id == "stock" else "UNC" + pfx = {"stock": "STOCK", "uncensored": "UNC", "fp8": "FP8"}[recipe_id] repo, rev, image = assigns[f"{pfx}_REPO"], assigns[f"{pfx}_REV"], assigns["SERVE_IMAGE"] base = None overlay = "dflash2" @@ -248,18 +248,24 @@ def presence(recipe: dict, registry: dict) -> dict: from the registry (model outside the managed set).""" images = {i.get("ref") for i in registry.get("images", [])} known: dict[str, set] = {} + busy: set = set() for m in registry.get("models", []): known.setdefault(m["repo_id"], set()).update(r["rev"] for r in m.get("revisions", [])) + if m.get("incomplete"): + busy.add(m["repo_id"]) def cached(repo, rev): if repo is None: return None if repo not in known: return None + if repo in busy: + return False # a snapshot with blobs still arriving is not servable return rev in known[repo] dr = recipe.get("drafter", {}) return {"image": recipe["engine"].get("image") in images, + "downloading": recipe["model"].get("repo") in busy, "model": cached(recipe["model"].get("repo"), recipe["model"].get("revision")), "drafter": cached(dr.get("repo"), dr.get("revision")) if dr.get("algorithm") == "DFLASH" else None} diff --git a/dashboard/registry.py b/dashboard/registry.py index 7e1dbf33..c6b6a5e2 100644 --- a/dashboard/registry.py +++ b/dashboard/registry.py @@ -15,6 +15,7 @@ from pathlib import Path PIN_MODELS = { "STOCK_REV": "RadixArk/Qwen3.8-27B-NVFP4", "UNC_REV": "edp1096/Huihui-RadixArk-Qwen3.8-27B-abliterated-NVFP4", + "FP8_REV": "Qwen/Qwen3.8-27B-FP8", "FLASH_REV": "RadixArk/Qwen3.8-Flash-Next-NVFP4", "DRAFT_REV": "RadixArk/Qwen3.8-27B-DSpark", "DRAFT2_REV": "z-lab/Qwen3.8-27B-DFlash2", @@ -58,9 +59,16 @@ def scan_hf_cache(root: Path) -> list[dict]: repo_id = d.name[len("models--"):].replace("--", "/") seen: set[int] = set() disk = 0 + incomplete = 0 blobs = d / "blobs" if blobs.is_dir(): for f in blobs.iterdir(): + # huggingface_hub writes .incomplete while a blob is still + # arriving: a snapshot directory exists long before it is usable, + # so its mere presence must never be read as "the model is here". + if f.name.endswith(".incomplete"): + incomplete += 1 + continue try: st = f.stat() except OSError: @@ -82,7 +90,7 @@ def scan_hf_cache(root: Path) -> list[dict]: pass revs.append({"rev": rd.name, "bytes": size}) out.append({"repo_id": repo_id, "disk_bytes": disk, - "revisions": revs}) + "incomplete": incomplete, "revisions": revs}) return out diff --git a/dashboard/static/app.js b/dashboard/static/app.js index d99d8a67..0c81cb6a 100644 --- a/dashboard/static/app.js +++ b/dashboard/static/app.js @@ -124,6 +124,10 @@ function rGpu(d){ } function rEngineInfo(d){ if (d.prompt_ceiling_tokens != null) F.ceiling = d.prompt_ceiling_tokens; + // the selector shows what is serving, so "Switch" always reads as a change + F.target = d.served_target || null; + const sel = $('switchsel'); + if (sel && F.target && !sel.dataset.touched && sel.value !== F.target) sel.value = F.target; const i = d.info || {}; setText('engmodel', (i.model_path || '...').split('/').pop()); setText('engrev', (i.revision || '').slice(0, 12) || 'n/a'); @@ -307,6 +311,7 @@ function rFeed(d){ if (!rows.length){ const tr = tb.insertRow(); const c = tr.insertCell(); c.colSpan = 6; c.className = 'empty'; c.textContent = 'no request has gone through the proxy yet (agent clients use :30001)'; } } function rOpencode(d){ + F.ocfit = d.fit || null; const fmtLim = l => l && l.context ? `${fmtN(l.context)} ctx / ${fmtN(l.output || 0)} out` : 'not declared'; setText('oclim27', fmtLim(d.real.limits['qwen38/qwen3.8-27b'])); setText('oclimflash', fmtLim(d.real.limits['flashnext/qwen3.8-flash-next'])); if (!d.enabled){ @@ -326,6 +331,11 @@ function rOpencode(d){ setText('oclauncher', d.launcher.present ? (d.launcher.ours ? `oc, output cap ${d.launcher.cap ? fmtN(d.launcher.cap) : '?'}` : 'a foreign oc command, launcher not installed') : 'missing (re-run ./install.sh)'); + const f = d.fit; + setText('ocfit', !f ? 'unknown until an engine is serving' + : f.ok ? `fits: prompt up to ${fmtN(f.context)} of ${fmtN(f.prompt_cap)}, worst case ${fmtN(f.worst)} of ${fmtN(f.usable)}` + : `too large: ${f.why} (${fmtN(f.worst)} asked, ${fmtN(f.usable)} servable)`); + const fe = $('ocfit'); if (fe) fe.style.color = f && !f.ok ? 'var(--warn)' : ''; $('occmd').hidden = false; setText('ocnote', 'One command: the launcher lifts the output cap and auto-approves permissions. The default model follows every switch; existing sessions keep the model they started with.'); badge('setup', ok === false ? 'opencode' : '', 'warn'); @@ -365,8 +375,10 @@ function rLanePill(){ return; } const [name, e] = s; + const TARGET_SHORT = {stock: 'stock', uncensored: 'uncensored', fp8: 'FP8', flash: ''}; setChip('lanestate', STATE_LABEL[e.state] || e.state, stateChipCls(e.state)); - setText('lanename', LANE_NAME[name] || name); + const t = F.target && TARGET_SHORT[F.target] ? ' ' + TARGET_SHORT[F.target] : ''; + setText('lanename', (LANE_NAME[name] || name) + t); const l = F.load || {}; let sub = ''; if (e.state === 'ready' || e.state === 'degraded'){ @@ -675,6 +687,9 @@ function banners(state, errors){ }); if (F.memFloor && F.memFloor.aborts && F.memFloor.last_abort && Date.now() / 1000 - F.memFloor.last_abort < 600) add('warn', 'Memory floor fired.', `Host memory fell under ${F.memFloor.gib} GiB with requests running: every generation was aborted ${fmtDur(Date.now() / 1000 - F.memFloor.last_abort)} ago to keep the box out of a livelock.`); + const ocf = F.ocfit; + if (ocf && !ocf.ok) add('warn', 'opencode asks for more than this engine can hold.', + `${ocf.why} (${fmtN(ocf.worst)} asked, ${fmtN(ocf.usable)} servable on ${ocf.served}): the session would break mid-conversation when the proxy refuses the prompt. Setup tab, "Fit the limits to this engine".`); ((F.life || {}).orphans || []).forEach(o => add('warn', `${LANE_NAME[o.unit] || o.unit} is running outside systemd.`, `The container ${o.container} is serving${o.image ? ` from ${o.image}` : ''}, but its unit is stopped, so the buttons here cannot manage it and a reboot will not bring it back. Stop it from a terminal (docker rm -f ${o.container}) and start the unit instead.`)); @@ -732,14 +747,27 @@ function askAction(name, params, argv, warns){ if (NEEDS_ENGINE.has(name) && !servingReady()){ toast('No engine is serving: start one first, then this action has something to talk to.', 'warn'); return; } if (F.job && F.job.current){ toast(`Another action is running (${F.job.current.action}). Wait for the job strip to finish.`, 'warn'); return; } if (!$('modal').hidden) return; - const TITLES = {unit: p => `${p.verb} ${LANE_NAME[p.unit] || p.unit.replace('.service', '')}`, switch: p => `switch the target model to ${p.target}`, + const TARGET_NAME = {stock: 'stock 27B (NVFP4)', uncensored: 'uncensored 27B (NVFP4)', + fp8: 'FP8 27B (Qwen official)', flash: 'flash 176B'}; + const TARGET_NOTE = { + fp8: 'Qwen\u2019s own FP8 release: the most faithful weights of this lane, and the heaviest. ' + + '30.9 GB against 21 GB for NVFP4, and SGLang takes that out of the KV pool: expect around ' + + '200,000 fewer tokens of context and a slower decode, because this box is bandwidth bound. ' + + 'The first switch downloads about 31 GB.', + stock: 'The NVFP4 quantization this repo pins by default: smallest and fastest of the 27B targets.', + uncensored: 'The abliterated NVFP4 checkpoint: same size and speed as stock, refusals removed.', + flash: 'The 176B Flash-Next lane. It has its own unit, its own image and its own 48 GB PLE table.'}; + const TITLES = {unit: p => `${p.verb} ${LANE_NAME[p.unit] || p.unit.replace('.service', '')}`, + switch: p => `switch the target model to ${TARGET_NAME[p.target] || p.target}`, flush_cache: () => 'flush the engine cache', abort_all: () => 'abort every in-flight generation', smoke: () => 'run a smoke generation through the proxy', diag_bundle: () => 'write a diagnostics bundle'}; const EXPLAIN = {unit: p => p.verb === 'stop' ? 'systemd stops the unit; the container gets SIGTERM and disappears in seconds.' : 'systemd starts the unit; the engine loads its weights and is ready in about 9 minutes (watch the boot bar).', - switch: () => 'switch-model.sh rewrites the unit for the chosen target, updates the boot enablement, the proxy ceiling and the opencode default model. It never restarts anything: stop and start the engines afterwards.', + switch: p => (TARGET_NOTE[p.target] ? TARGET_NOTE[p.target] + '\n\n' : '') + + 'switch-model.sh rewrites the unit for the chosen target, updates the boot enablement, the proxy ceiling and the opencode default model. It never restarts anything: stop and start the engines afterwards.', flush_cache: () => 'Empties the radix cache. Harmless; refused by the engine if requests are running.', abort_all: () => 'Every running or queued generation ends now; the clients see their stream end.', smoke: () => 'One real 200-token generation through the proxy, the way a client uses it (up to a few minutes while a boot finishes).', - diag_bundle: () => 'Collects logs, state and versions into a tarball in your home; the API key is masked everywhere.'}; + diag_bundle: () => 'Collects logs, state and versions into a tarball in your home; the API key is masked everywhere.', + fit_opencode: () => 'Reads the KV pool of the engine that is serving right now and rewrites only opencode\u2019s context and output limits so a conversation can never outgrow it. Your other opencode settings, providers and the default model are untouched, and a dated backup is written first. Restart opencode to pick the new limits up.'}; $('mtitle').textContent = 'Confirm: ' + (TITLES[name] ? TITLES[name](params) : name); $('mwhat').textContent = (EXPLAIN[name] ? EXPLAIN[name](params) : '') + (F.config.dry_run ? '\nDry run: nothing will really be executed.' : ''); const w = $('mwarn'); w.hidden = !(warns && warns.length); w.textContent = (warns || []).map(x => '⚠ ' + x).join('\n'); @@ -776,6 +804,7 @@ $('mgo').addEventListener('click', async () => { }catch(e){ $('mstatus').textContent = 'request failed: ' + e.message; } finally{ inflight = false; $('mgo').disabled = false; $('mcancel').disabled = false; } }); +$('switchsel').addEventListener('change', e => { e.target.dataset.touched = '1'; }); document.querySelectorAll('.actbar [data-act]').forEach(b => { const act = b.dataset.act; if (act === 'lane') return; b.addEventListener('click', () => { @@ -811,7 +840,10 @@ function recipeRow(tb, row){ tr.insertCell().textContent = d.algorithm === 'none' || !d.algorithm ? 'none' : d.algorithm + (d.repo ? ' ' + d.repo.split('/').pop() : ' (own head)') + (d.draft_tokens ? ' ×' + d.draft_tokens : ''); tr.insertCell().textContent = fmtServe(r.serve || {}); const p = row.presence || {}; - cellChips(tr, [['image', p.image], ['model', p.model], ['drafter', p.drafter]].map(([k, v]) => [v === true ? k : v === false ? k + ' missing' : k + ' n/a', v === true ? 'ok' : v === false ? 'err' : ''])); + const cells = [['image', p.image], ['model', p.model], ['drafter', p.drafter]].map(([k, v]) => + [v === true ? k : v === false ? k + ' missing' : k + ' n/a', v === true ? 'ok' : v === false ? 'err' : '']); + if (p.downloading) cells[1] = ['model downloading', 'warn']; // blobs still arriving + cellChips(tr, cells); const cd = tr.insertCell(); if (row.drift == null) cd.append(chip('lane not installed')); else if (!row.drift.length) cd.append(chip('matches installed', 'ok')); @@ -825,7 +857,7 @@ function recipeRow(tb, row){ async function loadRecipes(){ $('rcpbtn').textContent = 'loading…'; $('rcpbtn').disabled = true; try{ - const r = await fetch('/api/recipes'); if (r.status === 401) return login(); + const r = await fetch('/api/recipes?refresh=1'); if (r.status === 401) return login(); if (!r.ok) throw new Error('HTTP ' + r.status); const d = await r.json(); loaded.recipes = true; const tb = $('rcptable').tBodies[0]; clear(tb); @@ -844,7 +876,7 @@ const fmtGiB = b => (b / 1024 ** 3).toFixed(1) + ' GiB'; $('regbtn').addEventListener('click', async () => { const b = $('regbtn'); b.textContent = 'scanning…'; b.disabled = true; try{ - const r = await fetch('/api/registry'); if (r.status === 401) return login(); if (!r.ok) throw new Error('HTTP ' + r.status); + const r = await fetch('/api/registry?refresh=1'); if (r.status === 401) return login(); if (!r.ok) throw new Error('HTTP ' + r.status); const d = await r.json(); const tb = $('regmodels').tBodies[0]; clear(tb); (d.models || []).forEach(m => (m.revisions || []).forEach((rv, i) => { @@ -871,7 +903,7 @@ $('regbtn').addEventListener('click', async () => { $('upbtn').addEventListener('click', async () => { const b = $('upbtn'); b.textContent = 'checking…'; b.disabled = true; try{ - const r = await fetch('/api/upstream'); if (r.status === 401) return login(); if (!r.ok) throw new Error('HTTP ' + r.status); + const r = await fetch('/api/upstream?refresh=1'); if (r.status === 401) return login(); if (!r.ok) throw new Error('HTTP ' + r.status); const d = await r.json(); const tb = $('uptable').tBodies[0]; clear(tb); (d.models || []).forEach(m => { diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 63cdcb19..bc78392f 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -259,8 +259,9 @@
@@ -552,7 +553,9 @@
Limits 27B
...
Limits flash
...
Launcher
...
+
Limits vs the pool
...
+
oc

...

diff --git a/dashboard/tests/smoke-http.sh b/dashboard/tests/smoke-http.sh index 16d23e31..0f9cf511 100755 --- a/dashboard/tests/smoke-http.sh +++ b/dashboard/tests/smoke-http.sh @@ -24,7 +24,7 @@ ck "state avec session" 200 "$(code -b "$J" "$BASE/api/state")" ck "registry" 200 "$(code -b "$J" "$BASE/api/registry")" ck "upstream (cache)" 200 "$(code -b "$J" "$BASE/api/upstream")" ck "recipes" 200 "$(code -b "$J" "$BASE/api/recipes")" -ck "recipes: 3 builtin, flash sans derive" "3 0" "$(curl -s -b "$J" "$BASE/api/recipes" | python3 -c 'import json,sys; d=json.load(sys.stdin); f=[b for b in d["builtin"] if b["recipe"]["id"]=="flash"][0]; print(len(d["builtin"]), len(f["drift"] or []))')" +ck "recipes: 4 builtin, flash sans derive" "4 0" "$(curl -s -b "$J" "$BASE/api/recipes" | python3 -c 'import json,sys; d=json.load(sys.stdin); f=[b for b in d["builtin"] if b["recipe"]["id"]=="flash"][0]; print(len(d["builtin"]), len(f["drift"] or []))')" ck "inventory" 200 "$(code -b "$J" "$BASE/api/inventory")" ck "logs allowlist" 404 "$(code -b "$J" "$BASE/api/logs/etc-passwd")" ck "static traversal" 404 "$(code -b "$J" "$BASE/static/../cockpit.py")" diff --git a/dashboard/tests/test_recipes.py b/dashboard/tests/test_recipes.py index fae91c90..cff53ba3 100644 --- a/dashboard/tests/test_recipes.py +++ b/dashboard/tests/test_recipes.py @@ -71,14 +71,25 @@ class ProfileFromText(unittest.TestCase): class Builtins(unittest.TestCase): - def test_three_valid_recipes(self): + def test_every_builtin_recipe_is_valid(self): recs = rc.builtins(ASSIGNS, TEMPLATES) - self.assertEqual([r["id"] for r in recs], ["stock", "uncensored", "flash"]) + self.assertEqual([r["id"] for r in recs], ["stock", "uncensored", "fp8", "flash"]) for r in recs: errs = rc.validate(r) if r["lane"] == "flash" else rc.validate( {**r, "serve": {**r["serve"], "context_length": 262144}}) self.assertEqual(errs, [], r["id"]) + def test_fp8_is_the_27b_lane_with_qwens_own_checkpoint(self): + f = rc.builtin("fp8", ASSIGNS, TEMPLATES) + self.assertEqual(f["lane"], "27b") + self.assertEqual(f["model"]["repo"], ASSIGNS["FP8_REPO"]) + self.assertEqual(f["model"]["revision"], ASSIGNS["FP8_REV"]) + # same engine image and same drafter as the NVFP4 targets: only the weights differ + s = rc.builtin("stock", ASSIGNS, TEMPLATES) + self.assertEqual(f["engine"], s["engine"]) + self.assertEqual(f["drafter"], s["drafter"]) + self.assertEqual(f["serve"], s["serve"]) + def test_flash_pins_substituted(self): f = rc.builtin("flash", ASSIGNS, TEMPLATES) self.assertEqual(f["model"]["repo"], ASSIGNS["FLASH_REPO"]) @@ -183,14 +194,15 @@ class Presence(unittest.TestCase): def test_present(self): p = rc.presence(good(), self.REG) - self.assertEqual(p, {"image": True, "model": True, "drafter": None}) + self.assertEqual(p, {"image": True, "downloading": False, "model": True, "drafter": None}) def test_missing_and_unknown(self): r = good() r["engine"]["image"] = "qwen38-flash:v9" r["model"]["revision"] = "8" * 40 r["drafter"] = {"algorithm": "DFLASH", "repo": "z-lab/Qwen3.8-27B-DFlash2", "revision": "9" * 40} - self.assertEqual(rc.presence(r, self.REG), {"image": False, "model": False, "drafter": False}) + self.assertEqual(rc.presence(r, self.REG), + {"image": False, "downloading": False, "model": False, "drafter": False}) r["model"]["repo"] = "someone/else" self.assertIsNone(rc.presence(r, self.REG)["model"]) @@ -213,5 +225,29 @@ class LoadCustom(unittest.TestCase): self.assertEqual(rc.load_custom(Path("/nonexistent/dir")), []) + +class PresenceDuringDownload(unittest.TestCase): + """A snapshot directory exists long before the model can be served: while + huggingface_hub still has .incomplete blobs, presence must not say 'here'.""" + + def rec(self): + return rc.builtin("fp8", ASSIGNS, TEMPLATES) + + def reg(self, incomplete): + r = self.rec() + return {"images": [{"ref": r["engine"]["image"]}], + "models": [{"repo_id": r["model"]["repo"], "incomplete": incomplete, + "revisions": [{"rev": r["model"]["revision"]}]}]} + + def test_complete_model_is_present(self): + p = rc.presence(self.rec(), self.reg(0)) + self.assertIs(p["model"], True) + self.assertFalse(p["downloading"]) + + def test_model_with_incomplete_blobs_is_not_present(self): + p = rc.presence(self.rec(), self.reg(8)) + self.assertIs(p["model"], False) + self.assertTrue(p["downloading"]) + if __name__ == "__main__": unittest.main()